Control flow

1. Conditional execution

1.1 Using if ... elif ... else


In [ ]:
# Some usefull functions for the code of next sections ...

def _1():
    return 'You entered one'

def _2():
    return 'You entered two'

def different():
    return 'You dit not enter one or two'

In [ ]:
a = int(input('Please, enter a natural number: '))
if a == 1:
    print(_1())
elif a == 2:
    print(_2())
else:
    print(different())

1.2 Using a dictionary ... to implement an if ... elif ... else structure

We use a dictionary which stores functions:


In [ ]:
a = int(input('Please, enter a natural number: '))
switcher = {
    1: _1,
    2: _2
}
print(switcher.get(a, different)())

A different version that at run-time evaluates the "values" (functions) indexed by the dictionary:


In [ ]:
a = int(input('Please, enter a natural number: '))
switcher = {
    1: _1(),
    2: _2()
}
print(switcher.get(a, different()))

1.3 Building a function-call at run-time ... to implement an if ... elif ... else structure

Using a $\lambda$-function:


In [ ]:
a = int(input('Please, enter a natural number: ')) 
function = lambda x:eval(x)()
try:
    print(function('_' + str(a)))
except:
    print(different())

1.4 Using a class ... to implement an if ... elif ... else structure


In [ ]:
class Switcher(object):
    def run(self, argument):
        method = getattr(self, '_' + str(argument), different)
        return method()

    def _1(self):
        return _1()

    def _2(self):
        return _2()

a = int(input('Please, enter a natural number: ')) 
print(Switcher().run(a))

2. Looping

2.1 With while statement


In [ ]:
import random

unknown = int(random.uniform(1, 10)) # A random number betweem 1 and 10
counter = 0

while(True):
    counter += 1
    
    print('(Try {}) Please, enter a number between 1 and 10: '.format(counter), end='')
    a = int(input())

    if a == unknown:
        print('Congratulations!\nYou have guessed my number :-)')
        break
    else:
        print('Wrong number. ', end='')
        if a > unknown:
            print('Try a smaller one!')
        else:
            print('Try a bigger one!')

In [2]:
x = 0
while x<5:
    print(x)
    x += 1
else:
    print(x)


0
1
2
3
4
5

2.2 With for statemet


In [5]:
for x in range(5):
    print(x)
else:
    print(x)


0
1
2
3
4
4

2.2.1 Iterating over a string


In [ ]:
for i in 'python':
    print(i, end=' ')

2.2.2 Interating over a list


In [ ]:
for i in [1, 2, 3, 4]:
    print(i, end=' ')

2.2.3 Iterating over a tuple


In [ ]:
for i in (1, 2, 3, 4):
    print(i, end=' ')

2.2.4 Iterating over a dictionary


In [ ]:
for i in {1:'a', 2:'b', 3:'c'}.items():
    print(i, end=' ')
    print(type(i))

2.2.5 Iterating over a file


In [ ]:
for i in open('hello_world.py'):
    print(i, end='')

2.2.6 Iterating over a iterator


In [ ]:
for i in range(10):
    print(i, end=' ')

In [ ]:
for i in range(9,0,-1):
    print(i, end=' ')

2.2.7 Iterating over a iterator (again)


In [ ]:
for i in range(1,11):
    print(i, end=' ')

2.2.8 Using continue


In [ ]:
for letter in 'Python':
    if letter == 'h':
        continue
    print(letter, end='')

In [ ]:
for l in 'Python':

2.3 A word about iterators

Iterators are objects:


In [ ]:
print(type(range(10)))

With the following methods:


In [ ]:
dir(range(10))

Iterators can be used to generate other structures:


In [ ]:
list(range(10)) # Such as lists