Conditional statements allow us to make decisions and perform different actions based on whether a condition is True
or False
.
The most common conditional statement in Python is the if
statement. It allows us to execute a block of code only if a certain condition is true. Here's an example:
age = 15 if age >= 18: print("You are old enough to vote!")
In this example, we have a variable called age
with a value of 15
. The if
statement checks if the condition age >= 18
is true. If it is, the code inside the if
block (indented with four spaces) will be executed. In this case, since age
is not greater than or equal to 18
, the code inside the if
block will not be executed.
You can also include an else
statement to specify what should happen if the condition is false. Here's an example:
age = 15 if age >= 18: print("You are old enough to vote!") else: print("You are not old enough to vote yet.")
In this code, if the condition age >= 18
is true, the code inside the if
block will be executed. Otherwise, the code inside the else
block will be executed.
You can also use the elif
statement (short for "else if") to check multiple conditions. Here's an example:
age = 15 if age >= 18: print("You are old enough to vote!") elif age >= 16: print("You can get a driver's license!") else: print("You are not old enough to vote or get a driver's license yet.")
In this code, the first condition age >= 18
is checked. If it is true, the code inside the first if
block will be executed. If it is false, the next condition age >= 16
is checked. If it is true, the code inside the elif
block will be executed. If both conditions are false, the code inside the else
block will be executed.
Conditional statements are very useful for controlling the flow of your program based on different conditions. They allow us to make decisions and perform different actions depending on the situation.
If you want to repeat actions until a condition is met, read about the while loop.