You are on page 1of 8

Python examples

Maxim Tyan December 29, 2012

1
1.1

Control ow
While loop

1 a = 5 2 while a > : 3 print a 4 a = a - 1

# note : indentation is important

1.2
1 2 3 4 5 6 7

If-else conditions

a = 3 if a < : print less elif a == : # else if print equal else : print greater

1.3

Nested blocks

1 a = 2 while a <=1 : 3 if ( a % 2)==1: 4 print a # prints odd numbers 5 a += 1 # same as a = a +1

1.4

Print primes less than 1000

By denition, a number is prime if it cannot be evenly divided by anything except 1 and itself. 1

The pseudocode is simple: 1. start with 2 (since 1 is not prime) 2. loop up to 1000 3. check if the number is prime 4. if it is prime, print it
1 num = 2 2 while num <= 1 : 3 isPrime = True # assuming that number is prime 4 trial = 2 5 while trial < num : 6 if ( num % trial )== : # check if remainder is equal zero 7 isPrime = False 8 trial += 1 9 if isPrime : # same as isPrime == True 10 print num 11 num += 1

Optimized version of this code. Since number cannot be evenly divided by anything greater than its own square root.
1 num = 2 2 while num <= 1 : 3 isPrime = True 4 trial = 2 5 while trial **2 <= num : # changed line 6 if ( num % trial )== : 7 isPrime = False 8 trial += 1 9 if isPrime : 10 print num 11 num += 1

2
2.1

Lists
Simple list

One of the collection types in Python is list.


1 2 3 4 gases print print print = [ He , Ne , Ar , Kr ] # create new list gases gases [ ] # prints first element of the list gases [ -1] # prints last element of the list

2.2

length of the list

1 gases = [ He , Ne , Ar , Kr ] 2 print len ( gases ) # returns the length of the list

2.3
1 2 3 4 5

Empty list
# returns zero , because list is empty # creates new empty list . same as gases = [] # returns zero

gases = [] print len ( gases ) gases = list () print len ( gases )

2.4

Edit list values

1 gases = [ He , Ne , Ar , K ] # Kr is misspelled 2 gases [3] = Kr # element must exist before assign to it 3 print gases

Same example, but using negative index


1 gases = [ He , Ne , A , Kr ] # Ar is misspelled 2 gases [ -2] = Ar # assign to second element from the end 3 print gases

2.5
1 2 3 4 5

Store dierent type of data

# string , integer and float numbers in same list helium = [ He , 2 , 4. 26 2] argon = [ Ar , 18 , 39.948] gases = [ helium , argon ] # list of lists

2.6

For loop

Example of loop using while


1 gases = [ He , Ne , Ar , Kr ] 2 3 i = 4 while i < len ( gases ): 5 print gases [ i ] 6 i += 1

Same loop using For


1 gases = [ He , Ne , Ar , Kr ] 2 3 for gas in gases : 4 print gas

2.7
1 2 3 4 5

Delete elements

gases = [ He , Ne , Ar , Kr ] del gases [ ] # delete first element in list print gases del gases [ -1] # delete last element in list print gases

2.8
1 2 3 4

Append elements

gases = list () gases . append ( He ) gases . append ( Ar ) print gases

2.9

Useful methods of lists

Check number of duplication in list.


1 gases = [ He , He , Ar , Kr ] 2 print gases . count ( He ) # counts number of He appearances in list

Find the element index.


1 gases = [ He , Ne , Ar , Kr ] 2 # returns index of the First occurrence of Ar 3 print gases . index ( Ar )

Insert value into specic position


1 gases = [ He , He , Ar , Kr ] 2 gases . insert (1 , Ne ) 3 print gases

More useful methods:


1 2 3 4 5 gases = [ He , Ne , Ar , Kr ] gases . sort () # sorts list , note : Doesn t return any value print gases gases . reverse () # reverses list , note : Doesn t return any value print gases

Common BUG. Methods sort, reverse do not return any value.


1 gases = [ He , Ne , Ar , Kr ] 2 gases = gases . sort () # assigns NONE value to gases 3 print gases

2.10

in operator

If we need to check if variable exists in a list use in.


1 gases = [ He , Ne , Ar , Kr ] 2 print He in gases

Another example.
1 gases = [ He , Ne , Ar , Kr ] 2 if Pu in gases : 3 print But plutonium is not a gas ! 4 else : 5 print The universe is well ordered .

2.11

Range function

Use range to construct list of numbers.


1 2 3 4 5 6 7 8 9 10 11 12 # produces list of integers starting from # ( last number is not included ) print range (5) # list of integers from 2 to 5 print range (2 ,6) # list of integers from print range ( ,1 ,3) # produces an empty list print range (1 , ) to 9 with step 3 to 4

Another example.
1 gases = [ He , Ne , Ar , Kr ] 2 print len ( gases ) # prints length of the gases list 3 print range ( len ( gases )) # prints all indexes of the gases list

Print all values of the list and their indexes.


1 # example 1 2 for i in range ( len ( gases )): 3 print i , gases [ i ] # loops through the length of the list

4 5 # example 2 6 for i , gas in enumerate ( gases ): # enumerates all the elements in list 7 print i , gas

3
3.1

Functions
Simple function

Dene new functions using keyword def.


1 def greet (): # define new function 2 return Good Evening ! # return values 3 4 tmp = greet () 5 print tmp

3.2
1 2 3 4 5 6 7

Function with parameters

def greet ( name ): answer = Hello , + name + ! return answer person = doctor result = greet ( person ) print result

3.3

Function returns

Function can return a value at any time. But usually it is better to make only one return statement at the end of the function.
1 def sign ( num ): 2 if num > : 3 return 1 4 elif num == : 5 return 6 else : 7 return -1 8 9 print sign (3) 10 print sign ( -9)

Function and parameters dont have types! 6

1 def double ( x ): 2 return 2* x 3 4 print double (2) 5 print double ( two )

3.4

Default parameters

Function may have default parameters. Default parameters must be at the end of the list.
1 def multiply (a , b =2): 2 return a * b 3 4 print multiply (1 ) # returns 1 *2 , because b =2 is default value 5 print multiply (1 ,5) # returns 1 *5 because now b =5

Parameters can be called in dierent way.


1 def multiply (a , b =2 , c =1): 2 return a * b * c 3 4 print multiply (1 ) # returns 1 *2*1 , where b =2 , c =1 are default 5 print multiply (1 , c =5) # returns 1 *2*5 , b =2 still remains default 6 # while c is assigned with different value

3.5

Compact view of the code

Try not to use long expressions even if theyre used only once. Example of hard-to-read code.
1 for x in range (1 , GRID_WIDTH -1): 2 for y in range (1 , GRID_HEIGHT -1): 3 if ( density [x -1][ y ] > density_threshold ) or \ 4 ( density [ x +1][ y ] > density_threshold ): 5 if ( flow [ x ][ y -1] < flow_threshold ) or \ 6 ( flow [ x ][ y +1] < flow_threshold ): 7 temp = ( density [x -1][ y ] + density [ x +1][ y ]) / 2 8 if abs ( temp - density [ x ][ y ]) > update_threshold : 9 density [ x ][ y ] = temp

Example of easy-to-read code.


1 def grid_interior ( GRID_SIZE ): 2 return range (1 , GRID_SIZE -1) 3 4 def density_exceeds ( density , x , y , density_threshold ):

5 densityLb = density [x -1][ y ] 6 densityUb = density [x +1][ y ] 7 return densityLb > density_threshold or densityUb > density_threshold 8 9 def flow_exceeds ( flow , x , y , flow_threshold ): 10 flowLb = flow [ x ][ y -1] 11 flowUb = flow [ x ][ y +1] 12 return flowLb < flow_threshold or flowUb > flow_threshold 13 14 # main part of the code is easy readable 15 for x in grid_interior ( GRID_WIDTH ): 16 for y in grid_interior ( GRID_HEIGHT ): 17 if density_exceeds ( density , x , y , density_threshold ): 18 if flow_exceeds ( flow , x , y , flow_threshold ): 19 update_on_tolerance ( density , x , y , tolerance )

You might also like