Today you will learn to:
if, elif, and elseand, or, notBy the end, you will be able to write programs that respond to input.
Programs often need to make decisions.
Examples:
For that, we use conditions.
if means:
If a condition is true, then execute the code.
age = 20
if age >= 18:
print("You are an adult")
Explanation:
if starts a condition>= means greater than or equal toSometimes something should happen if the condition is false.
For that, there is else.
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are still a minor")
Explanation:
else blockSometimes there are multiple possibilities.
For that, we use elif.
points = 80
if points >= 90:
print("Grade A")
elif points >= 75:
print("Grade B")
elif points >= 60:
print("Grade C")
else:
print("Failed")
Explanation:
if → first conditionelif → additional conditionselse → if nothing else matchesThese operators are used to compare values.
== → equal!= → not equal> → greater< → less>= → greater or equal<= → less or equalExamples:
number = 10
if number == 10:
print("The number is 10")
if number != 5:
print("The number is not 5")
Sometimes multiple conditions need to be checked at the same time.
Both conditions must be true.
age = 20
has_ticket = True
if age >= 18 and has_ticket == True:
print("You may enter")
Only one condition must be true.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend")
Reverses a condition.
rain = False
if not rain:
print("It is not raining")
name = input("What is your name? ")
age = int(input("How old are you? "))
if age >= 18:
print("Hello", name)
print("You are an adult")
else:
print("Hello", name)
print("You are still a minor")
The % operator returns the remainder of a division.
Example:
10 % 2 = 0
9 % 2 = 1
This is often used to check if a number is even or odd.
Write a program that checks whether a number is even or odd.
Steps:
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")