Skip to content

Conditions

Of course, you don't always do the same thing in the programme. So we have to react to changing situations. This is done with conditions. In Python there is the keyword if.

For example, a programme can decide whether a number is even or odd:

value = 42
if value % 2 == 0:
    print("The number is even.")
else:
    print("The number is uneven.")

Here you can already see the general syntax:

if (<condition>):
    <code_A>
else:
    <code_B>

Python therefore checks the condition (condition) in the brackets. If it is true, <code_A> is executed, otherwise <code_B>.

Several conditions can be checked using and and or:

value = 42
if value % 2 == 0 or value > 10:
    print("The number is greater than 10.")

In this case, the conditions are not all checked: as soon as the result has been determined, a further check is no longer necessary for reasons of efficiency. In this case, this means that the number 42 is even and the check for value > 10 is no longer carried out.

Each condition is implicitly converted into a truth value. This means that the conversion rules that we have already learnt about with truth values apply again. This would make the following equivalent (albeit more difficult to read):

value = 42
if not value % 2 or value > 10:
    print("The number is even or greater than 10.")

If conditions are to be checked separately, we can use elif:

value = 42
if value % 2 == 0:
    print("The numer is even.")
elif value > 10:
    print("The number is greater than 10.")
else:
    print("The number is odd or smaller than 10.")

It should be noted here that elif is only checked if the previous condition does not apply. So if value is even, it is only output that the number is even. The check as to whether it is also greater than ten is no longer carried out. This check is only carried out for odd numbers. The final else is only executed if none of the previous conditions apply.

Each condition requires at least one instruction as to what should happen. If you want to carry out several steps if a condition is fulfilled, you can indent several lines:

value = 42
if value % 2 == 0:
    print("The number is even.")
    print("The number is even.")

More on this in the section on blocks.