3 Types, Functions and Flow Control

Data types


In [1]:
x_int = 3

x_float = 3.

x_string = 'three'

x_list = [3, 'three']

In [2]:
type(x_float)


Out[2]:
float

In [3]:
type(x_string)


Out[3]:
str

In [4]:
type(x_list)


Out[4]:
list

Numbers


In [5]:
abs(-1)


Out[5]:
1

In [6]:
import math

math.floor(4.5)


Out[6]:
4

In [7]:
math.exp(1)


Out[7]:
2.718281828459045

In [8]:
math.log(1)


Out[8]:
0.0

In [9]:
math.log10(10)


Out[9]:
1.0

In [10]:
math.sqrt(9)


Out[10]:
3.0

In [11]:
round(4.54,1)


Out[11]:
4.5

If this should not make sense, you can print some documentation:


In [12]:
round?


Docstring:
round(number[, ndigits]) -> number

Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
Type:      builtin_function_or_method

Strings


In [13]:
string = 'Hello World!'
string2 = "This is also allowed, helps if you want 'this' in a string and vice versa"
len(string)


Out[13]:
12

Slicing


In [14]:
print(string)
print(string[0])
print(string[2:5])
print(string[2:])
print(string[:5])
print(string * 2)
print(string + 'TEST')
print(string[-1])


Hello World!
H
llo
llo World!
Hello
Hello World!Hello World!
Hello World!TEST
!

String Operations


In [15]:
print(string/2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-051052e91dd4> in <module>()
----> 1 print(string/2)

TypeError: unsupported operand type(s) for /: 'str' and 'int'

In [16]:
print(string - 'TEST')


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-ed2359c80151> in <module>()
----> 1 print(string - 'TEST')

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [17]:
print(string**2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-e987988de494> in <module>()
----> 1 print(string**2)

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

capitalizing strings:


In [18]:
x = 'test'

In [19]:
x.capitalize()


Out[19]:
'Test'

In [20]:
x.find('e')


Out[20]:
1

In [21]:
x = 'TEST'
x.lower()


Out[21]:
'test'

Enviromnents like Jupyter and Spyder allow you to explore the methods (like .capitalize() or .upper() using x. and pressing tab.

Formating

You can also format strings, e.g. to display rounded numbers


In [22]:
print('Pi is {:06.2f}'.format(3.14159))
print('Space can be filled using {:_>10}'.format(x))


Pi is 003.14
Space can be filled using ______TEST

With python 3.6 this became even more readable


In [23]:
print(f'{x} 1 2 3')


TEST 1 2 3

Lists


In [24]:
x_list


Out[24]:
[3, 'three']

In [25]:
x_list[0]


Out[25]:
3

In [26]:
x_list.append('III')
x_list


Out[26]:
[3, 'three', 'III']

In [27]:
x_list.append('III')
x_list


Out[27]:
[3, 'three', 'III', 'III']

In [28]:
del x_list[-1]
x_list


Out[28]:
[3, 'three', 'III']

In [29]:
y_list = ['john', '2.', '1']

y_list + x_list


Out[29]:
['john', '2.', '1', 3, 'three', 'III']

In [30]:
x_list*2


Out[30]:
[3, 'three', 'III', 3, 'three', 'III']

In [31]:
z_list=[4,78,3]
max(z_list)


Out[31]:
78

In [32]:
min(z_list)


Out[32]:
3

In [33]:
sum(z_list)


Out[33]:
85

In [34]:
z_list.count(4)


Out[34]:
1

In [35]:
z_list.append(4)
z_list.count(4)


Out[35]:
2

In [36]:
z_list.sort()
z_list


Out[36]:
[3, 4, 4, 78]

In [37]:
z_list.reverse()
z_list


Out[37]:
[78, 4, 4, 3]

Tuples

Tuples are immutable and can be thought of as read-only lists.


In [38]:
y_tuple = ('john', '2.', '1')
type(y_tuple)


Out[38]:
tuple

In [39]:
y_list


Out[39]:
['john', '2.', '1']

In [40]:
y_list[0] = 'Erik'
y_list


Out[40]:
['Erik', '2.', '1']

In [41]:
y_tuple[0] = 'Erik'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-fe270b26fef3> in <module>()
----> 1 y_tuple[0] = 'Erik'

TypeError: 'tuple' object does not support item assignment

Dictionaries

Dictonaries are lists with named entries. There is also named tuples, which are immutable dictonaries. Use OrderedDict from collections if you need to preserve the order.


In [42]:
tinydict = {'name': 'john', 'code':6734, 'dept': 'sales'}
type(tinydict)


Out[42]:
dict

In [43]:
print(tinydict)
print(tinydict.keys())
print(tinydict.values())


{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])

In [44]:
tinydict['code']


Out[44]:
6734

In [45]:
tinydict['surname']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-45-e0955cd458fa> in <module>()
----> 1 tinydict['surname']

KeyError: 'surname'

In [46]:
tinydict['dept'] = 'R&D'  # update existing entry
tinydict['surname'] = 'Sloan'  # Add new entry

In [47]:
tinydict['surname']


Out[47]:
'Sloan'

In [48]:
del tinydict['code']  # remove entry with key 'code'

In [49]:
tinydict['code']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-49-26dd6f3c19d8> in <module>()
----> 1 tinydict['code']

KeyError: 'code'

In [50]:
tinydict.clear()
del tinydict

When duplicate keys encountered during assignment, the last assignment wins


In [51]:
dic = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
dic


Out[51]:
{'Name': 'Manni', 'Age': 7}

Finding the total number of items in the dictionary:


In [52]:
len(dic)


Out[52]:
2

Produces a printable string representation of a dictionary:


In [53]:
str(dic)


Out[53]:
"{'Name': 'Manni', 'Age': 7}"

Functions


In [54]:
def mean(mylist):
    """Calculate the mean of the elements in mylist"""
    number_of_items = len(mylist)
    sum_of_items = sum(mylist)
    return sum_of_items / number_of_items

In [55]:
type(mean)


Out[55]:
function

In [56]:
z_list


Out[56]:
[78, 4, 4, 3]

In [57]:
mean(z_list)


Out[57]:
22.25

In [58]:
help(mean)


Help on function mean in module __main__:

mean(mylist)
    Calculate the mean of the elements in mylist


In [59]:
mean?


Signature: mean(mylist)
Docstring: Calculate the mean of the elements in mylist
File:      ~/Projects/BIST-Python-Bootcamp/<ipython-input-54-75dbfb6ce315>
Type:      function

Flow Control

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. In Python a block is delimitated by intendation, i.e. all lines starting at the same space are one block.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.

while Loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.


In [60]:
count = 0
while (count < 9):
    print('The count is: ' + str(count))
    count += 1

print('Good bye!')


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

for Loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.


In [61]:
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second Example
    print('Current fruit :', fruit)


Current fruit : banana
Current fruit : apple
Current fruit : mango

Sometimes one also needs the index of the element, e.g. to plot a subset of data on different subplots. Then enumerate provides an elegant ("pythonic") way:


In [62]:
for index, fruit in enumerate(fruits):
    print('Current fruit :', fruits[index])


Current fruit : banana
Current fruit : apple
Current fruit : mango

In principle one could also iterate over an index going from 0 to the number of elements:


In [63]:
for index in range(len(fruits)):
    print('Current fruit:', fruits[index])


Current fruit: banana
Current fruit: apple
Current fruit: mango

for loops can be elegantly integrated for creating lists


In [64]:
fruits_with_b = [fruit for fruit in fruits if fruit.startswith('b')]
fruits_with_b


Out[64]:
['banana']

This is equivalent to the following loop:


In [65]:
fruits_with_b = []
for fruit in fruits:
    if fruit.startswith('b'):
        fruits_with_b.append(fruit)
fruits_with_b


Out[65]:
['banana']

Nested Loops

Python programming language allows to use one loop inside another loop. A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.


In [66]:
for x in range(1, 3):
    for y in range(1, 4):
        print(f'{x} * {y} = {x*y}')


1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

if

The if statement will evaluate the code only if a given condition is met (used with logical operator such as ==, <, >, =<, =>, not, is, in, etc. Optionally we can introduce a elsestatement to execute an alternative code when the condition is not met.


In [67]:
x = 'Mark'

if x in ['Mark', 'Jack', 'Mary']:
    print('present!')
else:
    print('absent!')


present!

In [68]:
x = 'Tom'

if x in ['Mark', 'Jack', 'Mary']:
    print('present!')
else:
    print('absent!')


absent!

We can also use one or more elif statements to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE


In [69]:
x = 'Tom'

if x in ['Mark', 'Jack', 'Mary']:
    print('present in list A!')
elif x in ['Tom', 'Dick', 'Harry']:
    print('present in list B!')
else:
    print('absent!')


present in list B!

else statements can be also use with while and for loops (the code will be executed in the end)

You can also use nested if statements.

break

It terminates the current loop and resumes execution at the next statement. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.


In [70]:
var = 10
while var > 0:              
    print('Current variable value: ' + str(var))
    var = var -1
    if var == 5:
        break

print('Good bye!')


Current variable value: 10
Current variable value: 9
Current variable value: 8
Current variable value: 7
Current variable value: 6
Good bye!

continue

The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop (like a "skip").

The continue statement can be used in both while and for loops.


In [71]:
for letter in 'Python':
    if letter == 'h':
        continue
    print('Current Letter: ' + letter)


Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n

pass

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet


In [72]:
for letter in 'Python': 
    if letter == 'h':
        pass
        print('This is pass block')
    print('Current Letter: ' + letter)

print('Good bye!')


Current Letter: P
Current Letter: y
Current Letter: t
This is pass block
Current Letter: h
Current Letter: o
Current Letter: n
Good bye!

pass and continuecould seem similar but they are not. The printed message "This is pass block", wouldn't have been printed if continue had been used instead. pass does nothing, continue goes to the next iteration.


In [73]:
for letter in 'Python': 
    if letter == 'h':
        continue
        print('This is pass block')
    print('Current Letter: ' + letter)

print('Good bye!')


Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n
Good bye!