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?
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With