Python's Random Module: Generating Random Numbers

Explore Python's random module methods for generating, sampling, and manipulating random numbers and lists.

Discover how Python's random module can simplify generating random numbers, creating samples, and even mimicking real-world data like SAT scores or lottery tickets. Additionally, explore practical methods such as shuffling lists and picking random items with ease.

Key Insights

  • Learn how the random module generates random integers using methods like randint(), which allows specifying inclusive minimum and maximum values, and randrange(), useful for generating numbers within a specific range and interval steps.
  • Understand practical applications by generating realistic random data, such as SAT scores within the 400–800 range ending in zero, and random Olympic years ranging from 1896 to 2024 in increments of four.
  • Explore advanced randomization techniques including using random.sample() to produce unique random sets, random.shuffle() to randomize lists such as a deck of cards, and random.choice() to select a single random element from a list.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

This is a lesson preview only. For the full lesson, purchase the course here.

Next module we're going to check out is random. The random module can generate random numbers, it can generate them in a range, it can give you multiple random numbers that are unique like a sample. It's really powerful.

Okay, so we're going to begin with just a raw random number. Say r for random is random the module dot random the kind of namesake method. So the random module has a random method just like the date time module has a date time property inside of it and that will give you a 16 digit float which is a 16 digit float from 0 to 1. There it is.

Like what would be the usage of that? Well, I don't know, we could say r equals you can do another one and this time multiply it by a thousand and print that. Okay, that's not so useful. Yeah, but you could int it.

And now look what you got. You've all suddenly you've got random integers in a range. So that is kind of useful.

Now in a program like JavaScript you actually have to mechanically go through like hand do all the steps first generate the float then multiply it by your range max and then round it off. We could just round this as well you don't have to int it. Why are they different? Because you're asking for a different random number twice.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Like if you want to use the same random number you could just say don't do another random one use the existing r. There you go. So there's that's better, right? It's more clear. So there's a 552 and all these 16 decimals float and there's just the random int.

So that's one way to generate a random int. But there's a better way. You can just ask for a random int and you can specify a range of min and a max.

So random has a rand int method that takes as its arguments a min value and a max value with the max being inclusive. So returning you a it will return you a random integer in that min max range. So let's go ahead and get ourselves a random number.

Let's say r equals random dot rand int and we'll say we want from one to three and such a narrow range is only because we want to make sure that the three is inclusive. If we never get a three that's exclusive there you got your three that proves it's inclusive, right? If you ask for one to a thousand you're going to sit here a while waiting for a thousand to prove it's inclusive. So there you go there's your random int from one to a thousand.

All right so a little challenge. Let's read this and then turn off the recording. Give it a try and you'll come back see how you did.

We're going to generate two random SAT scores. We did SAT scores prior but you know we weren't generating random ones. We were letting the user input scores or we were just write hard coding them.

Generate two random SAT scores one math one english. Scores are in the 200 800 range. We'll make the minimum 400 so people don't get like really low scores.

Your SAT score report will look something like so. Let's turn these off. We don't want to give the answers here though do we? No we don't.

Let's get rid of that. So here let's say five. So it's possible that your score could be something like that right? Let's just go ahead and try.

We'll say so turn off the recording. Try to get the random score and CONCATENATE it like so. CONCATENATE and print a score report.

Bonus make the scores end in a zero because actually SAT scores for individuals do end in zero. We would say something like your SAT score is five sixty seven ten right? Ending in zero and you'd have to think a little bit about that. Maybe generate a random number between 40 and 80 and then multiply that by 10 or something.

All right turn off the recording see what you can come up with and then I will implement the solution. Okay we're back looking at the solution. We're going to say math score or math SAT equals random dot randint.

Now randint will take a min we said 400 and it'll take a max we said 800 and it's inclusive. So there you go and then we'll say your verbal or English score is the same deal. Now to CONCATENATE that into a score report you can start with the substrings and that's going to be a variable.

That's going to be a substring and that's a variable. So the variable is going to be math SAT and ING SAT and remember you cannot CONCATENATE numbers so we'll have to stringify the math SAT and the ING SAT scores by wrapping them in stra. But that should work.

Nope what's not? Oh yeah I'm missing a plus sign and I got my other plus sign on the wrong part. Okay there you go random. Wow pretty good scores there right.

Hello Harvard yo. Now to get them to round to get them end in zero the little hack would be you don't set the min and max to 400 × 800 you set it to 40 × 80 and then you just round off. I mean excuse me you multiply by 10.

So you generate scores from 40 to 80 and then multiply those by 10. That's one way to do it a little hacky but it totally works. And there you go these are ending in zeros right because we're not generating 400 800 we're generating 40 to 80 37 and multiply no well 57 and multiplying that by 10 570.

Okay write that out porfa vorfa. Yeah you gotta do it you gotta write it out mate. All right boom you're getting there.

All right now you can also this is a little bit more a little slicker way this is a way to get your number ending in zero without multiplying by 10. You just say your min your max and your step and if you step by 10 that means give me multiples of 10. If you step by 2 you'd only get say even numbers and if you step by watch if we come in here and give a 2 all of our values will be even.

Oh no that's randiant we can't do it with randiant we have to do it with randrange. Wrong method. Okay so randrange takes min max and a step.

So to get the math and English scores now we would use randrange and we would say 400 to 800 but step by 10. So you would everything ends in a zero now and it would be the same concatenation. Oh that's randiant randrange there it is ending in zeros.

Now to test this out if you made it a two it would just always be an even number. If you started 401 and you said step by two it would always be an odd number but we want to start at 400 go to 800 and step by 10. Have the score end it in have the score end in a zero or end in zero by adding step of 10 as third argument.

So min max step challenge generate and print one olympic year from the summer olympics. Okay so your numbers are your min is 1896 your max is 2024. That was the first modern olympics 1896 it goes 1900 1904 etc.

You know they skipped a couple times there was no olympics in 1940 or 44 but we don't have to consider that. The 2020 olympics was actually in 2021 we don't have to consider that. So what we will do is just generate a random olympic year.

We'll say rand olympic year or I'd like you to do that. Generate a random olympic year you're going to have to step right think about it you're going to have to step by four aren't you. Start stop step min max step stop the recording try to generate a random olympic year and then come back and test your answer check your result.

Okay so we're going to say olympic year equals random dot rand range 1896 to 2024 comma four perhaps skipping and jumping by four there you go 2020 1976 that was the one in where was that one 76. I forget Bruce Jenner wasn't that Bruce Jenner Anyway moving along range min max exclusive returns all numbers in the min max exclusive range returns all numbers in the min max exclusive range. So you basically get a list let's say you want all the numbers from one to ten.

So here's what we're gonna do let's say nums list we'll say range min max exclusive we want one to ten nums list from one to ten from one to ten. We want to start at one and we want to go to ten and ten is exclusive so we go to eleven and we print and it doesn't work because you have to listify it so we wrap it all in list to unpack it. So the nums list has all the numbers it's just not it's like in a suitcase packed up you can't see them so we unpack then unpack the list by listifying it unpack the numbers there you go.

Now here's another one sample so that's range to listify a range right that's what we just did list range list rank look list range min max exclusive there's your max exclusive 11 right didn't exclusive meaning it didn't come out in the answer we 11 was excluded.

Now the next one we're going to look at is random dot sample which is kind of neat sample gives you random numbers as many as you like and they're all unique in a range so you could say if you wanted to say a random lottery ticket we would say give me five numbers from say 1 to 69 and if you call that that's a range that you want comma account how many you want let's say you want five of them and you call that on random sample.

So let's try it out we'll say lottery nums these will be non-repeating numbers that'll be random dot sample a range we're going to start at one we're going to go to 70 because we want 69 as a possibility on the outside of that comma five we want five numbers run and gun and there it is.

Now lottery tickets if you look you know i'm not going to go but if you look at lottery tickets when they report the tickets the winning tickets they do sort them in ascending order so let's say lottery nums dot sort if you recall we have sorted that is a list method that we used in lesson one so now they're sorted in ascending order.

Now what about the powerball number okay let me show you powerball so the powerball is five consecutive numbers from 1 to 69 in ascending order and then there's a unique drawing from 1 to 26 called a powerball which could be a repeat of one of these five because it's independently drawn so if we wanted to get the sixth number of the powerball what we would do is we would generate another number from 1 to 26.

We'll just call it powerball equals and that's just going to be random rand int we just want one number 1 to 27 oh wait is ran into inclusive actually yeah we proved that yep so we'll say 1 to 26 print the powerball nine okay.

Now what you'd want to do is if you wanted to complete the ticket you would append or add that last powerball number into the list right the lottery nums so we'll say to complete the ticket lottery nums dot append powerball and then if you print the whole thing you've got the six numbers five ascending from 1 to 69 in a unique drawing unique drawings meaning if you run it enough times ah there it is.

So notice that the powerball is repeating one of the five because these five are their own independent drawing powerball is different it's a separate drawing separate random number right so it doesn't know about these it's not trying to avoid repeating them.

All right another method that we're going to look at is shuffle is great it randomizes a list so let's say you have a list of consecutive integers you want to randomize them so let's make a list of consecutive integers from 1 to 52 representing say a deck of cards and then we'll shuffle the deck.

So first we're going to say deck of cards and we're just going to represent that as the ints from 1 to 20 for 52 so we're going to say range 1 to 53 and we're going to list of whoops we're going to listify that right to unpack the suitcase of numbers and we could print and there is your 1 to 52 but it's like a fresh deck of cards you might want to shuffle it.

We're going to say random dot shuffle the shuffle method is called on the random module object and it takes a list and returns a random version of same and you don't have to well it doesn't really return it just does it operates in place we're not saving this to anything if you see there it is shuffles random shuffle.

And if you just want deal if you want to deal yourself five cards just pop off the top pop off the end right grab the last five or grab the first five as you wish there's five random cards five random numbers in that 1 to 52.

Now picking a random number you could there's a choice method that that is called in random it takes a list and will return you a random a random item so we'll say random card pick a card any card right random dot choice it's the choice method you feed it a list and it returns a random item from the list so if you run it twice or thrice it just keeps picking random values every time and that is the last of the methods.

So just to recap you've got random dot choice random dot shuffle random dot sample you've got range min max random dot ran range random dot ran in and good old ran just random itself and we've got all these date objects so we've taken a pretty good look at the date time and the random modules to get our feet wet with two important modules but also just the concept of modules and all the methods and properties that come with modules and they're all you know kind of unique to the to the module.

All right that is it for lesson three thank you so much i hope you learned a lot you're hanging with it um i know i'm talking a little fast it's a lot of material i just need you to hit the pause button that's all hit the pause button move back camp out on a screen freeze it you don't have to have me listen you know talking the whole time just pause and type copy it right you get you get to a thing this guy's talking too fast but okay pause the guy you know mute me make me stop talking pause me and sit here and type this and then move on to the next one and keep it rolling.

Really need you to type this all righty on to lesson four we'll see when you're ready for that bye.

Brian McClain

Brian is an experienced instructor, curriculum developer, and professional web developer, who in recent years has served as Director for a coding bootcamp in New York. Brian joined Noble Desktop in 2022 and is a lead instructor for HTML & CSS, JavaScript, and Python for Data Science. He also developed Noble's cutting-edge Python for AI course. Prior to that, he taught Python Data Science and Machine Learning as an Adjunct Professor of Computer Science at Westchester County College.

More articles by Brian McClain

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram