Back to: Python Programming
Conditional statements allow code to be executed when a specific condition is met, it the condition is not met, some alternate code may run.
age = int(input("Enter your age: "))
if age >= 18:
print("You are old enough to vote!")
else:
print(f"You can vote in {18 - age} years.")
The indentation is important here and you can have multiple lines for each condition. You can also have a condition within another condition using ‘elif’ short for ‘else if’. There is no limit to the number of ‘elif’ conditions but their order does matter.
age = int(input("Enter your age: "))
if age >= 21:
print("You are old enough to drink in Australia and the USA.")
elif age >= 18:
print("You are old enough to drink in Australia,")
print("but not the USA.")
elif age <10:
print("You are much too young to drink alcohol.")
else:
print(f"In {18 - age} years you can drink in Australia.")
print(f"In {21 - age} years you can drink in the USA.")
Comparison operators are:
- > greater than
- >= greater than or equal to
- < less than
- <= less than or equal to
- == equal to
- != anything other than
response = input("Do you like Maths? (Y/N): ")
if response == "Y": #<-- the == is a comparison operator
print("You will be a good programmer!")
elif response != "N":
print("You need to enter Y or N!")
else:
print("Maths is easy if you work at it!")
Another example to check whether the user entered something:
name = input("Enter your name: ")
if name == "": #<-- the == "" check for blank input
print("You did not enter anything, dummy!")
else:
print(f"Good to see you, {name}")
A ‘boolean’ condition simply checks if the variable is set to True.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age < 18:
restricted = True
else:
restricted = False
if restricted:
print(f"Sorry {name}, you are too young to enter")
else:
print(f"Welcome {name}, you may now enter")
Exercise:
Write code using an if statement that asks for the user’s name via input() function. If the name is “Bond” make it print “Welcome on board 007”. Otherwise make it print “Good morning <name>”. (Replace <name> with user’s inputted name).
Exercise:
Extend the above code making sure that the code prints “Welcome on board 007” if the user types either “Bond” or “bond” or “BOND”.
hint: construct your logical statement with name.lower()