在python中存储随机生成的数字,可以随时调用

时间:2017-07-18 21:39:04

标签: python python-3.x function random

我想要做的是让Python生成一个介于1到6之间的数字,然后将6添加到我已经完成的数字并为我提供结果,但是我无法想象out是如何让这个值可以调用,以便它可以在游戏中上下移动,这是我到目前为止:

import random
import time
Name = input("Before we get started lets get your character created, tell me what is your name?") 
print()
print ("Welcome ",Name," to the adventure of a lifetime. The next thing you will need to do is sort out your character stats. This will require dice rolls which we will do within the game.")
print()

def skillroll():
    skillroll=""

    while skillroll !="Y" and skillroll != "N":
        skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")

        if skillroll=="Y":
            print("Rolling the dice..")
            skill=random.randint(1,6)
            time.sleep(2)
            print("I rolled a", skill, " I will now add 6 to this so your skill is", skill+6)
            skill=skill+6
            print()

    return skillroll

skillroll()

我只是不知道如何得到最终答案,所以我可以在游戏过程中使用它。

我的一位朋友送我这个帮忙 https://github.com/protocol7/python-koans/blob/master/python%202/koans/about_classes.py

但我不知道这是如何相关的,我在Stackoverflow上找到的每个答案都是针对不同的语言。

1 个答案:

答案 0 :(得分:1)

只需使用:

import random
random.randrange(1, 7)

获得1到6之间的任何数字。

您的代码变为:

import random
import time

def skillroll():
    skillroll=""
    while skillroll !="Y" and skillroll != "N":
        skillroll = input("First we need to roll for your skill, would you like me to roll? Y/N")
        if skillroll=="Y":
            print("Rolling the dice..")
            skill = random.randrange(1, 7)
            time.sleep(2)
            print("I rolled a ", skill, ". I will now add 6 to this so your skill is", skill+6, "\n")
            skill=skill+6
            return skillroll # What if N??

Name = input("Before we get started lets get your character created, tell me 
what is your name?") 
print ("\nWelcome ",Name," to the adventure of a lifetime. The next thing you 
will need to do is sort out your character stats. This will require dice 
rolls which we will do within the game.\n")
skillroll()