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.

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 branch

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

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.



Last modified: Monday, 28 October 2019, 7:17 PM