我的python随机数生成了相同的结果



所以我在python中玩这个小游戏时遇到了一个问题。我想随机化randomNumber变量。我每次跑步时它都会改变,但当我打印数字时,它会一直显示相同的数字。例如,我选择玩游戏3次,我的游戏会让我输入3个值,但随机数对所有3个都是相同的。

代码:

import random
def guessingNumber():
userPlayTimes = int(input('How many times you wanna play : '))
randomNumber = random.randrange(1,10)
userScore = 0
for x in range(1,userPlayTimes+1):
userGuess = int(input('Please enter your random Guess : '))
print(userScore , randomNumber)
if userGuess == randomNumber:
userScore += 1
return userScore
print(userScore)

结果:

Q : How many times you wanna play : 5
Please enter your random Guess : 1
0 3 (score , randomNumber)
Q : Please enter your random Guess : 2
0 3 (score , randomNumber)
Q : Please enter your random Guess : 3
0 3 (score , randomNumber)
1 (overall score)

如果我不擅长写作,请不要介意,因为这是我第一次使用stackoverflow询问问题

您应该在内部循环中移动您的随机数选择
当前随机数是在游戏开始前选择的,所有游戏都是相同的。

for x in range(1,userPlayTimes+1):
userGuess = int(input('Please enter your random Guess : '))
randomNumber = random.randrange(1,10) # <-- here
print(userScore , randomNumber)
if userGuess == randomNumber:
...

最新更新