gpt4 book ai didi

python - 如何使用 if、elif 和 else 运行多参数函数?

转载 作者:行者123 更新时间:2023-12-01 23:05:04 25 4
gpt4 key购买 nike

因此,我尝试制作一个根据输入将变量加一的函数,但出现错误。

def food_ch(i, a, b, c, d):
if a in i.lower():
first += 1
elif b in i.lower():
second += + 1
elif c in i.lower():
third += 1
elif d in i.lower():
fourth += 1
else:
hungry += 1


print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)

最佳答案

您应该使first, second, third, fourth, hungry 变量全局。否则,您将得到 UnboundLocalError。该功能应更正如下。

def food_ch(i, a, b, c, d):
global first, second, third, fourth, hungry # this part should be added
if a in i.lower():
first += 1
elif b in i.lower():
second += + 1
elif c in i.lower():
third += 1
elif d in i.lower():
fourth += 1
else:
hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "Mexican")

print (first, second, third, fourth, hungry)

关于python - 如何使用 if、elif 和 else 运行多参数函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71072776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com