Flow of execution — functions
Try debugging in thonny for the following examples. (Also try Step out button, when the code inside a function is being executed.)
1# Function definition2def display_greeting():3 print("+------------+")4 print("| Welcome! |")5 print("+------------+")67display_greeting()89display_greeting()
1def f(x):2 result = x * x - x - 13 return result4 # OR: return x * x - x - 156y = f(5)7print(y)89y = f(10)10print(y)
1def f():2 return 2345def g():6 return 3789def h():10 return f() * g()111213print(h())
Variables and if statement
Variables can be created inside the branches of if statement.
Make sure that all branches have same variable names!
1income = 1500023if income < 12000:4 tax = 0.05else:6 taxes = income * 15.5 / 100 # Change variable name to tax78print("Your tax is", tax)
NameError: name 'tax' is not defined
Mutually exclusive conditions — chained if-elif-else statement
1income = 2000023if income < 12000:4 tax = 0.05elif income < 30000:6 tax = income * 15.0 / 1007elif income < 100000:8 tax = income * 20.0 / 1009else:10 tax = income * 25.0 / 1001112print("Your tax is", tax)
- Mutually exclusive — only one of these blocks will get executed.
- Order matters! If first of the conditions is True, later conditions are not checked.
- We can have as many elif’s as you want.
- The final else part is not required so you may omit it if not needed.
Example
Is there anything wrong in code below?
1temperature = 2523if temperature > 0:4 print("Cold")5elif temperature > 20:6 print("Warm")7elif temperature > 30:8 print("Hot")9else:10 print("Freezing")
Cold
Order of conditions matters!
1temperature = 2523if temperature > 30:4 print("Hot")5elif temperature > 20:6 print("Warm")7elif temperature > 0:8 print("Cold")9else:10 print("Freezing")
1temperature = 2523if temperature > 0 and temperature <= 20:4 print("Cold")5elif temperature > 20 and temperature <= 30:6 print("Warm")7elif temperature > 30:8 print("Hot")9else:10 print("Freezing")
Try “Blood Pressure” problem on Ed Lessons.
if statements can be nested
Examples below are logically equivalent.
Nested if statements
1x = 102if x > 0:3 print("Positive")4else:5 if x < 0:6 print("Negative")7 else:8 print("Zero")
Chained if statement
1x = 102if x > 0:3 print("Positive")4elif x < 0:5 print("Negative")6else:7 print("Zero")
Correct indentation is essential!
Sometimes, incorrect indentation may not give an error but it may lead to an unexpected program.
1income = 100023if income < 12000:4 print("You don't have to pay tax.")5 tax = 0.06else:7 print("You have to pay tax.")8tax = income * 15.0 / 100 # this line should be indented910print("Your tax is", tax)
Iteration using for loop
for loop can be used to repeatedly execute a block of code.
1for i in range(5):2 print("Hello")
Hello Hello Hello Hello Hello
1for i in range(5):2 print(i)
0 1 2 3 4
What happens when the for loop is executed?
1for i in range(5):2 print(i)
- range(5) will produce a sequence of integers 0,1,2,3,4 in steps.
- for loop allows us to iterate i.e. “go over” that sequence, a number at a time
- In each step of the loop, variable i gets a value from the sequence
- We can have any valid variable name, other than i if we want.
Try step-by-step execution of the examples above!
range() function takes up to 3 arguments
range(end): produces sequence 0, 1, 2, ..., end-1
range(start, end): produces sequence start, start+1, ..., end-1
range(start, end, step):
- if step > 0, produces sequence start, start+step, ..., N where N < end
- if step < 0, produces sequence start, start+step, ..., N where N > end
Examples of range()
1# 0, 1, 2, ..., 92for i in range(10):3 print(i)45# 1, 2, ..., 106for i in range(1, 11):7 print(i)89# 0, 2, 4, ..., 1810for i in range(0, 20, 2):11 print(i)
1# 10, 15, 20, 25, ..., 952for i in range(10, 100, 5):3 print(i)45# 10, 9, 8, ..., 16for i in range(10, 0, -1):7 print(i)
Exercise
Compute sum of first N numbers.
1N = 5023total = 04for num in range(1, N+1):5 total = total + num67print(total)
Try “Harmonic sum” problem on Ed Lessons.
Indexing & Slicing Strings
Recall that a string is a sequence of characters.
Each character, therefore, has a position or an index.
Index starts with zero. For example, for the string "Hello":
Indices must be integers and cannot be float.
Python also allows negative indices, which go from right to left:
For any string s,
- valid positive index values are from 0 to len(s)-1.
- valid negative index values are from -len(s) to -1.
Square brackets [] are used to get the letter in a string at a given index.
1>>> message = "Hello"2>>> message[0] # first letter3'H'4>>> message[1] # second letter5'e'6>>> message[4] # fifth letter, the last one in the string7'o'
1>>> message = "Hello"2>>> message[5] # there is no letter at this index3IndexError: string index out of range4>>> message[-1]5'o'6>>> message[-5]7'H'8>>> message[-6] # there is no letter at this index9IndexError: string index out of range10>>> message[1.0]11TypeError: string indices must be integers
Traversing a string
We can use for loop with range() function to go over a string letter-by-letter.
1message = "Hello"23for i in range(len(message)):4 print(i, message[i])
0 H 1 e 2 l 3 l 4 o
Another example:
1letters = "bcmrst"23for i in range(len(letters)):4 print(letters[i] + "ake")
Try “Remove spaces from a string” problem on Ed Lessons.
Using slice to get substrings
Using slice notation we can get parts of a string: string[start:end:step].
start, end, step values must be integers and work similar to range() function.
1>>> fruit = "pineapple"23>>> fruit[4:7] # letters at indices 4, 5, 64'app'5>>> fruit[2:7:2] # letters at indices 2, 4, 66'nap'
1>>> fruit[:4] # same as fruit[0:4]2'pine'3>>> fruit[4:] # same as fruit[4:len(fruit)]4'apple'56>>> fruit[-5:] # from index -5 to the end of string7'apple'8>>> fruit[-5:-2] # letters at indices -5, -4, -39'app'
1# Negative step size of -1 means go from2# right to left, i.e. in reverse order3>>> fruit[-4:-8:-1] # letters at -4, -5, -6, -74'paen'56# Omitting start and end mean select whole string,7# but step size -1 means right to left i.e. reverse order8>>> fruit[::-1]9'elppaenip'