A condition evaluates as true or false. After one branch runs, Python skips the rest of that chain and continues after the indented block. An else has no condition.
02 / Operators at a glance
Comparison and logical operators
Operator
Meaning
Example
==
Equal to
x == 5
!=
Not equal to
x != 5
>
Greater than
x > 5
<
Less than
x < 5
>=
Greater than or equal to
x >= 5
<=
Less than or equal to
x <= 5
and
Both conditions must be true
age >= 13 and age <= 19
or
At least one condition must be true
day == "Sat" or day == "Sun"
not
Reverse the condition
not is_ready
in / not in
Membership / non-membership
choice in ("yes", "y")
Python also supports chained comparisons: 0 <= grade <= 100 means grade >= 0 and grade <= 100. Use parentheses to make mixed and/or conditions clear; not binds before and, then or.
03 / Useful patterns
Separate ifs or one chain?
Separate if statements can both run. An if/elif chain chooses at most one branch.
score = 95
if score >= 50:
print("Passed")
if score >= 90:
print("Excellent")
# Both messages print.
Nested conditions
Put an if inside another if when the second decision depends on the first.
has_ticket = True
age = 16
if has_ticket:
if age >= 12:
print("Enter the show")
else:
print("An adult must accompany you")
else:
print("You need a ticket")
Boolean values and membership
Use Boolean variables directly. in checks membership; not reverses a condition. Empty strings, zero, None, and empty collections are falsy.
is_ready = True
choice = "yes"
if is_ready and choice in ("yes", "y"):
print("Start")
if not is_ready:
print("Wait")
Short conditional expression
Useful for a simple choice between two values. Keep longer decisions in normal blocks.
age = 16
label = "adult" if age >= 18 else "child"
print(label)
Handle non-numeric input
input() returns a string. int() accepts whole numbers; float() also accepts decimals. Bad numeric text raises ValueError before an if can check its range. Use try/except when you need to handle it.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a whole number.")
else:
if age < 0:
print("Age cannot be negative.")
else:
print("Valid age.")
04 / Twelve practical examples
Run each example separately in Python 3. Numeric examples assume valid numeric text unless they explicitly use try/except. They check ranges after conversion.
Example 01
Positive or not
Zero is not positive. Use > rather than >=.
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
else:
print("The number is not positive.")
Example 02
Pass or fail
Validate the range first, then check the pass mark. These examples use a pass mark of 50.
grade = int(input("Enter your grade: "))
if grade < 0 or grade > 100:
print("Invalid grade. Enter 0 to 100.")
elif grade >= 50:
print("You passed the class.")
else:
print("You failed the class.")
Example 03
Even or odd
% gives the remainder. An integer is even when dividing by 2 leaves no remainder.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Example 04
Adult or child
For this exercise, adult means age 18 or above. Reject negative ages first.
age = int(input("Enter your age: "))
if age < 0:
print("Invalid age.")
elif age >= 18:
print("You are an adult.")
else:
print("You are a child.")
Example 05
Larger of two numbers
After checking both greater-than cases, the only remaining possibility is equality.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if num1 > num2:
print("The larger number is", num1)
elif num2 > num1:
print("The larger number is", num2)
else:
print("The numbers are equal.")
Example 06
Numerical grade to letter grade
Check from highest to lowest. Earlier branches have already ruled out higher grades. This is a practice scale, not official Cambridge grade boundaries.
grade = int(input("Enter your grade: "))
if not 0 <= grade <= 100:
print("Invalid grade. Enter 0 to 100.")
elif grade >= 90:
print("You got an A.")
elif grade >= 80:
print("You got a B.")
elif grade >= 70:
print("You got a C.")
elif grade >= 60:
print("You got a D.")
else:
print("You got an F.")
Example 07
Hot, warm, or cold
With these chosen thresholds, 30°C is warm and 20°C is cold. float() also accepts decimal temperatures.
temperature = float(input("Temperature in Celsius: "))
if temperature > 30:
print("It is hot.")
elif temperature > 20:
print("It is warm.")
else:
print("It is cold.")
Example 08
Compare two strings
This keeps the username/password comparison as a string exercise. Equality is case-sensitive. It does not authenticate a user; use made-up values, not a real password.
username = input("Enter a practice username: ")
password = input("Enter a practice password: ")
if username == password:
print("The strings match.")
else:
print("The strings do not match.")
Example 09
Leap year
For Gregorian calendar years: divisible by 400, or divisible by 4 but not by 100. 2000 is a leap year; 1900 is not.
year = int(input("Enter a year: "))
if year <= 0:
print("Enter a positive year.")
elif year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("This is a leap year.")
else:
print("This is not a leap year.")
Example 10
Simple calculator
Check the operator and guard both division operations against zero. / divides; // performs floor division (rounds down, so -5 // 2 is -3).