Python if and condition example

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!

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.
Читайте также:  Php if date less

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.

Источник

Python If . Else

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

In this example we use two variables, a and b , which are used as part of the if statement to test whether b is greater than a . As a is 33 , and b is 200 , we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

Example

In this example a is equal to b , so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b , so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif :

Example

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

Short Hand If . Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example

One line if else statement:

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example

One line if else statement, with 3 conditions:

And

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b , AND if c is greater than a :

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b , OR if a is greater than c :

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional statement:

Example

Test if a is NOT greater than b :

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

Источник

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