gpt4 book ai didi

python - 在switch-case语句(python)中为每种情况添加多行

转载 作者:行者123 更新时间:2023-12-03 08:20:01 24 4
gpt4 key购买 nike

我是编程的新手,试图了解如何在python中使用switch-case语句。我的问题是当我尝试使用每种情况下有多行的语句时发生语法错误。这可能吗?我想念什么?如果不可能,那么switch-case语句如何有用?

这是我用来测试的代码

drop = random.randint(1,3)
inventory = []
def randomDrop(i):
switcher ={
1:
"you got x"
inventory.append(x) #syntax error on this line
2:
"you got y",
inventory.append(y)

3:
"you got z",
inventory.append(z)

}
return switcher.get(i,"you got nothing")
randomDrop(drop)

最佳答案

Python不支持支持开关大小写。您正在使用的东西是字典。它是键,值数据结构。
dict的语法:{key1:value1,key2:value2}
但是您使用值多的语句代替了值,这就是语法错误的原因。

drop = random.randint(1,3)
inventory = []
def randomDrop(i):
switcher ={
1:
"you got x"
inventory.append(x) #multiple statement instead of value or reference
2:
"you got y",
inventory.append(y) #multiple statement instead of value or reference

3:
"you got z",
inventory.append(z) #multiple statement instead of value or reference

}
return switcher.get(i,"you got nothing")
randomDrop(drop)

请改用 if-else
inventory = []
def randomDrop(i):
if i == 1:
inventory.append(x)
return 'you got x'
elif i == 2:
inventory.append(y)
return 'you got y'
elif i == 3:
inventory.append(z)
return 'you got z'
else:
return 'you got nothing'

drop = random.randint(1,3)
randomDrop(drop)

看到:
https://docs.python.org/3/tutorial/controlflow.html

关于python - 在switch-case语句(python)中为每种情况添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58947057/

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