我如何重置最小变化的随机数生成器python

时间:2015-05-30 06:30:37

标签: python reset

我的学校任务是尝试使用以下规则制作游戏: 创建一个随机生成1到50之间的数字的程序。用户必须猜测该数字。当他们猜测时,我应该评论以帮助用户猜测。一旦他们得到号码,我应该告诉用户它花了多少猜测并询问用户他们是否想再玩一次。如果他们这样做,则创建另一个号码,否则,结束该程序。

我的问题是,当我再次播放时,我的猜计数不会重置,我的“随机数”不会改变,请包含对我的代码更改的解释,因为我在11年级课程中刚开始学习编码,所以我对此非常新,谢谢! 有代码:

import random
ran=random.randrange(1,50)
counter=0
guessed=False

def startgame():
    answer=input("would you like to play a game? enter 'yes' or 'no'")
    if answer == "yes":
        while guessed != True:
            game()
    if answer=="no":
        print("thanks for playing")

def game():
    global counter
    counter=counter+1
    x=input("chose a number between 0 and 50")
    if int(x)>ran:
        print("your value is too high")
    elif int(x)<ran<50:
        print("your value is too low")
    elif int(x)==ran:
        guessed=True
        answer=input("that is correct! it took you "+ str(counter) +" tries,     "+"would you like to play again? enter 'yes' or 'no'")
        if answer == "yes":
            main()
        if answer=="no":
            print("thanks for playing")

def main():
    startgame()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

因为您已在全局范围内声明ran=random.randrange(1,50),因此在运行脚本时只调用一次,以获得所需的行为,您应该在每次调用startgame()时初始化它将它作为参数传递给每个函数。

def main():
    ran=random.randrange(1,50)
    startgame(ran)

def startgame(ran):
    #your function here.

def game(ran):
    #Your function here

另一个想法是将ran声明为全局变量并在每次调用game()函数时更改它的值,这将是您可以做的最小变化期望的行为,但globals不应该被用作许多全局变量使代码无法管理。

答案 1 :(得分:1)

您已将ran声明为全局变量。作为一个全局变量,它将被初始化一次。如果你调用一个函数让我们说get_random_no每次都会返回随机数会更好。在该函数内部,我们将编写逻辑以返回随机数。

import random
counter=0
guessed=False

def get_random_no():
    ran = random.randrange(1,50)
    return ran

def startgame():
    answer=input("would you like to play a game? enter 'yes' or 'no'")
    if answer == "yes":
        while guessed != True:
            game()
    if answer=="no":
        print("thanks for playing")

def game():
    global counter
    counter=counter+1
    ran = get_random_no()
    x=input("chose a number between 0 and 50")
    if int(x)>ran:
        print("your value is too high")
    elif int(x)<ran<50:
        print("your value is too low")
    elif int(x)==ran:
        guessed=True
        answer=input("that is correct! it took you "+ str(counter) +" tries,     "+"would you like to play again? enter 'yes' or 'no'")
        if answer == "yes":
            main()
        if answer=="no":
            print("thanks for playing")

def main():
    startgame()

if __name__ == '__main__':
    main()