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: Complete Python Programming Course & Exercises
Example
In the example below we show the use of if-statements.
Copy the program below and run it.1
2
3
4
5
6
7
8
9
10
11
12
13#!/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):
Exercise
Do these exercises:
1 | 1\. Make a program that asks the number between 1 and 10\. |
Once completed continue with the next exercise.