我的 while 循环不工作。当我 运行 它时,它总是给我无限输出
My while-loop is not working. When I run it, it always give me infinite output
我在这个 while 循环中遇到了麻烦。每次我输入 'yes' 它都会给我无限的输出。它似乎跳过了“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,这就是您遇到异常的原因,
因此,首先从用户那里获取输入,然后将其转换为 int
num = int(input('Enter a number within 1-10:'))
无限循环的原因是因为你没有改变开始的值。所以你需要改变start的值,如果输入不等于随机numbe.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)
我在这个 while 循环中遇到了麻烦。每次我输入 'yes' 它都会给我无限的输出。它似乎跳过了“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,这就是您遇到异常的原因,
因此,首先从用户那里获取输入,然后将其转换为 int
num = int(input('Enter a number within 1-10:'))
无限循环的原因是因为你没有改变开始的值。所以你需要改变start的值,如果输入不等于随机numbe.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)