Controll Structures

Download this notebook: ControlStructures.ipynb.

Topics in this lesson: - Selection Logic: If-statements - Iterating Logic: Loops

If-statements: if, if-else, elif

# Using simple if-statement
variable_1 = 5 

if variable_1 > 10: 
    print("Variable is greater than 10!")

if variable_1 < 10: 
    print("Variable is smaller than 10!")
# Using if-else statement 
variable_1 = 5

if variable_1 > 10: 
    print("Variable is greater than 10!")
else: 
    print("Variable is smaller than 10!")

# What is the problem here? 
# Using elif statement 
variable_1 = 5

if variable_1 > 10: 
    print("Variable is greater than 10!")
elif variable_1 == 10: 
    print("Variable is equal to 10!")
else: 
    print("Variable is smaller than 10!") 
    
Switch case (sort of)
# Switch case using elif-ladder (Similar to switch-case)
variable_1 = 5

if variable_1 == 1: 
    print("Variable is 1!")
elif variable_1 == 2: 
    print("Variable is 2!")
elif variable_1 == 3:
    print("Variable is 3!")
elif variable_1 == 4: 
    print("Variable is 4!")
# No else needed! 
# else:                 
#     print("Variable is not in range of 1 to 4!")
# Switch case using "Structural pattern matching" (Python version 3.10 and upwards)

# input_variable = input("Select a number between 1 and 5:")

# match input_variable: 
#     case 1:
#         print("Number 1 choosen!")
#     case 2:
#         print("Number 2 choosen!")
#     case 3:
#         print("Number 3 choosen!")
#     case 4:
#         print("Number 4 choosen!")
#     case 5:
#         print("Number 5 choosen!")
#     case _:
#         print("Invalid input!")

Loops: for, while, do-while

# Using for loops 

variable_2 = 7 

for i in range(variable_2): 
    print(f"For loop iteration with range and single number: {i}")

print("_______________________________________________________")  

for i in range(3, variable_2): 
    print(f"For loop iteration with range starting at position 3: {i}")

# Why does it show "3" as first iteration? 
# Starting at position three we would expect iteration 2 as first number...

print("_______________________________________________________")  

string_variable = "Hello World!"

for character in string_variable: 
    print(character)
# Using while loops: 

variable_3 = 10 
counting_variable = 0

while counting_variable < variable_3: 
    print(f"Counting variable is: {counting_variable}")
    counting_variable = counting_variable + 1

print("_______________________________________________________")  

# Interrupt a loop using the break-statement 

counting_variable = 0

while counting_variable < variable_3: 
    
    if counting_variable == 5: 
        print("Interrupted by break statement!")
        break
    
    print(f"Counting variable is: {counting_variable}")
    counting_variable = counting_variable + 1
# Using a do-while loop 
# The advantage of this kind of loop is, that it will always run a single time! 

variable_4 = 10

while True: 
    
    print("Stuff is made at least one time!")
    
    if variable_4 < 0: 
        print("Number is negative, abort!")
        break 

    if variable_4 > 0: 
        print("ALWAYS INCLUDE A CONDITION WITH BREAK TO EXIT A 'DO-WHILE LOOP'!!!")
        break

    # The code in this cell works just fine, but here is dangerous logical mistake...
    # Can you find it? HINT: take a look at the if statements...   
    # Use the "interrupt" on the top to stop the kernel 
counter_variable = 1 
max_iteration = 10 
break_condition = 11

while (counter_variable <= max_iteration): 
    print("We are at iteration:", counting_variable )
    counter_variable += 1 
    if (counter_variable == break_condition): 
        print("Stopped at iteration", counter_variable, "because of break condition!")
        break

"""Fix the code!"""

# Syntax error --> Code doesn´t work, why? 
# Logical error --> "Stopped at iteration 11", but we only wannt to do max. 10 interations???
# This code will iterate the counter_variable up, until it matches the max_iteration value. 
# Somehow the code does´t work as expected. Do you know why?

counter_variable = 1
max_iteration = 10 
continue_condition = 5

while (counter_variable <= max_iteration): 
    if (counter_variable == continue_condition): 
        print("The condition number ", counter_variable, " appeared. Starting at the top of the loop!")
        continue
    print("The current number number is: ", counter_variable, " and the while loop works just fine." )
    counter_variable += 1 

# Why does the code not work???
# Use the "interrupt" on the top to stop the kernel 

Excercise!

(Mögliche) Lösungen der Aufgaben aus dem Rep. Probiert sie erst selbst und schaut erst die Lösung an, wenn ihr hängen bleibt, oder die Lösungen vergleichen wollt!

my_list = range(0, 100, 1)
my_divisor = 4


for number in my_list: 
    if (number % my_divisor):
        print(number, " is not a multiple factor of ", my_divisor)
    else: 
        print(number, "is a multiple factor of ", my_divisor) 
from random import randint

game_rounds = int(input("How many times do you want to play?"))
result_list = []
game_counter = 0

while (game_counter < game_rounds): 
    guess_number = int(input("Select a number between 1 and 6!"))
    random_number = randint(1,6)
    if (random_number == guess_number): 
        print("Your guess was right!")
        result_list.append("Win")
    else: 
        print("Your guess was wrong!")
        result_list.append("Lose")
    game_counter += 1

print("Your game result is: ", result_list)
# Beantwortung der Frage, ob eine if-elif Kette nach dem ersten Match abbricht:
# Ja tut sie. Es ist also nicht wie in einem switch-case von C nötig, ein break 
# einzufügen. 

my_test_var = 3

if my_test_var > 1:     # Statement is True
    print("1")          # Code will be executed, elif chain will exit
elif my_test_var > 2:   # Statement will not be checked, due to the execution of the code above
    print("2")
elif my_test_var > 3: 
    print("3")
elif my_test_var > 4: 
    print("4")
elif my_test_var > 5: 
    print("5")