This output when the content of the argument is'range'or'r' That output when the content of the argument is'ladder' or'l' I want to do that I tried to make a conditional branch by comparing strings
def function1(mode):
if mode == ('range' or 'r'):
x=1
elif mode == ('ladder' or 'l'):
x=2
return x
print(function1('r'))
'''Execution result
Traceback (most recent call last):
print(function1('r'))
return x
UnboundLocalError: local variable 'x' referenced before assignment
'''
Doesn't it react with ʻor? I tried to reverse the front and back of
==`
def function2(mode):
if ('range' or 'r') == mode :
x=1
elif ('ladder' or 'l') == mode :
x=2
return x
print(function2('r'))
'''Execution result
Traceback (most recent call last):
print(function2('r'))
return x
UnboundLocalError: local variable 'x' referenced before assignment
'''
What should I do (・ ω ・ \ `) I thought about it and tried using the list and the in operator.
def function3(mode):
if mode in ['range' ,'r']:
x=1
elif mode in ['ladder' ,'l']:
x=2
return x
print(function3('r'))
'''Execution result
1
'''
It went well I looked it up and didn't come out, so I thought it might be a problem for someone, so I wrote it down.
It may be embarrassing to make a note in python (・ ω ・ \ `)
By the way, there is also a comparison operator called ʻis`, but this seems to mean something like "Does the object point to itself?" And it seems to be a narrower usage.
Recommended Posts