How to Use Two Conditions in If Statement in Python
In Python, the if statement is a fundamental part of the language, allowing you to control the flow of your program based on certain conditions. Often, you may need to evaluate multiple conditions before deciding which path to take. This article will guide you on how to use two conditions in an if statement in Python, providing you with a clear understanding of the syntax and examples to help you implement this effectively in your code.
The syntax for using two conditions in an if statement in Python is quite straightforward. You can use the logical operators `and`, `or`, and `not` to combine two conditions. The `and` operator requires both conditions to be true, while the `or` operator requires at least one of the conditions to be true. On the other hand, the `not` operator is used to negate a condition.
Let’s take a look at some examples to illustrate the use of two conditions in an if statement:
1. Using the `and` operator:
“`python
age = 25
is_student = True
if age >= 18 and is_student:
print(“You are eligible to vote.”)
else:
print(“You are not eligible to vote.”)
“`
In this example, the `and` operator is used to check if the `age` variable is greater than or equal to 18 and if the `is_student` variable is `True`. If both conditions are true, the message “You are eligible to vote.” is printed. Otherwise, the message “You are not eligible to vote.” is printed.
2. Using the `or` operator:
“`python
score = 85
passing_score = 60
if score >= passing_score or score >= 90:
print(“You passed the exam.”)
else:
print(“You failed the exam.”)
“`
In this example, the `or` operator is used to check if the `score` variable is greater than or equal to the `passing_score` or if it is greater than or equal to 90. If either of these conditions is true, the message “You passed the exam.” is printed. Otherwise, the message “You failed the exam.” is printed.
3. Using the `not` operator:
“`python
is_raining = True
is_sunny = False
if not is_raining and is_sunny:
print(“It’s a sunny day.”)
else:
print(“It’s not a sunny day.”)
“`
In this example, the `not` operator is used to negate the `is_raining` condition. The if statement checks if it is not raining and sunny at the same time. If both conditions are true, the message “It’s a sunny day.” is printed. Otherwise, the message “It’s not a sunny day.” is printed.
By using these logical operators, you can effectively evaluate two conditions in an if statement in Python. This allows you to make more complex decisions based on multiple factors, enhancing the functionality and flexibility of your code.