Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple conditions for one if statement in python [duplicate]

So I am writing some code in python 3.1.5 that requires there be more than one condition for something to happen. Example:

def example(arg1, arg2, arg3):     if arg1 == 1:         if arg2 == 2:             if arg3 == 3:                 print("Example Text") 

The problem is that when I do this it doesn't print anything if arg2 and arg3 are equal to anything but 0. Help?

like image 724
SooBaccaCole Avatar asked Apr 21 '16 01:04

SooBaccaCole


People also ask

Can you have multiple conditions in an if statement Python?

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else .

How do you write a multiline IF statement in Python?

The recommended style for multiline if statements in Python is to use parenthesis to break up the if statement. The PEP8 style guide recommends the use of parenthesis over backslashes and putting line breaks after the boolean and and or operators.

How do you check multiple conditions in one if statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.


1 Answers

I would use

def example(arg1, arg2, arg3):      if arg1 == 1 and arg2 == 2 and arg3 == 3:           print("Example Text") 

The and operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or operator if you want that logic gate.

EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.

like image 71
SSung2710 Avatar answered Sep 17 '22 12:09

SSung2710