If-else branch

Which program path is selected at a branch always depends on whether a certain condition is fulfilled or not.

UML 1.x activity diagramUML 1.x activity diagram of an if-else branch

In Python, the if keyword is followed by the condition that ends with a colon :.
If this condition is not met, i.e. the result of the check is false, then the if branch is skipped and else path is executed.

1
2
3
4
5
age = int(input("Enter age: "))
if age >= 18:
    print("adult")
else:
    print("child")

(In Python, the indentation indicates which commands belong to the respective program path.)


if-elif-else branches

Any number of elif branches (abbreviation for else if) with respective conditions can be inserted in between:

1
2
3
4
5
6
7
age = int(input("Enter age: "))
if age >= 18:
    print("adult")
elif age >= 10:
    print("teen")
else:
    print("child")

UML 1.x activity diagram of if-elif-else branch

UML 1.x activity diagram of if-elif-else branch

The conditions are checked sequentially and only the program path of the first true condition is executed. The else path is only executed if no condition is true.

Match-case branches

Since Python 3.10, match-case branches correspond to the switch-case branches known from C or Java, for example.
The above problem can therefore also be solved in this way:

1
2
3
4
5
6
7
8
age = int(input("Enter age: "))
match age:
    case age if age >= 18:
        print("adult")
    case age if age >= 10:
        print("teen")
    case _:
        print("child")

The “_” is the wildcard character that runs when all the cases fail to match the parameter value.

A variety of options are described here:
Python Match Case Statement - GeeksforGeeks   (05.09.2024)
Last modified: Thursday, 5 September 2024, 11:06 AM