Python中的Switch-case语句
我厌倦了尝试制作一个菜单,让我从字典中选择键,在每个值中我都可以选择。我发现我可以使用dictionary和get方法,它工作得很好,但是我应该在get之后使用if-else语句来执行一个响应用户选择的函数。我能做得更好吗?也许在键值中使用lambdaPython中的Switch-case语句,python,menu,switch-statement,Python,Menu,Switch Statement,我厌倦了尝试制作一个菜单,让我从字典中选择键,在每个值中我都可以选择。我发现我可以使用dictionary和get方法,它工作得很好,但是我应该在get之后使用if-else语句来执行一个响应用户选择的函数。我能做得更好吗?也许在键值中使用lambda def menu(): print("Welcome to Our Website") choises={ 1:"Login" ,
def menu():
print("Welcome to Our Website")
choises={
1:"Login" ,
2:"Register",
}
for i in choises.keys(): # Loop to print all Choises and key of choise !
print(f"{i} - {choises[i]}")
arg=int(input("Pleasse Chose : "))
R=choises.get(arg,-1)
while R==-1:
print("\n Wrong Choise ! Try again ....\n")
menu()
else:
print(f"You Chosed {R}")
if R==1:
login()
if R==2:
register()
def register():
print("Registration Section")
def login():
print("Login Section")
menu()
可以使用以下函数定义模拟switch语句:
def switch(v): yield lambda *c: v in c
您可以在C样式中使用它:
x = 3
for case in switch(x):
if case(1):
# do something
break
if case(2,4):
# do some other thing
break
if case(3):
# do something else
break
else:
# deal with other values of x
或者,您可以使用if/elif/else模式,而不使用中断:
x = 3
for case in switch(x):
if case(1):
# do something
elif case(2,4):
# do some other thing
elif case(3):
# do something else
else:
# deal with other values of x
对于函数分派来说,它尤其具有表现力
functionKey = 'f2'
for case in switch(functionKey):
if case('f1'): return findPerson()
if case('f2'): return editAccount()
if case('f3'): return saveChanges()