如果用户的猜测大于或小于随机生成的值,则Python循环不希望循环回来。它要么退出循环,要么创建无限循环。我哪里错了?
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False
答案 0 :(得分:2)
问题在于这一行:
if 0 <= guess <= 100:
inputcheck = False
每当用户输入0到100之间的数字时,这将终止循环。您可以将此部分重写为:
if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue
答案 1 :(得分:1)
正确的代码如下:
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 > guess or guess > 100:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False
这里的问题是,当inputcheck
的值介于0到100之间时,您将guess
设置为False。这会将while的值更改为False
并且循环次数为退出,因为不再是True
。
此外,您应该更改while循环中的最后一个if
个案,因为这样可以立即修复无限期运行的情况:
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False