每个个案在switch-case语句(python)中添加多行

时间:2019-11-20 05:06:10

标签: python switch-statement syntax-error

我是编程的新手,试图了解如何在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)

4 个答案:

答案 0 :(得分:1)

我相信您正在尝试这样做。让我知道是否有帮助。

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

Python不支持切换大小写。您将不得不使用switch case的if-elif-else insetad。

答案 3 :(得分:0)

对于更可口和可维护的结构,您可以使用开关的辅助函数:

def switch(v): yield lambda *c: v in c

这将使您以类似 C 的风格编写代码:

for case in switch(i): 
    if case(1):
        inventory.append(x)         
        return "you got x"
    if case(2): 
        inventory.append(y)
        return "you got y"
    if case(3):             
        inventory.append(z)   
        return "you got z"
else:
    return "you got nothing"