Conditional statements allow your program to make decisions based on conditions that are either True or False.
Comparison operators return True or False.
print(5 == 5)
print(5 != 3)
print(5 > 3)
print(5 < 3)
print(5 >= 5)
print(5 <= 4)
print(True and False)
print(True or False)
print(not True)
if Statement
age = 18
if age >= 18:
print("You are an adult")
else Statement
else runs when the if condition is False.
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are under 18")
elif Statement
elif means "else if" and allows multiple conditions.
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
else:
print("Grade F")
x = 10
if x == 10:
print("x is ten")
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")
Python uses indentation to define blocks of code. Incorrect indentation will cause errors.
= instead of ==:Complete the following exercises to reinforce your understanding of if statements.
Ask the user for an integer input. Write a program that prints whether the number is "Even" or "Odd" using an if-else statement [3].
Ask the user for a numerical grade ($0$-$100$). Using if-elif-else, print the letter grade:
Define a variable age. If age is 18 or older, print "You are an adult." Otherwise, print "You are a minor."
Take two numbers from the user (x and y). Print "Both are positive" if both numbers are greater than 0, otherwise print "At least one number is not positive" [2, 7].
Write a program that asks for a year and determines if it is a leap year. A year is a leap year if it is divisible by 4, but not by 100, unless it is also divisible by 400 [8].