Conditional statements in Python allow you to execute certain pieces of code based on the value of some conditions. The most common conditional statements are if
, else
, and elif
.
The if
statement is used to test a condition. If the condition is true, the block of code inside the if
statement will be executed.
age = 18 if age >= 18: print("You are an adult.")
You are an adult.
age
is less than 18?age
is less than 18, the condition age >= 18
will be false, and the block of code inside the if
statement will not be executed.
The else
statement can be combined with an if
statement to provide an alternative block of code to execute if the condition is false.
age = 16 if age >= 18: print("You are an adult.") else: print("You are a minor.")
You are a minor.
else
statement exist without an if
statement?else
statement cannot exist without an if
statement. It is always paired with an if
statement to handle the false case.
The elif
statement stands for "else if" and allows you to check multiple conditions sequentially. Once a condition is true, the corresponding block of code is executed, and the rest of the elif
statements are skipped.
age = 20 if age < 13: print("You are a child.") elif age < 18: print("You are a teenager.") else: print("You are an adult.")
You are an adult.
age
is 15?age
is 15, the output will be "You are a teenager." because the condition age < 18
will be true.
You can combine if
, elif
, and else
statements to create complex conditional logic.
score = 75 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")
Grade: C
score
is 85?score
is 85, the output will be "Grade: B" because the condition score >= 80
will be true.
Conditional statements are a fundamental part of programming that allow you to control the flow of your program based on different conditions. By understanding and using if
, else
, and elif
statements, you can create more complex and flexible programs.