python中的while循环永远循环

时间:2018-10-28 01:38:25

标签: python-3.x while-loop

几年前我学习了python,现在我正尝试重新学习它。我正在尝试制作一个询问姓名和年龄的基本程序,并且有一个while循环来尝试确保该人确实输入了正确的数字以确认其姓名,但是它不断循环播放。 / p>

name = input("What's your name? ")
print("Are you sure your name is",name,"? Type 1 for YES or  2 for NO.")
sure = int(input())
while(sure != 1 or 2):
    sure == input("Please type 1 for yes or 2 for NO.")

2 个答案:

答案 0 :(得分:0)

在我看来,“确保”始终为!= 1或2,请尝试使用“与”

答案 1 :(得分:0)

有一些问题可以解决,以使您的代码正常工作。

  1. sureinput捕获为int,但这只是第一次。

    修复程序:将int()移到while循环声明中,或者甚至更好地将sure与字符串进行比较,只需引用'1'和{ {1}}与'2'一样将返回一个字符串。

  2. input不正确,因为从未将or '2'sure进行比较。您可能在想:

    '2'

    sure != '1' or sure != '2' #'or' would not work in this scenario
    

    但是,它可以更简单地写为sure != '1' and sure != '2'

    修复程序:将sure not in ('1','2')声明替换为:!= '1' or '2'

  3. 在循环not in ('1','2')中,是比较而不是赋值。

    修复程序:将sure == input替换为:sure == input

固定代码应如下所示:

sure = input
相关问题