Welcome back! In this section, we're diving into the heart of making your Python programs dynamic and intelligent: Conditional Statements. These are the tools that allow your code to make decisions, executing different blocks of code based on whether certain conditions are true or false. Think of them as the 'if this, then that' logic that powers so much of what computers do.
The most fundamental conditional statement in Python is the if statement. It allows you to execute a block of code only if a specific condition evaluates to True. If the condition is False, the code block within the if statement is skipped.
age = 25
if age >= 18:
print("You are an adult.")In the example above, the condition age >= 18 is evaluated. Since 25 is indeed greater than or equal to 18, the condition is True, and the message 'You are an adult.' is printed. If age were, say, 16, the condition would be False, and nothing would be printed.
What if you want to execute one block of code if a condition is true, and another block if it's false? That's where the else statement comes in. It pairs with an if statement to provide a default action when the if condition is not met.
temperature = 15
if temperature > 25:
print("It's a hot day!")
else:
print("It's not too hot.")Here, since temperature (15) is not greater than 25, the if condition is False. Therefore, the code within the else block is executed, printing 'It's not too hot.'
graph TD;
A[Start]
B{Condition True?}
C[Execute If Block]
D[Execute Else Block]
E[End]
A --> B;
B -- Yes --> C;
B -- No --> D;
C --> E;
D --> E;
But what about situations where you have more than two possibilities? For instance, you might want to check if a number is positive, negative, or zero. This is where the elif (short for 'else if') statement shines. You can chain multiple elif statements after an if to check a series of conditions in order.