Python if несколько условий and

How to use AND Operator in Python IF Statement?

You can combine multiple conditions into a single expression in Python conditional statements like Python if, if-else and elif statements. This avoids writing multiple nested if statements unnecessarily.

In the following examples, we will see how we can use Python AND logical operator to form a compound logical expression.

Examples

1. If Statement with AND Operator

In the following example, we will learn how to use AND logical operator, in Python If statement, to join two boolean conditions to form a compound expression.

To demonstrate the advantage of and operator, we will first write a nested if, and then a simple if statement where in this simple if statement realizes the same functionality as that of nested if.

Python Program

a = 5 b = 2 #nested if if a==5: if b>0: print('a is 5 and',b,'is greater than zero.') #or you can combine the conditions as if a==5 and b>0: print('a is 5 and',b,'is greater than zero.')

Here, our use case is that, we have to print a message when a equals 5 and b is greater than 0. Without using and operator, we can only write a nested if statement, to program out functionality. When we used logical and operator, we could reduce the number of if statements to one.

a is 5 and b is greater than zero. a is 5 and b is greater than zero.

2. Python If-Else Statement with AND Operator

In the following example, we will use and operator to combine two basic conditional expressions in boolean expression of Python If-Else statement.

Python Program

a = 3 b = 2 if a==5 and b>0: print('a is 5 and',b,'is greater than zero.') else: print('a is not 5 or',b,'is not greater than zero.')
a is not 5 or 2 is not greater than zero.

3. Python elif Statement with AND Operator

In the following example, we will use and operator to combine two basic conditional expressions in boolean expression of Python elif statement.

Python Program

Summary

In this tutorial of Python Examples, we learned how to use Python and logical operator with Python conditional statement: if, if-else and elif with well detailed examples.

Читайте также:  Php выражения для валидации

Источник

How to Check Multiple Conditions in a Python if statement

Conditional statements are commands for handling decisions, which makes them a fundamental programming concept. They help you selectively execute certain parts of your program if some condition is met. In this article, we’ll tell you all you need to know about using multiple conditional statements in Python. And we’ll show you plenty of examples to demonstrate the mechanics of how it all works.

Python has a simple and clear syntax, meaning the code is easy to read and interpret. This is especially true for conditional statements, which can almost be read like an English sentence. This makes Python a great language to learn for beginners. For those of you who are new to Python, consider taking our Python Basics course; it will kickstart your programming journey and give you solid foundational skills in Python.

Python if Statement

The starting point for handling conditions is a single if statement, which checks if a condition is true. If so, the indented block of code directly under the if statement is executed. The condition must evaluate either True or False . If you’d like to learn the details of Python’s if statements, you’ll find more in this article on Python terms for beginners. Part 2 of Python Terms for Beginners is also a worthwhile read when you’re just getting started with programming.

The if statement in Python takes the following form:

>>> if condition == True: . print('Condition is True')

Before we go further, let’s take a look at the comparison operators. In Python, there are six possibilities:

Note that the equals comparison operator ( == ) is different from the assignment operator ( = ).

Now let’s try evaluating an example condition:

>>> temperature = 35 >>> temperature > 25 True

Here, we set the variable temperature = 35 . In the next line, we test if this value is greater than 25, which returns the Boolean value True . Now let’s put this in an if statement:

>>> temperature = 35 >>> if temperature > 25: . print('Warm') Warm

The condition evaluates to true, which then executes the indented block ( print(‘Warm’) ). This example is equivalent to writing “If the temperature is greater than 25, print the word “Warm”. As you can see from the code, it’s quite like the written sentence!

Читайте также:  Best java learning book

Logical Operators

If we want to join two or more conditions in the same if statement, we need a logical operator. There are three possible logical operators in Python:

  • and – Returns True if both statements are true.
  • or – Returns True if at least one of the statements is true.
  • not – Reverses the Boolean value; returns False if the statement is true, and True if the statement is false.

To implement these, we need a second condition to test. So, let’s create another variable and test if it’s above a threshold:

>>> temperature = 35 >>> humidity = 90 >>> if temperature > 30 and humidity > 85: . print('Hot and humid') Hot and humid

The or operator requires only one condition to be True . To show this, we’ll reduce the temperature and use the or comparison operator:

>>> temperature = 20 >>> humidity = 90 >>> if temperature > 30 or humidity > 85: . print('Hot, humid, or both') Hot, humid, or both

Notice that or only requires one condition to evaluate to True . If both conditions evaluate to True , the indented block of code directly below will still be executed.

The not operator can seem a little confusing at first, but it just reverses the truth value of a condition. For example:

>>> not True False >>> not False True

We can use it to test if the temperature is colder (i.e. not hotter) that a threshold:

>>> temperature = 15 >>> if not temperature > 20: . print('Cool') Cool

Using these as building blocks, you can start to put together more complicated tests:

>>> temperature = 25 >>> humidity = 55 >>> rain = 0 >>> if temperature > 30 or humidity < 70 and not rain >0: . print('Dry conditions') Dry conditions

This if statement is equivalent to “If temperature is greater than 30 (i.e. evaluates false) OR humidity is less than 70 (evaluates to true) and it’s not raining (evaluates to true) , then write …”. In code, it might look like this:

>>> if False or True and True: . print('Dry conditions') Dry conditions

Python’s if-elif-else Statements

So, what happens when the condition in the if statement evaluates to False? Then we can check multiple conditions by simply adding an else-if statement, which is shortened to elif in Python. Here’s an example using elif to define different temperature categories:

>>> temperature = 25 >>> if temperature > 30: . print('Hot') >>> elif temperature > 20 and temperature 
>>> temperature = 25 >>> if temperature > 30: . print('Hot') >>> elif temperature > 20 and temperature >> else: . print('Cool') Warm

The final else statement handles anything else that does not fall within the other statements. In this case, temperature

If you wanted to make more categories, you could add more elif statements. The elif and else statements are optional. But it’s always good form to finish with an else statement, to make sure anything unexpected is still captured. This can be useful for debugging more complicated conditional statements. For example, if we’re quantifying the amount of rain in millimeters per hour, we could do something like this:

>>> rain = -10 >>> if rain > 0 and rain >> elif rain > 3 and rain >> elif rain > 8: . print('Heavy rain') >>> else: . print('Something unexpected happened!') Something unexpected happened!

Having the final else statement here will alert you if there is an unexpected error somewhere, e.g. a negative value.

Now That You Know Multiple Conditions in Python …

Now you should have all you need to know to start implementing multiple conditional statements in Python. These examples were designed to show you the basics of how these statements work, so take the next step and extend what you’ve learnt here. For example, try combining if-elif-else statements in a loop. Define a list of values, loop through them, and test their values. If you need some background material on for loops in Python, check out How to Write a For Loop in Python.

If you’re interested in learning more about data structures in Python, we’ve got you covered. In Arrays vs. Lists in Python, we explain the difference between those two structures. We also have an article that goes into detail on lists, tuples and sets and another that explains the dictionary data structure in Python. With a bit of practice, you’ll soon master Python’s conditions, loops, and data structures.

Источник

Оцените статью