Python 初学者';猜猜我的号码';节目。当猜测到正确的数字或超出猜测范围时,循环不会中断

Python 初学者';猜猜我的号码';节目。当猜测到正确的数字或超出猜测范围时,循环不会中断,python,Python,因此,我正在学习python,我正在尝试编写一个简单的猜我的数字游戏,在这个游戏中,你只能猜5次,否则游戏就结束了。我真的有麻烦的while循环没有意识到数字已经猜测或猜测极限已经达到。还有没有更好的方法来格式化我的函数呢。感谢您第一次使用本网站时提供的所有帮助 # Guess my number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the comp

因此,我正在学习python,我正在尝试编写一个简单的猜我的数字游戏,在这个游戏中,你只能猜5次,否则游戏就结束了。我真的有麻烦的while循环没有意识到数字已经猜测或猜测极限已经达到。还有没有更好的方法来格式化我的函数呢。感谢您第一次使用本网站时提供的所有帮助

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

GUESS_LIMIT = 5

# functions
def display_instruct():
    """Display game instructions."""
    print("\tWelcome to 'Guess My Number'!")
    print("\nI'm thinking of a number between 1 and 100.")
    print("Try to guess it in as few attempts as possible.")
    print("\nHARDCORE mode - You have 5 tries to guess the number!\n")


def ask_number(question, low, high, step = 1):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high, step):
        response = int(input(question))
    return response


def guessing_loop():
    the_number = random.randint(1, 100)
    guess = ask_number("\nTake a guess:", 1, 100)
    tries = 1

    while guess != the_number or tries != GUESS_LIMIT:
        if guess > the_number:
            print("Lower...")
        else:
            print("Higher...")

        guess = ask_number("Take a guess:", 1, 100)
        tries += 1

    if tries == GUESS_LIMIT:
        print("\nOh no! You have run out of tries!")
        print("Better luck next time!")
    else:
        print("\nYou guessed it! The number was", the_number)
        print("And it only took you", tries, "tries!")


def main():
    display_instruct()
    guessing_loop()


# start the program
main()
input("\n\nPress the enter key to exit")

只要你没有达到猜测极限,你的while条件就是真的

while guess != the_number or tries != GUESS_LIMIT:

您应该将这些条件与
合并,而不是
。按照现在的方式,整个条件将为真,因为
尝试!=GUESS\u LIMIT
为真,即使
GUESS!=_编号
为假。

或者您可以使用
break
语句显式中断周期。但从某种意义上说,前面的答案更为正确,您应该真正理解为循环设置的条件。

您的
需要是