【问题标题】:Stack created in python using switch statement使用switch语句在python中创建的堆栈
【发布时间】:2019-05-29 08:28:18
【问题描述】:

我使用 switch 创建了一个堆栈程序,但它似乎无法正常工作。它继续迭代推送方法。它甚至没有退出程序。

global a
a=[]
def push():
    push_no=int(input("Enter number you want to push"))
    a.append(push_no)

def pop():
    poped_item=a.pop()
    print("Poped item {}".format(poped_item))


def display():
    print(a)  

def numbers_to_strings(a1): 
    switcher = { 
        1: push(), 
        2: pop(), 
        3: display(),
        4: quit()
    } 
    return switcher.get(a1, "nothing")


# Driver program 
if __name__ == "__main__": 
    while True:
        a1=int(input("ENTER WHICH OPERATION YOU WANT OT PERFORM 1-Push, 2-POP, 3-Display 4-quit"))
        numbers_to_strings(a1) 

【问题讨论】:

  • python 没有 switch 语句

标签: python switch-statement stack


【解决方案1】:

在您的numbers_to_strings 定义中,您已经评估了字典中的函数。试试:

def numbers_to_strings(a1): 
    switcher = { 
        1: push, 
        2: pop, 
        3: display,
        4: quit
    } 
    return switcher.get(a1, "nothing")()  # get the function object, then evalutate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多