Python Summary

You will receive this on the exam.

Format: In the simplest use of .format(), each occurrence of {} in the string is replaced by the corresponding format parameter:

    'the numbers are {}, {} and {}'.format(3,4,5)   

returns the string 'the numbers are 3, 4 and 5'. Usually, though not always, this would appear inside a print() statement.

Example functions:


Function to print 100 numbers, starting at 1:

def numprinter():
    for i in range(1,101):
        print i

We could also make the upper value a parameter:

def numprinter(N):
    for i in range(1,N+1):
        print i

Function to print a list LIS:

def listprinter(LIS):
    for x in LIS:
        print x

The collatz() function, illustrating while and if/else:

def collatz(n):
    count = 0
    while n != 1:
        if n%2 == 0: n = n//2
        else: n = 3*n+1
        count += 1
    return count