在python中使用dict作为switch语句

t5fffqht  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(315)

我尝试使用字典作为switch语句,从用户输入调用各种方法。然而,似乎正在发生的是,无论用户选择什么方法,它都会按方法在我的字典中的列出顺序遍历所有方法,而不是在特定的方法调用之后退出。
我是python新手,使用过java,它有一个switch语句,并且能够在switch中使用break关键字,而python没有。
我在stackoverflow和google上到处搜索,没有找到任何关于我的特殊问题的线索,所以任何帮助都将不胜感激。
完整代码如下:

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()
uqxowvwt

uqxowvwt1#

您正在调用字典中的函数,因此它们都是连续执行的,然后就再也不会执行了。要解决此问题,请删除括号:

def performAction(argument):

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

虽然可行,但这是一种非常规的方法,可以用更可读的方式编写:

def performAction(argument):
    if argument == 'I':
        insert()
    elif argument == 'U':
        update()
    elif argument == 'D':
        delete()
    elif argument == 'R':
        retrieve()
    elif argument == 'E':
        exit()
    else:
        print("Invalid Entry")

python不是java,所以没有必要假装它是java。

zfycwa2u

zfycwa2u2#

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

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)
atmip9wb

atmip9wb3#

用参数运行程序 updatedb.py --action insert more action=input('要执行哪个操作(i:插入,u:更新,d:删除,r:检索,e:退出):')
替换为

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'

表演(动作)
替换为
你可以用 eval() 调用函数

result = eval(args.action)

相关问题