Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python QRG

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

PYTHON: QUICK REFERENCE GUIDE P YTHON : Q UICK R EFERENCE G UIDE

AE1106 Programming I TU DELFT (Updated 2011-11)

Assignment statement:
Uses simply the = sign. Expression on right side determines type of variable (this is called implicit declaration). Examples: a=4 i = i + 1

(in math this would be nonsense but it is a common statement)

Variable Types
TYPE INTEGER FLOAT STRING BOOLEAN/LOGICAL CONTAINS Whole numbers All real numbers Text Switch/condition EXAMPLES 24 -2 12.5 0.5 .5 1. 1.0 1e6 Hello world True False OPERATIONS EXAMPLES 7/3 25%4 2+3 2-3 6*4 2**3 7./3. 25.%4. 2.+3. 2.-3. 6.*4. 2.**3. Hell + o world chr(84) + chr(85) + chr(68) ord(A) a>b a<=b a==b a<>b a!=b (a==b) or (a==c) swfound and not swcorrect

Conversion of types
int(x)

converts a float to an integer (truncated), so int(3.7) is 3, int(-2.5) gives -2 float(i) to convert integer to a float variable type str(a) or repr(a) converts a number to a string, normal or resp. maximum precision eval(txt) to get the value of the content of the string (can contain variable names)

Naming of variables
Variable names can contain numbers, characters and underscore character ( _ ), Names cannot start with a number. Though not required, by convention i, j, k, l, m, n are often used of integers as well as names starting with these characters. (e.g. ncount meaning number of counts)

Page 1

PYTHON: QUICK REFERENCE GUIDE


Lists (and Tuples)
a = [5, 15, 24, -3, 7, 18, 24 , 0, 0 ,1] After this assignment then: len(a) is 10 value of a[0] is 5 value of a[9] is 1 so indices range from 0 till 9! value of a[1:4] is [15,24,-3] this is called slicing, works also on strings Adding an element can be done in two ways: with append function or with + operator. Safest way is append, especially with adding content of variables a.append(3) a.append(i) a = a+[3] b = [[3,4,5].[4,5,6]] #list of two lists c = a[3] + b[1][0] A tuple is a special list, immutable (=cannot be changed) and assignment is done with normal brackets: black = (0,0,0) green = (0,255,0) then green[1] is 255 >>>>>By default: use lists! (now with square brackets because it is an index! )

U SING

MATH FUNCTIONS

You can use math functions from the supplied math library in two ways:

M ET HO D 1:
import math a = 50.*math.pi/180. x = math.sin(a) (only once at the beginning of your program file)

M ET HO D 2:
from math import pi,sin a = 50.*pi/180 x = sin(a) Not recommended (why not?) but also possible: from math import * a = 50.*pi/180 x = sin(a)

Page 2

PYTHON: QUICK REFERENCE GUIDE


P ROGRAM
FILE LAY - OUT
A lot of time of programming is spent debugging, so make your files readable for yourself and for others. Use a lot of comment lines, they are marked with a hash character ( # ). Use the hash sign at the beginning of a comment line or at the end of a program line. You can continue on the next line with your statement by ending the line with a backslash ( \ ) as a continuation mark. Sometimes it is automatically done (in lists for example). In print statements just add a comma at the end of a line to continue on the same line with the next print statement) Use also plenty of empty lines and spaces to enhance readability as well as clear but not too long variable names. Basic statements PRINT print Hello world print The answer is ,a print Two solutions are,x1,and,x2

INPUT
Input function recognizes type of variable based on input, use raw_input() for string. a = input(Give value of a:) name = raw_input(What is your name?)

IF-statement
Use of ELSE or ELIF (else-if) is optional, always end with : to indicate start of block or statement Indenting margin determines begin and end of block! if a < b: print "a smaller than b" c=b elif a == b: print "a and b are equal" c=a else: print "a is larger than b" c=a

Page 3

PYTHON: QUICK REFERENCE GUIDE


FOR-statement For example to loop 10 times: for i in range(10): x = x + i*4 print i = ,i

range function: range(end) range(start,end) range(start,end,step) default start is zero and end is not included! Examples:

range(5) range(3,10) range(10,0,-1)

equals [0,1,2,3,4] equals [3,4,5,6,7,8,9] equals [10,9,8,7,6,5,4,3,2,1]

WHILE-statement Loop while a condition is True, note again use of semicolon and indenting:

WHILE a[i]!=b and i<len(a): i = i+1 print Checking element,i

D EFINING

AND USIN G FU NCTIONS IN SAME FILE ( OR IN SHELL ):

def faculteit(n): fac = 1 for i in range(1,n+1): fac = fac*i return fac a = input(Give number for factorial:) print Factorial ,a, = ,faculteit(a)

D EFINING

AND USIN G FU NCTIONS IN DIFFERENT FILES ( MODULES ):

In file mytools.py: def faculteit(n): fac = 1 for i in range(1,n+1): fac = fac*i return fac

Page 4

PYTHON: QUICK REFERENCE GUIDE


In file myprog.py we put the import statement in the header, the function can then be used throughout file:

import mytools f = mytools.faculteit(a) or: from mytools import faculteit f = faculteit(a)

or: from mytools import faculteit as factorial f = factorial(a)

or: import mytools.faculteit as factorial or: from mytools import *

C HECK OUT THE MANY H ELP FUNCTIONS

MODULES SUPPLIED WIT H

P YTHON

AND

There is a saying Python is free as in free beer and in free speech and it comes with batteries included. This means among other things that there is a whole list of standard modules supplied next to the basic math module.

To see which ones you have, type the following in the shell: >>>help() [welcome text interactive help] help>modules and you will see a list of modules. You can also type help(modules) or help(print) To get more information you can also access a HTML help file via the help function from the pulldown menu. In this menu you can also add links to your own help files such as to the CHM files (pronounced chum-files) for Numpy and Scipy and/or a link to the online documentation for pygame. You can also a link to for example http://www.tutorialspoint.com/python/ For scientific computing we will use the numpy, scipy and matplotlib modules. For animation and 2D visualization, as well as game programming, we will use the user-friendly pygame module.

Page 5

PYTHON: QUICK REFERENCE GUIDE


See also the file on the blackboard: tutorial.pdf which contains an extensive Python tutorial. (It is also included in the Help function.) Study these sections for block 1 of the Python course:

3.1.1 Numbers 3.1.2 Strings 3.1.4 Lists 3.2 First steps prgrmng: while

4.1 if-statement 4.2 for-statement 4.3 range() function (4.4 break, continue,else in loops) 4.6 defining functions Not 4.7!

5.2 del statement 5.3 Tuples 5.6 More on conditions

6 Modules but not 6.1.1 en 6.1.2 6.2 Standard Modules

7.2.1 Method of File Objects 10.6 math module

App B Floating Point Arithmetic: Issues and Limitations

Page 6

You might also like