我的while循环不工作.当我运行它时,它总是给我无限的输出



我在这个while循环中遇到了麻烦。每次我输入"是",它都会给我无限的输出。它似乎跳过了">try:";我不知道为什么。

import random
number = int(random.randint(1, 11))
start = input('Do you wanna play Guess The Number? [Yes] [No]--')
while start.lower() == "yes":
try:
num = int('Enter a number within 1-10')
if int(num) < 1 or int(num) > 10:
raise ValueError ('Enter a number within the 1-10 only!')
if int(num) == number:
print('You got it!')
break
except ValueError as err:
print('Number only!')

这一行num = int('Enter a number within 1-10')失败,因此您得到一个异常。

你可能是指num = int(input('Enter a number within 1-10'))

没有将数字作为输入从用户那里,你将字符串转换为整型,这就是为什么你得到异常,

首先从用户处获取输入然后将其转换为int

num = int(input('Enter a number within 1-10:'))

无限循环的原因就是因为你没有改变开始的价值。因此,如果输入不等于随机数,则需要更改start的值。r

这里是改进后的代码,希望它能让你理解
import random
number = int(random.randint(1, 11))
start = input('Do you wanna play Guess The Number? [Yes] [No]--')
while start.lower() == "yes":
try:
num = int(input('Enter a number within 1-10:'))
if int(num) < 1 or int(num) > 10:
print('A number should be within the 1-10 only!')
if int(num) == number:
print('You got it!')
break
else:
print("Failed to Guess!!!")
start=input('Do you wanna play Guess The Number? [Yes] [No]--')
except Exception as err:
print(err)

最新更新