gpt4 book ai didi

Python随机猜谜游戏

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:09 26 4
gpt4 key购买 nike

实现 GuessNumber 游戏。在这个游戏中,电脑 - 想一个 0-50 范围内的随机数。 (提示:使用随机模块。) - 反复提示用户猜测神秘号码。 - 如果猜对了,恭喜用户中奖。如果猜测不正确,让用户知道猜测是太高还是太低。 - 猜错 5 次后,告诉用户正确答案。

下面是正确输入输出的例子。

I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!

这是我到目前为止得到的:

import random

randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False

while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)

print("End of program")

我一直遇到语法错误,我不知道如何在用户输入错误答案时让猜测值增加一,例如,猜 1?、猜 2?、猜 3?、猜 4?,猜 5?等...

最佳答案

既然您知道循环执行了多少次,并且想对它们进行计数,请使用 for 循环来控制该部分。

for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here

你知道它是如何工作的吗?

关于Python随机猜谜游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121437/

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