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

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

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

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

from flask import Flask, request, jsonify, make_response, abort
import mysql.connector
from mysql.connector import Error
import myfunctions
import datetime
from myfunctions import create_connection, execute_query, execute_read_query, connection
from friend_insert import friend_insert
from movie_insert import movie_insert
from friend_delete import friend_delete
from random_movie import random_movie

while True:
    print("Press 1 To Add Friend Information")
    print("Press 2 To Add Up To 10 Movies Per Friend")
    print('Press 3 To Select Who Participates And Generate A Random Movie')
    choice = int(input())

    if choice == 1:
        friend_insert()
    if choice == 2:
        movie_insert()
    if choice == 3:
        friend_delete()
        random_movie()
        break

if choice != 1 and 2 and 3:
    print("Please Try Again")

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

dauxcl2d

dauxcl2d1#

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

while True:
    print("Press 1 To Add Friend Information")
    print("Press 2 To Add Up To 10 Movies Per Friend")
    print('Press 3 To Select Who Participates And Generate A Random Movie')
    choice = int(input())

    if choice == 1:
        friend_insert()
    elif choice == 2:
        movie_insert()
    elif choice == 3:
        friend_delete()
        random_movie()
        break
    else:
        print("Please Try Again")

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

相关问题