#python 字典实现类似c的switch def print_hi():
print('hi') def print_hello():
print('hello') def print_goodbye():
print('goodbye') choice = int(input('please input your choice:')) # 例子,不考虑输入错误的情况 # if ... elif 实现
if choice ==1:
print_hi()
elif choice ==2:
print_hello()
elif choice ==3:
print_goodbye() # 字典实现
choice_dict = {1:print_hi, 2:print_hello, 3:print_goodbye} # 这里只是引用函数,如果写成print_hi()这种形式,则一运行程序,所有选择都会执行一遍
# 替代方案是:1:lamba:print_hi()这种形式
choice = int(input('please input your choice:')) choice_dict[choice]() # 当对一函数引用但不加()时,只是引用,并不执行,所以这里加上()如果有参数,也可以传参数