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

2024-10-01 01:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在用python做这个小游戏时遇到了一个问题。我想随机化随机数变量。每次我跑步时它都会改变,但当我打印号码时,它会一直显示相同的号码。例如,我选择玩游戏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询问问题。


Tags: inputyourrandommany号码howintscore
1条回答
网友
1楼 · 发布于 2024-10-01 01:43:15

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

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:
        ...

相关问题 更多 >