How to Add Two Conditions in an If Statement in Python
In Python, the if statement is a fundamental construct used for conditional execution of code. It allows you to specify certain conditions that, when met, will trigger the execution of a block of code. One common scenario is when you need to evaluate two conditions simultaneously. In this article, we will explore how to add two conditions in an if statement in Python.
To add two conditions in an if statement, you can use the logical operators `and` and `or`. The `and` operator returns `True` if both conditions are `True`, while the `or` operator returns `True` if at least one of the conditions is `True`. Let’s dive into some examples to illustrate this concept.
First, consider the following scenario: you want to check if a number is both positive and even. You can achieve this by combining two conditions using the `and` operator. Here’s an example:
“`python
number = 10
if number > 0 and number % 2 == 0:
print(“The number is positive and even.”)
else:
print(“The number is not positive and even.”)
“`
In this example, the if statement checks if the `number` is greater than 0 and if it is divisible by 2 with no remainder. If both conditions are met, the code inside the if block will be executed, printing “The number is positive and even.”
Now, let’s consider a scenario where you want to check if a number is either positive or even. In this case, you can use the `or` operator. Here’s an example:
“`python
number = 5
if number > 0 or number % 2 == 0:
print(“The number is positive or even.”)
else:
print(“The number is not positive and not even.”)
“`
In this example, the if statement checks if the `number` is greater than 0 or if it is divisible by 2 with no remainder. If either of the conditions is met, the code inside the if block will be executed, printing “The number is positive or even.”
It’s important to note that the order of the conditions matters when using the `and` and `or` operators. The `and` operator evaluates both conditions before returning a result, while the `or` operator evaluates the conditions from left to right and returns `True` as soon as one of the conditions is `True`.
By using the `and` and `or` operators, you can effectively add two conditions in an if statement in Python. This flexibility allows you to create more complex and precise conditions for your code, making it more robust and versatile.