Python/if Statements
[i]Learn· More Control Flow Tools

if Statements

As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter.

Perhaps the most well-known statement type is the if statement. For example:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

If you’re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful. For more details see match Statements.

Source: More Control Flow Tools by Python Software Foundation, licensed under PSF-2.0. Retrieved 2026-11-18. Changes: Extracted section 4.1 with the introduction of chapter 4 from The Python Tutorial (Python 3.14), https://docs.python.org/3.14/tutorial/controlflow.html; removed section numbers, permalinks and site navigation; code blocks kept as shown.