The if and else statements are fundamental control structures in Python. They allow you to execute certain blocks of code based on specific conditions. In this tutorial, we’ll explore how to use them effectively.
if Statement?The if statement evaluates a condition, and if the condition is True, it executes the block of code indented beneath it. Here's an example:
x = 10
if x > 5:
print("x is greater than 5")Output:
x is greater than 5else StatementAn else statement provides an alternative block of code to execute when the condition in the if statement is False:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")Output:
x is not greater than 5elif for Multiple ConditionsThe elif (short for "else if") statement lets you check multiple conditions:
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not greater than 10")
else:
print("x is 5 or less")Output:
x is greater than 5 but not greater than 10if StatementsYou can nest if statements to check more complex conditions:
x = 8
y = 15
if x > 5:
if y > 10:
print("x is greater than 5 and y is greater than 10")Output:
x is greater than 5 and y is greater than 10Use logical operators like and, or, and not to combine conditions:
x = 7
y = 12
if x > 5 and y > 10:
print("Both conditions are True")Output:
Both conditions are TruePractice writing your own if, elif, and else statements with various conditions. Understanding control flow is essential for solving problems in Python. Happy coding! To learn more check out loops in python!