Conditions: if, elif, else
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
if runs a block of code only if the condition is true. The block is marked with an indent of 4 spaces — it isn't decoration, it's part of the syntax:
age = int(input())
if age >= 18:
print("Access granted")
print("Welcome") # also inside the if
print("This always runs") # no indent — already outside the if
else — what to do if the condition is false. elif ("else if") — check the next condition:
t = int(input())
if t < 0:
print("Freezing")
elif t < 20:
print("Cool")
else:
print("Warm")
Python checks the conditions from top to bottom and runs only the first branch that fits. That's why the order of the elifs matters.
Don't forget the colon : at the end of lines with if, elif, else — it's the most common mistake.
Task. Read a year and print leap or common. A year is a leap year if it divides by 4 but not by 100, or if it divides by 400. For example, 2024 and 2000 are leap years, but 1900 isn't.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.