A program sometimes may have to make choices. These choices can execute different code depending on certain condition. In Python the if statement is used for conditional execution.

The if statement may be combined with certain operator such as equality (==), greater than (>=), smaller than (<=) and not equal (!=). Conditions may be combined using the keywords or and and.

Related course: Python Crash Course: Master Python Programming!

Example

In the example below we show the use of if-statements.
Copy the program below and run it.

#!/usr/bin/env python3

gender = input("Gender? ")
if gender == "male" or gender == "Male":
print("Your cat is male")
else:
print("Your cat is female")

age = int(input("Age of your cat? "))
if age < 5:
print("Your cat is young.")
else:
print("Your cat is adult.")

Visual example of if statement (click to enlarge):
if statement

Exercise

Do these exercises:

1\. Make a program that asks the number between 1 and 10\. 
If the number is out of range the program should display "invalid number".

2\. Make a program that asks a password.

Once completed continue with the next exercise.

Download answers