初学者'猜猜我的号码'计划。当猜测正确的数字或​​没有猜测时,循环不会中断

时间:2014-04-30 15:45:40

标签: python

所以我正在学习python,我试图编写一个简单的猜测我的数字游戏,你只有5个猜测或游戏结束。我真的遇到了问题,因为我没有意识到数字已被猜到或已经达到了猜测限制。是否有更好的格式化我的功能的方法。感谢您提供的任何帮助,第一次使用本网站。

# 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")

2 个答案:

答案 0 :(得分:2)

只要您没有达到猜测限制,您的状态就会成立。

while guess != the_number or tries != GUESS_LIMIT:

您应该将这些条件加入and,而不是or。你现在拥有它的方式,整个条件都是正确的,因为tries != GUESS_LIMIT为真,即使guess != the_number为假。

答案 1 :(得分:0)

或者您可以使用break语句明确地中断您的循环。但从某种意义上说,之前的答案更为正确,你应该真正理解你为循环设定的条件。