当前位置:   article > 正文

python中switch功能实现(if…elif及while)_python switch

python switch

原理:

        首先直接进入while循环里,设置全局变量通过eval(input())获取输入的数值(为使每次功能实现后都能进行选择),获得选择的数值后,通过if…elif分支使用户进入子界面实现子功能;当功能实现后使用continue退出当前子界面,而不退出while循环,从而继续功能的选择;当用户想结束功能选择时,使用break退出while循环结束运行。其基础原理基于switch…case选择功能原理。

代码:

  1. #自定义主界面
  2. def test():
  3. print("\t\t-------主界面-------")
  4. print("\t\t(1)")
  5. print("\t\t(2)")
  6. print("\t\t(3)")
  7. print("\t\t(4)")
  8. print("\t\t(5)")
  9. print("\t\t(6)")
  10. print("\t\t(7)")
  11. print("\t\t(8) 退出")
  12. print("\t\t-------------------\n")
  13. test()#调用主界面函数提供第一次功能选择目录
  14. #进入子界面
  15. while True:#进行功能选择,相当于switch开关
  16. number = eval(input("请输入数字:"))#相当于做为全局角色
  17. if number == 1:
  18. print("1")
  19. test() # 再次提供功能选择目录
  20. continue
  21. elif number == 2:
  22. print("2")
  23. test() # 再次提供功能选择目录
  24. continue
  25. elif number == 3:
  26. print("3")
  27. test() # 再次提供功能选择目录
  28. continue
  29. elif number == 4:
  30. print("4")
  31. test() # 再次提供功能选择目录
  32. continue
  33. elif number == 5:
  34. print("5")
  35. test() # 再次提供功能选择目录
  36. continue
  37. elif number == 6:
  38. print("6")
  39. test() # 再次提供功能选择目录
  40. continue
  41. elif number == 7:
  42. print("7")
  43. test() # 再次提供功能选择目录
  44. continue
  45. elif number == 8:
  46. break


结果展示:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/54773
推荐阅读
相关标签
  

闽ICP备14008679号