Sometimes, we want to check if multiple conditions are correct before running the code in an ‘if statement’. We can do this using the ‘and’ operator. Here’s an example…
age = int(input("Enter your age: ")) skill_level = int(input("Rate your programming skill level on a scale of 1-10: ")) if age >= 22 and skill_level >= 8: print("You should consider getting a job!") elif age >= 22 and skill_level < 8: print("You should consider learning Python!") else: print("Keep exploring the field and have fun!")
Enter your age: 18 Rate your programming skill level on a scale of 1-10: 9 Keep exploring the field and have fun!
Basically, this program asks for your age and your skill level. If you are over 22 and very skilled, it suggests a job. If you are not very skilled but over 22, it suggests learning Python. If you are less than 22, no matter how skilled, it suggests having fun! Notice how the program uses the ‘and’ keyword to check for two conditions in one if statement.
Note: The int() is used to convert from data from a string type to an integer type. This allows us to then perform math operations on the number.
Similarly, we can also check if one of two or more conditions is True. If one of them is True, then we can run the code in the if statement, thanks to the ‘or’ keyword! Here’s an example…
has_paid = False has_coupon = True if has_coupon==True or has_paid==True: print("Ok, you are allowed to watch the movie")
Ok, you are allowed to watch the movie
This program checks to see if the person either has paid for a ticket to a movie, or has a coupon for the movie. If the person has either, he/she is allowed to watch the movie. This is just one simple example of the potentially infinite number of uses for the ‘or’ keyword.