When we want to do something based on an specific value, or do something if a value is equal to something or do something else if the value is different than that, we use control flow for example we want to create a program that reads user age and prints whether or not he can enter to the bar
In this case we can use the if conditional, the if sintaxis works like this
if (conditional):
(statements)
“If this is true then do this (statements)”
age = input(“Whats your age? “)
if age >= 18:
print(“You may come in”)
This program checks if the age is bigger or equal than 18 and if the age is, it prints the string, if the age is less than 18 the statements in if will be ignored.
If we wanted to do something
age = input(“Whats your age? “)
if age >= 18:
print(“You may come in”)
else:
print(“Weenie hut is next door kid”)
Now we have something to handle when the condition is set to false.
Simple if this is something, do this, if not do that instead
But what if we want to check for another condition if the first one is met? Well in many programming language we would be required to put an if inside the else, but python is helpful including the elif statement, this one works like this
if (condition): #If the first is true
#Do This
elif (anotherCondition): #If the one above this False
#Do this
elif (someOtherCondition): #Do this if the one above false
#Do this
else: #This one is run if non of the conditions is met
#Do this
#Here we continue the program
This way we can do specific things depending on the value of our variables
Here is a simple flowchart for easier understanding:
But what if we need to do more things depending in more values, for example checking if the user is male or female then checking if he/she is old enough to drink
Lets review this code:
age = int(input(“Whats your age: “))
if age >= 18:
gender = input(“Whats your gender: “)
if gender == “Male”:
print(“No males allowed on Thursdays”)
if gender == “Female”:
print(“Welcome to Juanitos Bar”)
The program first checks if the user age is bigger or than 18, if he/she is, we check if he is a female or male