How to have multiple conditions for one if statement in python
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.
Can you make multiple if conditions in Python?
Python indeed allows you to do such a thing
if integer > 3 and integer < 34
Python is also smart enough to handle:if 3 < integer < 34:
# do your stuff
Styling multi-line conditions in 'if' statements?
You don't need to use 4 spaces on your second conditional line. Maybe use:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Also, don't forget the whitespace is more flexible than you might think:if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
Both of those are fairly ugly though.Maybe lose the brackets (the Style Guide discourages this though)?
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
This at least gives you some differentiation.Or even:
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
I think I prefer:if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
Here's the Style Guide, which (since 2010) recommends using brackets. Multiple IF statements in python
break
doesn't let you leave if
clauses, if that's what you are indeed attempting to break out of. The trick here is to remove the break
statements and replace your second if
s with elif
s like so:
if lineCount == 5:
if line[0]:
print line[0],'A5'
OPfound = 1
elif line[1]:
print line[1],'B5'
OPfound = 1
if lineCount == 4:
if line[0]:
print line[0],'A4'
OPfound = 1
elif line[1]:
print line[1],'B4'
OPfound = 1
This way you are only running through the second if
statement in each lineCount clause if the first one failed, not every time. Multiple if conditions, without nesting
I would write it like this, so the function ends once it encounters an error, and the most likely error should be on top, and if it encounters that error, it will return False and end the function. Else, it will check for all the other errors and then eventually conclude that the outcome is indeed True.
# testOutcome returns a boolean
outcome = testOutcome(a,b)
# Expects a and b
# Breaks out of the function call once error happens
def testOutcome(a,b):
# Most likely error goes here
if a != b:
print("Error - 01")
return False
# Followed by second most likely error
elif a["test_1"] != "test_value":
print("Error - 02")
return False
# Followed by third most likely error
elif "test_2" not in a:
print("Error - 03")
return False
# Least likely Error
elif a["test_3"] == "is long data string":
print("Error - 04")
return False
else:
return True
How to make a multiple if statements more pythonic and condensed?
Combine all the conditions into one:
good = type(USERNAME) == str and type(PASSWORD) == str and type(PHONE) == int AND type(CARRIER) == str and type(SERVER) == str
BTW, you generally shouldn't use int
for phone numbers. Even though we call them phone numbers we don't perform any numeric operations on them. And putting a phone number in an int
variable will lose leading zeroes. multiple if else conditions in pandas dataframe and derive multiple columns
You need chained comparison using upper and lower bound
def flag_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return 'Red'
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return 'Yellow'
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return 'Orange'
elif (df['height'] > 8):
return np.nan
df2['Flag'] = df2.apply(flag_df, axis = 1)
student score height trigger1 trigger2 trigger3 Flag
0 A 100 7 84 99 114 Yellow
1 B 96 4 95 110 125 Red
2 C 80 9 15 30 45 NaN
3 D 105 5 78 93 108 Yellow
4 E 156 3 16 31 46 Orange
Note: You can do this with a very nested np.where but I prefer to apply a function for multiple if-elseEdit: answering @Cecilia's questions
- what is the returned object is not strings but some calculations, for example, for the first condition, we want to return df['height']*2
def flag_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return df['height']*2
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return df['height']*3
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return df['height']*4
elif (df['height'] > 8):
return np.nan
- what if there are 'NaN' values in osome columns and I want to use df['xxx'] is None as a condition, the code seems like not working
isnull
would do the trickdef flag_df(df):
if pd.isnull(df['height']):
return df['height']
elif (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return df['height']*2
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return df['height']*3
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return df['height']*4
elif (df['height'] > 8):
return np.nan
One else for multiple if conditions
There are two ways to do this.
1). You can use one if
statement, and and
the conditions together. This will produce "short circuiting" behavior, in that it will continue through the functions until the first one fails, then none of the remaining will execute.
if function_1() and function_2() and function_3():
print "Everythings went well"
else:
Reboot
2) If you want all to execute, here is a method, though it is more cumbersome.:successful = True
successful = successful and function_1()
successful = successful and function_2()
successful = successful and function_2()
if successful:
print "Everythings went well"
else:
Reboot
Related Topics
How to Save and Restore Multiple Variables in Python
Python Using Variables from Another File
How to Customize Title Bar and Window of Desktop Application
Typeerror: Only Length-1 Arrays Can Be Converted to Python Scalars While Plot Showing
How to Specify Python Version Used to Create Virtual Environment
Download Image File from the HTML Page Source
How to Pickle a Dynamically Created Nested Class in Python
How to Get a Gcp Bearer Token Programmatically with Python
Python Progress Bar and Downloads
Looping from 1 to Infinity in Python
How to Get the Version Defined in Setup.Py (Setuptools) in My Package
Merging Dictionary Value Lists in Python
What Is the Official "Preferred" Way to Install Pip and Virtualenv Systemwide