gpt4 book ai didi

python - 如何保持 while 循环继续但获得相同的随机数但在完成后更改

转载 作者:行者123 更新时间:2023-11-30 22:47:41 25 4
gpt4 key购买 nike

这个问题很难解释,希望标题不要让人迷惑。

所以我必须让用户猜测 1 - 100 之间的一个数字,如果用户猜对了数字,我希望它重新启动游戏,但生成一个新数字并再次显示欢迎消息。此外,用户只能尝试 10 次,然后就会出现游戏结束消息。我被困在尝试显示新消息、生成新数字、使数字在整个循环中保持相同并在 10 次尝试时失败。

如果这令人困惑,我再次表示歉意。

这就是我所拥有的:

import random
import time
def getInput():
x = random.randrange(100)
print(x) # for testing

print("***Welcome! Guess and try to find a number between 1 and 100!***")
while True:
userGuess = int(input("Enter Your Guess: "))

if (userGuess > x):
print("Lower! Enter Again: ")

elif (userGuess < x):
print("Higher! Enter Again: ")
elif (userGuess > 100):
print("Guess must be between 1 and 100")
elif (userGuess < 1):
print("Guess must be greater then 0")
elif (userGuess == x):
print("You win!")
time.sleep(3)
continue

def main():
getInput()

main()

最佳答案

每次循环开始时,您都需要生成一个新的随机数,然后将尝试次数重置为 0

import random
import time
def getInput():
x = random.randrange(100)
print(x) # for testing

print("***Welcome! Guess and try to find a number between 1 and 100!***")
tries = 0 # we need a variabe to see how many tries the user has had
while True:
userGuess = int(input("Try "+str(tries + 1)+" Enter Your Guess: "))

if (userGuess == x):
print("You win!")
print("***Think you can win again? Guess and try to find a number between 1 and 100!***")
x = random.randrange(100)
tries = 0 # reset tries
print(x) # we need a new random number for the user to guess
time.sleep(3)
continue

elif (userGuess > x):
print("Lower! Enter Again: ")
elif (userGuess < x):
print("Higher! Enter Again: ")

if (userGuess > 100):
print("Guess must be between 1 and 100")
elif (userGuess < 1):
print("Guess must be greater then 0")
else:
tries = tries + 1 # add 1 to tries unless they make an invalid guess
if tries == 10:
print("<<GAME OVER>>")
break # end


def main():
getInput()

main()

关于python - 如何保持 while 循环继续但获得相同的随机数但在完成后更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453180/

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