from IPython.core.display import HTML

HTML(open("custom.html", "r").read())
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright (C) 2014-2023 Scientific IT Services of ETH Zurich,
Contributing Authors: Uwe Schmitt, Mikolaj Rybniski

4. If / elif / else¶

Logical values¶

Python has a type bool which can take two values True and False:

ok = True
print(ok, type(ok))
True <class 'bool'>

Comparisons:¶

Logical values result from comparing numbers:

notation meaning
a < b a is less than b
a > b a is greater than b
a <= b a is less than or equal to b
a >= b a is greater than or equal to b
a == b a is is equal to b
a != b a is not equal to b

Comment:

  • = aka variable assignment is a statement ("it does something")
  • == aka test for equality is an expression (it can be evaluated to compute a value)

Logical computations:¶

Logical values can be combined

notation meaning
a and b True if a and b are True
a or b True if a or b are True
not a True if a is False else False
print(3 > 4 or 4 > 3)
True
print(3 < 7 and 7 < 12)
True

Commment: operators &&, || and ! to express and, or and not are not supported in Python. Operators & and | exist though but perform bitwise logical and and or (https://en.wikipedia.org/wiki/Bitwise_operation)

if / elif /else¶

  • Python uses if, elif and else keywords for branching code execution.

  • No else if!

  • The level of indentation defines the blocks, no "end" statement or braces !

  • after if follow zero to n elifs and then zero ore one else.

def test_if_even(x):
    if x % 2 == 0:
        print(x, "is even")
    else:
        print(x, "is odd")


test_if_even(12)
12 is even

Indentations can be nested:

def some_tests(x):
    if x > 0:
        if x % 2 == 0:
            print(x, "is positive and even")
        else:
            print(x, "is positive and odd")
    elif x == 0:
        print(x, "is zero")
    else:
        print(x, "is negative")

Code blocks:¶

Rule:

A code block ends if the level of indentation becomes less than the indentation of the first line of the block. Or if the program ends.


Recommended:

Use multiples of 4 spaces for indentation 
some_tests(4)
4 is positive and even
some_tests(-1)
-1 is negative

jupyter Tip:

To indent / deindent a code block you can mark it with the mouse or SHIFT+cursor-key and then press TAB resp. SHIFT-TAB.

Exercise block 4¶

  1. Reread the examples above carefully.

Check questions¶

Please try to answer the following question using pen and paper. You can afterwards check your results by writing and running code:

  1. Which of the following expressions are valid Python: a =< 3, a == 3 and !(a == 7), a == false, b >= c, a == 3 || b ==7, (c = 8) or (b > 3)?

Programming exercises¶

  1. Write a function which takes one value and doubles this if the value is even, else return the value unchanged. So the function returns 4 for input 2 and 3 for input 3.

  2. Write a function which takes a value and tests if it is a multiple of three and if it is a multiple of four. The function prints an appropriate message for all four possible cases.

Homework¶

  1. Read https://en.wikipedia.org/wiki/Fizz_buzz and write a function which takes a number and prints the number resp. "fizz", "buzz" or "fizzbuzz" according to the rules of the game.

Optional exercises*¶

  1. Repeat string methods and write a function which checks if all characters in a string are upper-case.

  2. Try to forecast and understand the output of the following snippet:

def return_true():
    print("this is return_true function")
    return True


def return_false():
    print("this is return_false function")
    return False


print(return_true() or return_false())
print()
print(return_false() or return_true())
print()
print(return_true() and return_false())
print()
print(return_false() and return_true())
this is return_true function
True

this is return_false function
this is return_true function
True

this is return_true function
this is return_false function
False

this is return_false function
False
  1. "Recursion" aka "a function calls itself": Try to understand what the following function computes:
def compute(n):
    if n <= 1:
        return 1
    return n * compute(n - 1)

Can you implement a function which computes the sum of the first n numbers using recursion ?