3 min read•june 24, 2024
Conditional statements are the backbone of decision-making in Python programs. They allow code to execute different blocks based on specific conditions, enabling dynamic responsive program flow.
, , and statements form the core of conditional logic. By combining these with comparison and , programmers can create complex decision trees, guiding program execution through various scenarios based on input and state.
if
statements enable conditional execution of code blocks based on whether a specified condition evaluates to [True](https://www.fiveableKeyTerm:TRUE)
[False](https://www.fiveableKeyTerm:FALSE)
if
statement executes only if the condition is True
(x > 5
)False
, the code block is skipped and program execution continues with the next statement after the if
blockif-else
statements provide an alternative code block to execute when the if
condition is False
if
statement executes if the condition is True
(temperature > 30
)else
statement executes if the if
condition is False
(temperature <= 30
)elif
(else if) statements allow for checking multiple conditions if the preceding if
or elif
conditions are False
True
will have its corresponding code block executed (grade >= 90
, grade >= 80
, etc.)True
, the code block under the else
statement (if present) will be executedif
statements start with the if
keyword, followed by a condition and a colon
True
or False
(count == 0
, name != "John"
)if
statement is indented (typically by 4 spaces)else
statements follow an if
statement and begin with the else
keyword and a colon
else
statement is also indentedelif
statements can be used between an if
and else
statement to check additional conditions
elif
statements begin with the elif
keyword, followed by a condition and a colonelif
statement is indentedif age >= 18: print("You are eligible to vote") elif age >= 16: print("You can pre-register to vote") else: print("You are [not](https://www.fiveableKeyTerm:not) eligible to vote yet")
True
or False
==
(equal to), !=
(not equal to), <
(less than), >
(greater than), <=
(less than or equal to), >=
(greater than or equal to)and
(both conditions must be True
), or
(at least one condition must be True
), not
(inverts the boolean value)if score > 100:
if MAX_VALUE == 100:
if is_valid_email(email):
temperature = 25 if temperature > 30: print("It's a hot day") print("Drink plenty of water") elif temperature > 20 and temperature <= 30: print("It's a nice day") else: print("It's a cold day") print("Wear warm clothes")
if outer_condition: if inner_condition: # Code block for both conditions true else: # Code block for outer true, inner false else: # Code block for outer false