虽然python中的循环没有按我所希望的方式工作

qnyhuwrf  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(380)

这个问题在这里已经有答案了

如何用一个值测试多个变量(27个答案)
19天前关门了。
我已经创建了执行条件验证语句的代码。我有一个菜单,提示用户输入一个1-3之间的数字,如果用户按下除这3个数字以外的任何数字,它会告诉用户一条错误消息,并再次循环菜单语句,直到满足条件。这是我的密码

  1. from flask import Flask, request, jsonify, make_response, abort
  2. import mysql.connector
  3. from mysql.connector import Error
  4. import myfunctions
  5. import datetime
  6. from myfunctions import create_connection, execute_query, execute_read_query, connection
  7. from friend_insert import friend_insert
  8. from movie_insert import movie_insert
  9. from friend_delete import friend_delete
  10. from random_movie import random_movie
  11. while True:
  12. print("Press 1 To Add Friend Information")
  13. print("Press 2 To Add Up To 10 Movies Per Friend")
  14. print('Press 3 To Select Who Participates And Generate A Random Movie')
  15. choice = int(input())
  16. if choice == 1:
  17. friend_insert()
  18. if choice == 2:
  19. movie_insert()
  20. if choice == 3:
  21. friend_delete()
  22. random_movie()
  23. break
  24. if choice != 1 and 2 and 3:
  25. print("Please Try Again")

循环工作。但是,它没有显示错误消息“请重试”。这是为什么?

dauxcl2d

dauxcl2d1#

它不起作用的原因是最后一个if语句不在while循环中!另外,我建议你改变一下if语句的格式。下面是您更正的while循环:

  1. while True:
  2. print("Press 1 To Add Friend Information")
  3. print("Press 2 To Add Up To 10 Movies Per Friend")
  4. print('Press 3 To Select Who Participates And Generate A Random Movie')
  5. choice = int(input())
  6. if choice == 1:
  7. friend_insert()
  8. elif choice == 2:
  9. movie_insert()
  10. elif choice == 3:
  11. friend_delete()
  12. random_movie()
  13. break
  14. else:
  15. print("Please Try Again")

这将消除格式错误的 if choice != 1 and 2 and 3 . 如果你真的想做那样的事,你就得做 if (choice != 1 and choice != 2) and choice != 3 ; 然而,else语句要优雅得多。

展开查看全部

相关问题