gpt4 book ai didi

python - 我如何生成一个新的随机数

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

import random
guess = '0'
while (guess) != 'exit':
answer = random.randrange(1,100)
answer = str(answer)
guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
if not guess.isdigit():
if guess == "exit":
print('Game closed')
break
else:
print('Your guess was not a digit, try again')
guess = (guess)
if guess == answer:
print('Correct')
elif guess > answer :
print('Too high, try again')
elif guess < answer :
print('Too low, try again')

在你猜出正确答案后,我如何让它生成一个新的随机数

最佳答案

这里的主要问题是,即使猜测是错误的,您每次实际上都会生成一个新数字。相反,您应该在循环外生成第一个随机数,并且仅在猜测正确时才生成新的随机数:

import random
guess = '0'
answer = random.randrange(1, 100)
while (guess) != 'exit':
answer = str(answer)
guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
if not guess.isdigit():
if guess == "exit":
print('Game closed')
break
else:
print('Your guess was not a digit, try again')
guess = (guess)
if guess == answer:
print('Correct')
answer = random.randrange(1, 100) #make new random number if guess is correct
elif guess > answer :
print('Too high, try again')
elif guess < answer :
print('Too low, try again')

关于python - 我如何生成一个新的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082965/

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