The if statement
if runs some code only when a condition is True:
temperature = 35
if temperature > 30:
print("It's hot! Drink water.")
print("Have a nice day.")Output
It's hot! Drink water. Have a nice day.
Two important details:
- The line with
ifends with a colon:. - The code that belongs to the
ifis indented (pushed right by 4 spaces). This indented group is called a block.
The last line isn't indented, so it always runs.
Think of it like this: Indentation is like the steps under a heading in a to-do list. Everything indented under “If it rains” only happens when it rains.
if ... else
else gives a plan B: the code to run when the condition is False.
age = 15
if age >= 18:
print("You can vote.")
else:
print("You can't vote yet.")Output
You can't vote yet.
elif: more than two choices
elif means “else if”. Python checks each condition from top to bottom and runs the first one that is True. The rest are skipped.
marks = 72
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Keep practising!")Output
Grade C
72 isn't ≥ 90 or ≥ 75, but it is ≥ 50, so we get Grade C.
With input
number = int(input("Enter a number: "))
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")Output (when you type 7)
Enter a number: 7 7 is odd
Common mistake: Forgetting the colon or the indentation. Both cause an error. Most editors indent automatically after you type a colon and press Enter.
Remember: Only one block runs in an
if/elif/elsechain – the first one whose condition is True.