Introduction to Python

Why Python?

  • easy to learn and use
  • excellent for beginners, yet superb for experts
  • highly scalable, suitable for large projects as well as small ones
  • rapid development
  • portable, cross-platform
  • powerful standard libs
  • wealth of 3rd party packages

And don't forget that with Python, programming is fun again!


In [4]:
print("Hello, world!")


Hello, world!

Python 2 or Python 3?

Short version: Python 2.x is legacy, Python 3.x is the present and future of the language

  • final 2.x version 2.7 was released 2010
  • 3.0 was released in 2008
  • 3.4 was released 2014
  • recent standard library improvements are only available in 3.x

Software

We will use:

- Python (https://www.python.org/)
- IPython (http://ipython.org/)
- IPython Notebook (http://ipython.org/notebook.html)
- an editor of your choice

You could use:

- an IDE (PyCharm, Eclipse)
- Python debuggers (pdb)
- Code checkers (pylint)

Interactive mode

Start the python command line interpreter by typing python, or the Python interactive shell by typing ipython into your terminal.

You can use this a calculator:


In [5]:
2 + 3


Out[5]:
5

In [6]:
5 * (7 + 2)


Out[6]:
45

Variables

You can assign numbers to variables:


In [7]:
width = 5
height = 2 + 6
width * height


Out[7]:
40

You can change variables:


In [8]:
height = 12
width * height


Out[8]:
60

Naming Rules

  • Variables can only contain letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number.
  • Spaces are not allowed in variable names, so use underscores instead of spaces.
  • You cannot use Python keywords as variable names. If you absolutely need to, add an underscore to the end.
  • Variable names should be descriptive, without being too long. For example mc_wheels is better than just wheels or number_of_wheels_on_a_motorycle.
  • Be careful about using the lowercase letter l and the uppercase letters O and I in places where they could be confused with the numbers 1 and 0. And never use them as single character variable names.

Datatypes

Int & Float

(Integers and Floating point numbers)

You'll have to be careful about the datatype (sometimes)


In [9]:
width / 2


Out[9]:
2.5

In [10]:
width // 2


Out[10]:
2

You can convert an int to a float:


In [11]:
float(width)


Out[11]:
5.0

This kind of type casting works for most datatypes in Python!

String

Strings are sets of characters and are either contained in single or double quotes.


In [12]:
bla = 'bla bla bla'
bla


Out[12]:
'bla bla bla'

In [13]:
print(bla)


bla bla bla

In [14]:
blub = "bla blub"
print(blub)


bla blub

This allows you to make strings that contain quotations.


In [15]:
quote = "Linus Torvalds once said, 'Any program is only as good as it is useful.'"
print(quote)


Linus Torvalds once said, 'Any program is only as good as it is useful.'

Use \ to continue your command on the next line.


In [16]:
bla = 'bla bla\
 bla bla'
print(bla)


bla bla bla bla

Use \n to put a newline into the string.


In [17]:
bla = 'bla bla\n\
 bla bla'
print(bla)


bla bla
 bla bla

Or use multi line strings in triple quotes (either ''' or """) to do both.


In [18]:
bla = '''bla bla 
   bla bla'''
print(bla)


bla bla 
   bla bla

You can concatenate strings:


In [19]:
blub = 'bla ' + blub
blub


Out[19]:
'bla bla blub'

In [20]:
blub * 3


Out[20]:
'bla bla blubbla bla blubbla bla blub'

In Ipython (and Ipython Notebook) you can see all the string functions by tabbing them.

blub.

In [21]:
blub.title?

In [22]:
blub.title()


Out[22]:
'Bla Bla Blub'

Unicode string

Like strings, but with more characters!


In [23]:
my_unicode = 'Hellö World!'
my_unicode


Out[23]:
'Hellö World!'

Some unicode strings can not be cast to strings.

While most Error messages are easy to understand, it might also be a good idea, to google (or whatever) them. Other questions occuring during programming are also likely to have been asked before (so, google!). Answers on stackoverflow.com are often useful.

If you absolutely want to convert to string, you can do it like that:

List

There are many compound data types in Python.

The most versatile one is a list. This is the closest to 'arrays' from other programming languages.


In [24]:
my_list = blub.split()
my_list


Out[24]:
['bla', 'bla', 'blub']

Lists can be indexed and sliced.


In [25]:
my_list[0]


Out[25]:
'bla'

In [26]:
my_list[-1]


Out[26]:
'blub'

In [27]:
my_list = my_list + ['more', 'and', 'more', 'words', 'plus', 'a', 'number', 4]
my_list


Out[27]:
['bla',
 'bla',
 'blub',
 'more',
 'and',
 'more',
 'words',
 'plus',
 'a',
 'number',
 4]

In [28]:
my_list[2:6]


Out[28]:
['blub', 'more', 'and', 'more']

In [29]:
my_list[0:2]


Out[29]:
['bla', 'bla']

In [30]:
my_list[:2]


Out[30]:
['bla', 'bla']

In [31]:
my_list[4:-2]


Out[31]:
['and', 'more', 'words', 'plus', 'a']

In [32]:
my_list[4:-2:3]


Out[32]:
['and', 'plus']

The indexing and slicing works for all built-in sequence types. (Also strings!)

In a list, you can change elements or slices. (Lists are mutable, strings for example are immutable.)


In [33]:
my_list[-4:] = ['a']
my_list


Out[33]:
['bla', 'bla', 'blub', 'more', 'and', 'more', 'words', 'a']

You can add new items to the end of the list with the append() method:


In [34]:
my_list.append(4)
my_list


Out[34]:
['bla', 'bla', 'blub', 'more', 'and', 'more', 'words', 'a', 4]

You can nest lists:


In [35]:
nested = [my_list, ['another', 'list']]
nested


Out[35]:
[['bla', 'bla', 'blub', 'more', 'and', 'more', 'words', 'a', 4],
 ['another', 'list']]

In [36]:
nested[1][0]


Out[36]:
'another'

Set

A set will not store duplicate entries.


In [37]:
my_list


Out[37]:
['bla', 'bla', 'blub', 'more', 'and', 'more', 'words', 'a', 4]

In [38]:
my_set = set(my_list)
my_set


Out[38]:
{'words', 4, 'bla', 'blub', 'a', 'and', 'more'}

Membership testing


In [39]:
'bla' in my_list


Out[39]:
True

In [40]:
'turtle' in my_set


Out[40]:
False

Dict

A dictionary contains key / value pairs. Instead of the position you use the key as the key.


In [41]:
phonebook = {'Max': 8389, 'Jannis': 8389, 'Thomas': 8325}
phonebook['Max']


Out[41]:
8389

In [42]:
phonebook['Katharina'] = 8592
phonebook


Out[42]:
{'Jannis': 8389, 'Katharina': 8592, 'Max': 8389, 'Thomas': 8325}

In [43]:
phonebook.keys()


Out[43]:
dict_keys(['Jannis', 'Max', 'Thomas', 'Katharina'])

More important datatypes

Bool

Values: True, False

- []         False
- [a, b]     True
- 0          False
- all other  True

None

Values: None

  • frequently used to represent the absence of a value

if Statements


In [44]:
if 1:
    print('yes!')


yes!

If the boolean statement is True, the code below is executed.


In [45]:
x = int(input("Please enter an integer: "))


Please enter an integer: 1

In [46]:
if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')


Single

Indentation

Indentation determines the context of commands.


In [47]:
if []:
    print('empty list!')
print('Never True!')


Never True!

In [48]:
if not []:
    print('That list isn\'t empty!')
print('Always True!')


That list isn't empty!
Always True!

You should use 4 spaces, not a tab!!

If you are presenting your code, be sure the indentation is right!

while Statements


In [49]:
i = 5
while i > 0:
    print(i**2)
    i = i - 1


25
16
9
4
1

for Statements

Looping through lists, strings, sets, ...


In [50]:
my_list


Out[50]:
['bla', 'bla', 'blub', 'more', 'and', 'more', 'words', 'a', 4]

In [51]:
for element in my_list:
    print(element, len(element))


bla 3
bla 3
blub 4
more 4
and 3
more 4
words 5
a 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-046bd5869bc6> in <module>()
      1 for element in my_list:
----> 2     print(element, len(element))

TypeError: object of type 'int' has no len()

List Comprehensions


In [52]:
my_first_lc = [len(element) for element in my_list[:-1]]
my_first_lc


Out[52]:
[3, 3, 4, 4, 3, 4, 5, 1]

The range() Function


In [ ]:
range?

In [ ]:
range(4)

In [ ]:
range(4,9)

In [ ]:
list(range(4, 9, 2))

range() is often used in for-loops


In [ ]:
for i in range(len(my_list)):
    print(i, my_list[i])

But using xrange() is the smarter solution. It does not return a list, but an object generating the numbers on demand. In Python 3, there is only range(), but behaving like xrange(). So, if you need the list, type list(range(4)).

And always keep in mind, that you can loop over the elements in a list in an easy, pythonic way. No need to use the indices.


In [ ]:
for i in range(len(my_list)):   # NOOOO!
    print(my_list[i])
    
for element in my_list:          # YES!!
    print(element)

break and continue Statements, and else Clauses on Loops

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.


In [ ]:
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n/x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

The continue statement, also borrowed from C, continues with the next iteration of the loop:


In [ ]:
for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found a number", num)

pass Statements

It will do nothing!


In [ ]:
x = int(input("Please enter an integer: "))

In [ ]:
if x < 0:
    pass
elif x == 42:
    pass #TODO must fill the answer to life, the universe, and everything here later
else:
    print('More')

Functions

Definition Syntax


In [ ]:
def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n.""" # docstring
    a, b = 0, 1  # multiple assignement
    while a < n:
        print(a, end=' ')  # prevents the newline
        a, b = b, a+b  # another multiple assignement
        
fib(500)

The keyword def introduces a function definition. It has to be followed by the function name and the paranthesized list of formal parameters.

Documentation strings

You should put a triple quoted string into the first line after the function definition, containing a description of the function. This is called docstring, and can be used to automatically produce documentation.

The return statement

It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:


In [ ]:
def fib2(n): # return Fibonacci series up to n
    """Return a list containing the Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

f100 = fib2(100)    # call it
f100                # write the result

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Default Argument Values and Keyword Arguments


In [ ]:
def parrot(voltage, state='a stiff', action='voom', type_='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type_)
    print("-- It's", state, "!")
    
parrot(1000)  # 1 positional argument

state, action, and type_ have default values, so they can be omitted from the function call.


In [ ]:
parrot(voltage=1000, action='jump')  # 2 keyword arguments

You can call the function using keyword arguments, positional arguments, or mix both.


In [ ]:
parrot('a lot of', 'bereft of life')  # 2 positional arguments

In [ ]:
parrot('a lot of', type_='Lory', state='pushing up the daisies')  # 1 positional and 1 keyword argument

The sentences are actually from a Monty Pythons episode. You can watch it later: https://www.youtube.com/watch?v=4vuW6tQ0218

Handling exceptions

You have seen error messages by now. Errors detected during excution are called exceptions and can be handled. Just as a reminder, error messages look like this:


In [ ]:
my_list[20]

Exceptions come in different types, which are given in the message. The type of this exception is IndexError.

So, let's handle that exception!


In [ ]:
def handle_index_error(i):
    try:
        print(my_list[i])
    except IndexError:
        print(my_list[-1])
        
handle_index_error(20)

In [ ]:
handle_index_error(5)

In [ ]:
handle_index_error('some useless string')

Coding style

“The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly." - Donald E. Knuth, Selected Papers on Computer Science

PEP8

Style guide for Python code

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.

A few rules

  • never use tabs, always 4 spaces
  • try to limit lines to 79 characters
  • use whitespace to make your code more readable

In [ ]:
spam(ham[1], {eggs: 2})        # YES!
spam( ham[ 1 ], { eggs: 2 } )  # NO!!

x, y = y, x     # YES!
x , y = y , x   # NO!!

counter = counter + 1  # YES!
counter=counter+1      # NO!!

result = add(x+1, 3)   # YES!
result = add(x + 1, 3) # YES!


def complex(real, imag=0.0):         # YES!
    return magic(r=real, i=imag)

def complex(real, imag = 0.0):       # NO!!
    return magic(r = real, i = imag)
  • Follow these naming conventions:
    • lower_case_under for variables and functions and methods
    • WordCap for classes
    • ALL_CAPS for constants

And of course, there is more: https://www.python.org/dev/peps/pep-0008/

The Zen of Python


In [ ]:
import this