gpt4 book ai didi

python - Python 猜数字中的重新启动选项

转载 作者:行者123 更新时间:2023-12-01 05:42:14 25 4
gpt4 key购买 nike

我在这个猜数字作业上遇到了困难。我似乎无法正确处理并需要一些帮助。 “重玩”选项不起作用,因为当您赢得游戏并选择"is"重玩时,它不会重新启动游戏,而是会继续您的下一个猜测数字(例如:猜测数字 1、猜测数字 2...)。但是当你输了时,它会回到第一部分,询问你“你想尝试多少次”。那么我怎样才能让你获胜的部分做到这一点呢?另外,有人可以给我一些关于如何改进提示选项的提示吗?另外,我需要插入任何 def main(): 内容吗?因为我不确定我们是否已经完成了这项任务。所以请帮帮我。谢谢。

# This is a guess the number game.
import random
answer = "yes"
number = random.randint(1, 10)

while answer == 'yes':
tries = 0
guess = 0
guessnumber = 0
tries = int(input("How many tries would you like? "))
tries2 = tries
while guessnumber != tries2:
guessnumber += 1
guess = int(input("Enter guess number " + str(guessnumber) + ": "))
if guess < number:
print("You guessed too low")
hint = input("Would you like a hint, yes or no?: ")
if hint == "no":
continue
print("The number is less than", number + 1)
if guess > number:
print("You guessed too high")
hint = input("Would you like a hint, yes or no?: ")
if hint == "no":
continue
print("The number is greater than", number - 1)
if guess == number:
tries = str(tries)
print("YOU WON!")
answer = input("Play again? Yes/No? ") `enter code here`
if answer == 'no':
break
if guess != number:
number = str(number)
print("GAME OVER!!! The number I was thinking of was " + number)
answer = input("Play again? Yes/No? ")
if answer == "no":
break

最佳答案

有几件事:

random.randint(1, 1) 表示生成一个 1 到 1 之间的随机整数。它总是给出 1。

为什么只设置一次“tries”会有一个副本?

Python 中的缩进很重要。它改变了 if/elif/else 分支的评估方式。因此 (guess > number) 和 (guess == number) 检查是以 (guess < number) 为条件的,这是不可能的。鉴于(guess < number)、(guess > number)和(guess == number)这些状态是互斥的并且比较相同的变量,最好将后续的 if block 更改为 elif。

“游戏结束”可能只有在尝试次数耗尽后才会触发,因此它不能位于 (guessnumber < attempts) 循环内。

# This is a guess the number game.
import random
answer = "yes"
number = random.randint(1, 100)

while answer != 'no':
guess = 0
guessnumber = 0
tries = int(input("How many tries would you like? "))
while guessnumber < tries:
guessnumber += 1
guess = int(input("Enter guess number " + str(guessnumber) + ": "))
if guess < number:
print("You guessed too low")
hint = input("Would you like a hint, yes or no?: ")
if hint == "no":
continue
print("The number is less than", number + 1)
elif guess > number:
print("You guessed too high")
hint = input("Would you like a hint, yes or no?: ")
if hint == "no":
continue
print("The number is greater than", number - 1)
elif guess == number:
print("YOU WON!")
answer = input("Play again? Yes/No? ") #enter code here
break
if (guess != number) and (guessnumber >= tries):
number = str(number)
print("GAME OVER!!! The number I was thinking of was " + number)
answer = input("Play again? Yes/No? ")

关于python - Python 猜数字中的重新启动选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246366/

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