Used to make decisions in a program based on conditions.
if
If the condition is True, the block will execute.
age = 21
if age >= 18:
print("you can vote")output
you can voteSyntax:
if condition:
print(" ")Note
Indentation is required in Python to define the block.
if-else
If the condition is True, if block runs
If False, else block runs
age = 12
if age >= 18:
print("you can vote")
else:
print("you cannot vote")output
you cannot voteSyntax:
if condition:
print(" ") # runs if True
else:
print(" ") # runs if Falseelif
Used to check multiple conditions.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")output
Grade BSyntax:
if condition1:
print(" ")
elif condition2:
print(" ")
else:
print(" ")Note
- Only one block will execute
elifmeans “else if”- Conditions are checked from top to bottom
Question
Write a program in Python to check age category:
< 13→ child
13–18→ teenager
18+→ adult
age = int(input("enter age: "))
if age < 13:
print("You are a child")
elif age >= 13 and age <= 18:
print("You are a teenager")
else:
print("You are an adult")output
enter age: 14
You are a teenagerQuestion
Write a program in Python to check username and password
username = input("enter username: ")
password = input("enter password: ")
if username == "admin" and password == "pass":
print("Login successful")
else:
print("Invalid username or password")output
enter username: admin
enter password: pass
Login successfulQuestion
Write a program in Python to check if a number is a multiple of 5 or not
num = int(input("enter a number: "))
if num % 5 == 0:
print("Number is a multiple of 5")
else:
print("Number is not a multiple of 5")output
enter a number: 20
Number is a multiple of 5Question
Write a program in Python to check if a number is odd or even
num = int(input("enter a number: "))
if num % 2 == 0:
print("Number is even")
else:
print("Number is odd")output
enter a number: 7
Number is odd<< Python User Input | Python Nesting >>