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())
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()))
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())
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))
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)
In [5]:
for x in range(5):
print(x)
else:
print(x)
In [ ]:
for i in 'python':
print(i, end=' ')
In [ ]:
for i in [1, 2, 3, 4]:
print(i, end=' ')
In [ ]:
for i in (1, 2, 3, 4):
print(i, end=' ')
In [ ]:
for i in {1:'a', 2:'b', 3:'c'}.items():
print(i, end=' ')
print(type(i))
In [ ]:
for i in open('hello_world.py'):
print(i, end='')
In [ ]:
for i in range(10):
print(i, end=' ')
In [ ]:
for i in range(9,0,-1):
print(i, end=' ')
In [ ]:
for i in range(1,11):
print(i, end=' ')
In [ ]:
for letter in 'Python':
if letter == 'h':
continue
print(letter, end='')
In [ ]:
for l in 'Python':
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