在Python的while循环中卡住

-2 投票
3 回答
70 浏览
提问于 2025-04-13 02:18

我有两个Python循环,其中一个运行得很好,而另一个完全不行:

omonth = int(input('Digite o mês do seu nascimento: '))
while True:
    if int(omonth) not in (1,12):
        omonth = int(input('Digite o mês do seu nascimento: '))
    else:
        break

oday = int(input('Digite o dia do seu nascimento: '))
while True:
    if int(oday) not in (1,31):
        day = int(input('Digite o mês do seu nascimento: '))
    else:
        break        

我想用一个while循环来不断询问用户输入,当输入的信息不正确时就继续问。第一个循环(omonth)运行得很好,但第二个循环(oday)无论我输入什么都一直重复,根本停不下来。

3 个回答

0

在之前的回答基础上,你还可以使用一个 while 循环,这样可以避免重复输入语句(这就是所谓的不要重复自己原则)。这样还可以避免你刚才犯的拼写错误。;-)
此外,这样做还省去了 else break 的部分。

不过,这样做需要先给目标变量设置一个不在期望范围内的值,这样循环的内容至少会执行一次:

# initialize with an invalid value to make sure the condition is not satisfied
omonth = 0

while omonth not in range(1,12):
    omonth = int(input('Digite o mês do seu nascimento: '))
2

在第二个循环中,这行代码 day = int(input('Digite o mês do seu nascimento: ')) 有个错误。这里把用户输入的值赋给了变量 day,但其实应该是 oday

1

你好,来自巴西的朋友!

这个问题发生的原因是,在这段代码中

while True:
if int(oday) not in (1,31):
    day = int(input('Digite o mês do seu nascimento: '))

你在if条件里把值赋给了变量day,而不是oday

除此之外,你的代码还有很多问题,不能正常工作。

首先,这个条件

if int(omonth) not in (1,12):

检查的是omonth是否等于1或12,而不是检查它是否在这两个数字之间。oday的循环也是同样的道理。

其次,int函数在int(omonth)中是多余的,因为你已经在使用int(input())了。

一个更好(也是正确)的代码实现应该是:

omonth = int(input('Digite o mês do seu nascimento: '))
while True:
    if not (1 <= omonth <= 12):
        omonth = int(input('Digite o mês do seu nascimento: '))
    else:
        break

oday = int(input('Digite o dia do seu nascimento: '))
while True:
    if not (1 <= oday <= 31):
        oday = int(input('Digite o mês do seu nascimento: '))
    else:
        break      

撰写回答