CodeNewbie Community 🌱

Richard B
Richard B

Posted on

How can I generate random numbers in Python?

Could anyone help walk me through the process of generating random numbers in Python?

More specifically, I'm trying to generate random numbers from a specified range.

Top comments (7)

Collapse
 
rickmeasham profile image
Rick Measham

@swizzard and @yechielk are right on here.

randint() will return a number integer between range_min and range_max inclusive. So if you call randint(1,10) you will get a random integer equal to 1, 2, 3, ..., 9, 10.

The random library has a number of useful functions in it for dealing with random things. For example if you need a random element from a list, use choice():

suit = choice(['hearts', 'diamonds', 'spades', 'clubs'])
Enter fullscreen mode Exit fullscreen mode

Documentation is here: docs.python.org/3/library/random.html

Collapse
 
richardb profile image
Richard B

Awesome thank you so much. Taking a look at that documentation now 👀

Collapse
 
yechielk profile image
Yechiel (he/him)
from random import randint

random_number = randint(1, 100)
Enter fullscreen mode Exit fullscreen mode

Will give you a number between 1 and 100

Collapse
 
richardb profile image
Richard B

thanks Yechiel 😀

Collapse
 
swizzard profile image
Sam Raker
from random import randint

range_min = 0
range_max = 10

a_number = randint(range_min, range_max)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tawfikyasser profile image
Tawfik Yasser
from random import randint
base = 1
limit = 10
print(randint(base ,limit))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
michaelcurrin profile image
Michael Currin

Hi. I wrote a Cheatsheet here which covers random strings, integers, floats and more.

michaelcurrin.github.io/dev-cheats...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.