简体   繁体   中英

how to store a randomly generated number into a variable python

So I'm working on a scenario where a number is randomly generated between 1 and 20. I need this number to be stored for a bit because depending on what number is generated, there will be a different outcome. I know you can you randrange and randint to generate numbers but I was wondering if you could store it into a variable. For example, I tried this:

def scenario():
   key = randrange(0, 21)

   if key > 10:
       print("A # greater than 10 has been generated")

   if key < 10:
       print("A # lesser than 10 has been generated")

   print(key) #To see what key was printed

I just have it printing 1 and 2 to see if it works and then printing the key so I can see if it's generated. Is there a specific way to make this work? Because when I try, it leaves it blank when I run it. I don't really want to go too deeply into this if it doesn't work, but I'm just asking if I'm missing something obvious or if it just doesn't work. Either way, if it does or doesn't work, I can probably find a way around it. Thanks for any help.

Your code looks fine, generally. Are you missing some important bits? You need to import randrange if you are going to use it. And you need to actually call your function. Other than that it looks fine

from random import randrange

def scenario():
   key = randrange(0, 21)

   if key > 10:
       print("A # greater than 10 has been generated")

   if key < 10:
       print("A # lesser than 10 has been generated")

   print(key) #To see what key was printed

scenario()

Everything looks fine here, but just remember to call your function, and import random:

from random import *
def scenario():
   key = randrange(0, 21)

   if key > 10:
       print("A # greater than 10 has been generated")

   if key < 10:
       print("A # lesser than 10 has been generated")

   print(key) #To see what key was printed

scenario()

If you don't call a function, nothing happens:

>>> def foo():
...     print 'hi'
... 
>>> #This is blank till I call foo()
... 
>>> foo()
hi
>>> 

Also, if you don't import random , it will raise an error at key = randrange(0, 21) :

>>> import random
>>> del(random) #Reverses import
>>> random.randrange(0, 21)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'random' is not defined
>>> 
from random import randint
def scenario():
   key = randint(0, 20)

   if key > 10:
       print("A # greater than 10 has been generated")

   if key < 10:
       print("A # lesser than 10 has been generated")

   print(key) #To see what key was printed

scenario()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM