Dear Study group attendees, this time we will do some basic exercise from http://www.practicepython.org/
We will do the assignments from the website blockwise and discuss the solutions in between - let's look how far we can reach during the lesson. If you want you can practice this assignments at home and use the python study group to ask questions.
At the end of this site you will find some python functions we discussed with Rodolfo.
Here you see the solutions for the first 3 Exercises:
Example 1: Character Input
1 name = input('Please tell me your name ')
2 print(f'Hello {name}\n')
3 age = input('Please tell me your age ')
4 difference = 100 - int(age)
5 print(f'{name}, you will turn 100 years in {difference} years.\n')
6
7 repeat = input('Please tell me another number ')
8 # print(f'{name}, you will turn 100 years in {difference} years.\n' * int(repeat))
9 print(name + ', you will turn 100 years in ' + str(difference) + ' years.\n')
Example 2: Odd Or Even
1 number = int(input('Please tell me a number '))
2 if number % 4 == 0 :
3 print('This number is a multiple of 4')
4 else:
5 if number % 2 == 0:
6 print('Number is even')
7 else:
8 print('Number is odd')
9
10 num = int(input('Please tell me a number '))
11 check = int(input('Tell me a number which devides you number '))
12 if num % check == 0:
13 print(f'{num} devides evently through {check}')
14 else:
15 print(f'{num} does not evently devide through {check}.')
Example 3: List Less Than Ten
1 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
2
3 emptylist = []
4
5 for elem in a:
6 if elem < 5:
7 print(elem)
8 emptylist.append(elem)
9
10 print(emptylist)
11
12 number = int(input('Please tell me a number '))
13 print(f'Listelements smaller than {number} are')
14
15 for elem in a:
16 if elem < number:
17 print(elem)
YIELD: The yield-command stops the code where it is and returns the value. When next element is requested it continues at the location it stopped before.
1 def myrange(stop):
2 v = 0
3 while v < stop:
4 yield v
5 v += 1
6
7 del __builtins__.range
8 for i in myrange(10):
9 print(i)
10
11 def some_people():
12 yield "thomas"
13 yield "marion"
14 yield "hop"
15 yield "adi"
16
17 def nice_people():
18 for person in some_people():
19 if person == "hop":
20 continue
21 yield person
22 yield "my imaginary friend"
23
24 def greet_the_nice_people():
25 for person in nice_people():
26 yield "Hello " + person
27
28 print(list(some_people()))
29 print(list(nice_people()))
30 for line in greet_the_nice_people():
31 print(line)
This is the output of the yield-example:
0 1 2 3 4 5 6 7 8 9 ['thomas', 'marion', 'hop', 'adi'] ['thomas', 'marion', 'adi', 'my imaginary friend'] Hello thomas Hello marion Hello adi Hello my imaginary friend
Things we discussed furthermore - credits to Rodolfo!
import inspect; inspect.getsource(...)