Python 3.4:While循环不循环

Python 3.4 :While loop not looping

如果用户的猜测大于或小于随机生成的值,

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

这一行有问题:

if 0 <= guess <= 100:
    inputcheck = False

这将在用户输入 0 到 100 之间的数字时终止循环。您可以将这部分重写为:

if not 0 <= guess <= 100:
    print("Choose a number in the range!")
    continue

正确代码如下:

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

这里的问题是,当 guess 的值介于 0 和 100 之间时,您将 inputcheck 设置为 False。这将 while 的值更改为 False 并且循环正在退出,因为 while 不再是 True

此外,您应该更改 while 循环中的最后一个 if 情况,因为这现在无限期地修复了 运行 的情况:

if tries > 7:
    print("Sorry, you only have  7 guesses...")
    inputcheck = False