在python中使用dict作为switch语句

时间:2018-04-19 23:45:33

标签: python mysql dictionary switch-statement

我正在尝试使用字典作为switch语句来从用户输入调用各种方法。然而,似乎正在发生的事情是,无论用户选择它的方法是什么,然后按照它们在我的字典中列出的方式循环遍历所有方法,而不是在特定方法调用之后退出。

我是Python新手,使用过JAVA,它有一个switch语句,并且能够在交换机内部使用break关键字,但python没有。

我一直在关注stackoverflow和谷歌,没有任何运气,我的特殊问题,所以任何帮助将不胜感激。

完整代码如下:

import pymysql

# Open DB
db = pymysql.connect()

# Prepare a cursor object using  cursor() method
cursor = db.cursor()

# Create a Student Table
cursor.execute("DROP TABLE IF EXISTS Student")
cursor.execute("CREATE TABLE Student(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")

# Method for inserting new student mySQL
def insert() :
    name = input('Enter the Students name: ')
    instatmt = "INSERT INTO Student VALUES(NULL, '%s')" % (name)
    cursor.execute(instatmt)
    db.commit()

    return(print("Successfully inserted student"))

# Method for updating a student record mySQL
def update() :
    name = input('Enter the Students name: ')
    update = input('Enter the Updated name: ')

    upstatmt = "UPDATE Student SET Name='%s' WHERE Name='%s'" % (update, name)
    cursor.execute(upstatmt)
    db.commit()

    return(print("Successfully updated object"))

# Method for deleting a student record mySQL
def delete() :
    name = input('Enter the Students name: ')

    delstatmt = "DELETE FROM Student WHERE Name ='%s'" % (name)
    cursor.execute(delstatmt)
    db.commit()

    return(print("Successfully deleted object"))

# Method for retrieving a student record mySQL
def retrieve() :
    name = input('Enter the Students name: ')

    retstatmt = "SELECT * FROM Student WHERE Name ='%s'" % (name)
    display = cursor.execute(retstatmt)
    print(display)

    return(print("Object Retrieved..."))

# Call method requested by user    
def performAction(argument):

    switcher = {
        'I': insert(),
        'U': update(),
        'D': delete(),
        'R': retrieve(),
        'E': exit
    }
    func = switcher.get(argument, lambda: "Invalid Entry")
    print (func)

# while True :
action = input('Which Operation would you like to perform ( I : Insert, U : Update, D: Delete, R: Retrieve, E: Exit): ')
performAction(action)

# disconnect from server
db.close()

3 个答案:

答案 0 :(得分:4)

您正在调用函数,而不是将它们插入到字典中。试试这个:

def performAction(argument):
    switcher = {
        'I': insert,
        'U': update,
        'D': delete,
        'R': retrieve,
        'E': exit
    }
    func = switcher.get(argument, lambda: "Invalid Entry")
    result = func()
    print (func, result)

答案 1 :(得分:1)

你在字典中调用函数,所以它们都是连续执行然后再也没有。要解决此问题,请删除括号:

POST
https://management.azure.com/subscriptions/mySubId/resourceGroups/myResourceGroup/providers/Microsoft.DataFactory/factories/myDataFactory/pipelines/copyPipeline/createRun?api-version=2017-03-01-preview

虽然可行,但这是一种非传统的做事方式 尝试做,并且可以用更易读的方式编写:

def performAction(argument):

    switcher = {
        'I': insert,
        'U': update,
        'D': delete,
        'R': retrieve,
        'E': exit
    }
    func = switcher.get(argument, lambda: print("Invalid Entry"))
    func()

Python不是Java,所以没有必要假装它。

答案 2 :(得分:0)

To run program with parameters

updatedb.py --action insert more

action = input('Which Operation would you like to perform ( I : Insert, U : Update, D: Delete, R: Retrieve, E: Exit): ')

to be replaced by

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-action", dest="action", nargs=1, default="exit", choices=['insert', 'exit', 'delete'], type=str)
args = parser.parse_args()
>>> args
Namespace(action='insert')
>>> args.action
'insert'

performAction(action)

to be replaced by

You can use eval() to call the func

result = eval(args.action)