【发布时间】:2026-01-16 14:55:02
【问题描述】:
我正在尝试使用字典作为 switch 语句从用户输入中调用各种方法。然而,似乎正在发生的事情是,无论用户选择什么方法,然后按照它们在我的字典中的列出顺序循环遍历所有方法,而不是在特定方法调用后退出。
我是 Python 新手,使用过 JAVA,它有一个 switch 语句,并且能够在 switch 中使用 break 关键字,而 python 没有。
我一直在研究 * 和 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()
【问题讨论】:
-
您正在调用该函数,而不是引用该函数。用
insert(无括号)代替insert()。 -
'I': insert()这将返回一个带有dict['I']=the result of insert()的字典,你需要改为I:insert,然后像swicther['I']()一样调用
标签: python mysql dictionary switch-statement