Condition check in python

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.

Читайте также:  Inline JavaScript

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.

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 Conditional Statements: IF…Else, ELIF & Switch Case

Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. Conditional statements are handled by IF statements in Python.

What is Python If Statement?

Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. If the condition is false, then the optional else statement runs which contains some code for the else condition.

When you want to justify one condition while the other condition is not true, then you use Python if else statement.

Python if Statement Syntax:

if expression Statement else Statement

Python if…else Flowchart

Python If Statement

Let’s see an example of Python if else Statement:

Python If Statement

# #Example file for working with conditional statement # def main(): x,y =2,8 if(x < y): st= "x is less than y" print(st) if __name__ == "__main__": main()
  • Code Line 5: We define two variables x, y = 2, 8
  • Code Line 7: The if Statement in Python checks for condition xTrue in this case
  • Code Line 8: The variable st is set to “x is less than y.”
  • Code Line 9: The line print st will output the value of variable st which is “x is less than y”,

What happen when “if condition” does not meet

In this step, we will see what happens when if condition in Python does not meet.

When if condition does not meet

  • Code Line 5: We define two variables x, y = 8, 4
  • Code Line 7: The if Statement in Python checks for condition xFalse in this case
  • Code Line 8: The variable st is NOT set to “x is less than y.”
  • Code Line 9: The line print st – is trying to print the value of a variable that was never declared. Hence, we get an error.

How to use “else condition”

The “else condition” is usually used when you have to judge one statement on the basis of other. If one condition goes wrong, then there should be another condition that should justify the statement or logic.

How to use else condition

# #Example file for working with conditional statement # def main(): x,y =8,4 if(x < y): st= "x is less than y" else: st= "x is greater than y" print (st) if __name__ == "__main__": main()
  • Code Line 5: We define two variables x, y = 8, 4
  • Code Line 7: The if Statement in Python checks for condition xFalse in this case
  • Code Line 9: The flow of program control goes to else condition
  • Code Line 10: The variable st is set to “x is greater than y.”
  • Code Line 11: The line print st will output the value of variable st which is “x is greater than y”,

When “else condition” does not work

There might be many instances when your “else condition” won’t give you the desired result. It will print out the wrong result as there is a mistake in program logic. In most cases, this happens when you have to justify more than two statement or condition in a program.

An example will better help you to understand this concept.

Here both the variables are same (8,8) and the program output is “x is greater than y”, which is WRONG. This is because it checks the first condition (if condition in Python), and if it fails, then it prints out the second condition (else condition) as default. In next step, we will see how we can correct this error.

When else condition does not work

# #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" else: st= "x is greater than y" print(st) if __name__ == "__main__": main()

How to use “elif” condition

To correct the previous error made by “else condition”, we can use “elif” statement. By using “elif” condition, you are telling the program to print out the third condition or possibility when the other condition goes wrong or incorrect.

How to use elif condition

# #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" elif (x == y): st= "x is same as y" else: st="x is greater than y" print(st) if __name__ == "__main__": main()
  • Code Line 5: We define two variables x, y = 8, 8
  • Code Line 7: The if Statement checks for condition xFalse in this case
  • Code Line 10: The flow of program control goes to the elseif condition. It checks whether x==y which is true
  • Code Line 11: The variable st is set to “x is same as y.”
  • Code Line 15: The flow of program control exits the if Statement (it will not get to the else Statement). And print the variable st. The output is “x is same as y” which is correct

How to execute conditional statement with minimal code

In this step, we will see how we can condense out the conditional statement. Instead of executing code for each condition separately, we can use them with a single code.

execute conditional statement with minimal code

def main(): x,y = 10,8 st = "x is less than y" if (x < y) else "x is greater than or equal to y" print(st) if __name__ == "__main__": main()
  • Code Line 2: We define two variables x, y = 10, 8
  • Code Line 3: Variable st is set to “x is less than y “if xy variable st is set to “x is greater than or equal to y.”
  • Code Line 4: Prints the value of st and gives the correct output

Instead of writing long code for conditional statements, Python gives you the freedom to write code in a short and concise way.

Python Nested if Statement

Following example demonstrates nested if Statement Python

total = 100 #country = "US" country = "AU" if country == "US": if total 

Uncomment Line 2 in above code and comment Line 3 and run the code again

Switch Case Statement in Python

What is Switch statement?

A switch statement is a multiway branch statement that compares the value of a variable to the values specified in case statements.

Python language doesn’t have a switch statement.

Python uses dictionary mapping to implement Switch Case in Python

For the above Switch case in Python

def SwitchExample(argument): switcher = < 0: " This is Case Zero ", 1: " This is Case One ", 2: " This is Case Two ", >return switcher.get(argument, "nothing") if __name__ == "__main__": argument = 1 print (SwitchExample(argument))

Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

# If Statement #Example file for working with conditional statement # def main(): x,y =2,8 if(x < y): st= "x is less than y" print st if __name__ == "__main__": main() # How to use "else condition" #Example file for working with conditional statement # def main(): x,y =8,4 if(x < y): st= "x is less than y" else: st= "x is greater than y" print st if __name__ == "__main__": main() # When "else condition" does not work #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" else: st= "x is greater than y" print st if __name__ == "__main__": main() # How to use "elif" condition #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" elif (x == y): st= "x is same as y" else: st="x is greater than y" print st if __name__ == "__main__": main() # How to execute conditional statement with minimal code def main(): x,y = 10,8 st = "x is less than y" if (x < y) else "x is greater than or equal to y" print st if __name__ == "__main__": main() # Nested IF Statement total = 100 #country = "US" country = "AU" if country == "US": if total return switcher.get(argument, "nothing") if __name__ == "__main__": argument = 1 print SwitchExample(argument)

Summary

A conditional statement in Python is handled by if statements and we saw various other ways we can use conditional statements like Python if else over here.

  • “if condition” – It is used when you need to print out the result when one of the conditions is true or false.
  • “else condition”- it is used when you want to print out the statement when your one condition fails to meet the requirement
  • “elif condition” – It is used when you have third possibility as the outcome. You can use multiple elif conditions to check for 4 th ,5 th ,6 th possibilities in your code
  • We can use minimal code to execute conditional statements by declaring all condition in single statement to run the code
  • Python If Statement can be nested

Источник

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