gpt4 book ai didi

python - While 循环、if-else 语句 : Guess my number game

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:27 24 4
gpt4 key购买 nike

我是一个使用Python的初学者,正在编写一个“猜我的数字游戏”。到目前为止,我一切正常。计算机在 1 到 3 之间随机选择一个数字,并要求玩家猜测该数字。如果猜测值高于随机数,程序将打印“Lower”,反之亦然。玩家只有 5 次尝试机会,当尝试次数用尽时,玩家会收到一条消息,游戏就会结束。如果玩家猜对了,就会恭喜他们,游戏结束。但是,有时当数字猜对时,程序不会打印祝贺消息,我不明白为什么......

import random

print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 100.")
print("Guess carefully, you only have 5 tries!.\n")

#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 4


#guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
elif guesses <= 0:
print("Sorry, you're out of guesses! Try again...")
break

elif guess < the_number:
print("Higher...")



guess = int(input("Take a guess: "))
tries += 1
guesses -= 1

if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

最佳答案

要回答有关缺少正确号码的祝贺消息的原始问题,请以 input() 结束代码,以确保在显示最后一条消息之前它不会终止。

计算顺序:

  1. 给出输入猜测
  2. 减少猜测(从 5 次开始),增加尝试(从 1 次开始)
  3. 如果猜测 == 0 则立即中断
  4. 评估猜测(较低、较高或等于,这将结束 while 循环)

import random

print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 3.")
print("Guess carefully, you only have 5 tries!.\n")

#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 5


#guessing loop


while guess != the_number:
tries += 1
guesses -= 1

if guesses == 0:
print("Sorry, you're out of guesses! Try again...")
break

elif guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")



guess = int(input("Take a guess: "))

if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

input()

关于python - While 循环、if-else 语句 : Guess my number game,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664786/

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