gpt4 book ai didi

python - 初学者 'Guess my number'程序。当猜到正确的数字或​​猜不出来时,while 循环不会中断

转载 作者:行者123 更新时间:2023-12-01 05:15:06 24 4
gpt4 key购买 nike

所以我正在学习 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:

您应该使用 and 连接这些条件,而不是 or。按照您现在的方式,整个条件将为 true,因为 tries != GUESS_LIMIT 为 true,即使 guess != the_number 为 false。

关于python - 初学者 'Guess my number'程序。当猜到正确的数字或​​猜不出来时,while 循环不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com