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.
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.