A program often needs to choose what happens next. Conditional statements let Python run different blocks depending on whether a condition evaluates to True or False.
if statementAn if statement runs its indented block only when its condition is true. The condition is usually a comparison, such as marks >= 40. A colon ends the condition line and the following block must be indented.
Indentation is part of Python syntax. Use four spaces consistently. If a line belongs inside the conditional block, it must have the same indentation level as the other statements in that block.
else and elifUse else when every case not covered by the if condition should follow one alternative path. Use elif to test another condition before reaching the final else.
Python checks these conditions from top to bottom and runs the first matching block. Put more specific or higher-priority cases first so a broad condition does not hide a case that should be handled separately.
Use and when all conditions must be true and or when any one of them is enough. For example, an account may be active only when the user has verified an email and has not been blocked.
Keep conditions readable. Store a complicated condition in a clearly named Boolean variable when that makes the decision easier to understand.
marks = int(input("Enter your marks: "))
if marks >= 80:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 40:
print("Grade: C")
else:
print("Result: Try again")
age = int(input("Age: "))
has_id = input("Do you have an ID? yes/no: ")
if age >= 18 and has_id == "yes":
print("Entry allowed")
else:
print("Entry not allowed")
Ask for a number and report whether it is positive, negative or zero. Use if, elif and else.
number = int(input("Number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")