包括作为if条件中的元素的功能



在"if"函数的初始化过程中,函数是否可以像普通变量一样在if条件中使用?我在我的程序中尝试过这个,但没有成功。

def choices():
choice = input('Choose which path to take out... Think carefully 😁😁😁😁😁 type left(l) or right(r) ').upper()
choices()

if choices() == 'LEFT' or choices() == 'L':
print('left')
elif choices() == 'RIGHT' or choices() == 'R':
print('right')

如注释所示,您需要从choices函数返回一个值,然后在比较中使用它。因此,下面这样的实现将几乎正常工作:

def choices():
choice = input('Choose which path to take out... Think carefully 😁😁😁😁😁 type left(l) or right(r) ').upper()
return choice
if choices() in ["L", "LEFT"]:
print('left')
elif choices() in ["R", "RIGHT"]:
print('right')

在上面的情况下,如果第一个选项是r,那么您需要两次输入,这是不好的。所以,最好的方法是每个周期只获得一次用户输入,并在提供有效值时退出:

def choices():
choice = input('Choose which path to take out... Think carefully 😁😁😁😁😁 type left(l) or right(r) ').upper()
return choice

while True:
# Get input only once per cycle
choice = choices()
if choice in ["L", "LEFT"]:
print('left')
break
elif choice in ["R", "RIGHT"]:
print('right')
break

最新更新