Python Tutorial: Generate Random Numbers and Data Using the random Module
13:36

Python Tutorial: Generate Random Numbers and Data Using the random Module

Corey Schafer 29.08.2017 525 735 просмотров 11 602 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we will be learning how to generate random numbers and choose random data from lists using the random module. I personally use the random module pretty often in my tutorials to generate random data. This can also be used be games, simulations, and plenty of other useful tasks. Let's get started. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Random ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (10 сегментов)

<Untitled Chapter 1>

hey there how's it going everybody in this video we're gonna take a quick look at the random module and how we can use this to get some random data so I use this a lot to create dummy data that I use within my videos so I figured I'd make a short video showing how you can use this to do something similar so we'll be taking a look at how to create random numbers and grabbing random values from a list of values and things like that now one thing that I want to mention before we get started is that this shouldn't be used for security purposes or cryptography and Python mentions this in their documentation and suggests using the secrets module instead if that's what you're trying to do but for most cases the random module works great so if you just want to generate some random data or have a game where you need some random values or shuffle some values or something like that then this is perfect for those types of things so with that said let's go ahead and get started so first to use the random module we're gonna need to import it and this is included in the standard library so you don't have to install any third-party packages so you can just say import random now the first two methods that

Random and Uniform Methods

are usually covered are the random and uniform methods now I hardly ever use these myself but let's take a quick look at these just to see what they do so we

Random Method

can use the random method to get a random value between 0 and 1 and the 0 is going to be inclusive and the 1 non inclusive and what this means is that you can get an exact value of 0 but you can't 1 and you can only get you know 0. 999 but never all the way up to 1 so if we say value is equal to random dot random and then we print out this value now if I run this a couple of times then each time we should get a value between 0 and 1 now the reason I never really use this is because I usually want random values between a certain range and we could multiply this random value to get values between a certain range but the other methods already provide this functionality for us so for example if we wanted a random floating point value between let's say 1 and 10 then we could use the uniform method to do this so we can say uniform and then the range of values and so if we run this we should get a random floating point value between 1 and 10 every time we run this now if you want random floating-point values between the different range then you can just change the arguments that you pass into that method now I personally don't use this method too often either because usually when I need random values I usually need whole numbers or integers now to get random integers we can use

Random Integers

the Rand int method so for example let's say that we wanted to simulate the role of a six-sided die now to do this we'll just want to use the rand int method and we're gonna want a random number between a 1 and 6 and 1 in 6 should be inclusive so this includes both 1 and 6 in the random values that you get so if we run this a few times then we should see random values between 1 and 6 pop up and so there we got 1 and 6 and a bunch of values in between now if you just wanted to simulate like something like a coin toss for example then you could just do a random integer between let's say 0 & 1 and you could just pretend that 0 is heads or 1 is tails so if you do that and run this a few times and each time you get a random value between 0 & 1 so that Rand int method is a method that I tend to use a lot now another random method that I personally end up using a

The Choice Method

lot is the choice method now the choice method picks a random value from a list of values so for example let's say that we had a list of greetings and that we want to grab a random greeting so let me create a list of greetings here and now let's say that we wanted to grab a random greeting so I'll do that with random dot choice and I will pass in that greetings list there and now whenever our print these out I'll print out that random greeting followed by my name so now if I run this a few times then we should see that it grabs a random greeting from that greetings list every time that we run this now it's also possible to get

Get Multiple Random Values from a List

multiple random values from a list and to do that instead of using choice will use choices so to do this let's say that we wanted to simulate some Rowlett results and whether it lands on red black or green so to do this let's create a list of colors here and we will create that list of colors that the outcomes can be so red black or green now I actually grabbed this example from the Python documentation because I thought they did a good job of showing what we can do with this so now let's say that we wanted to simulate like 10 rounds of the roulette wheel spinning so we could do this by saying I'll just call this results and we'll say random dot choices to grab a list of random values here and we want to choose random values from colors and then we can set our K value and our K value is just how many times we want to pick a random value so let's do this 10 times to simulate 10 wheel spins and we'll pass in the results to print out so let's save that and run it and we can see that it returns a list of ten random results since we passed in 10 for K and we can see that for each value in this list it grabbed a random value from our colors list now right now every color is equally likely to be randomly selected so we can see here that it's that there are two greens and the results here so the greens and the reds and the blacks are all just as likely to be randomly selected but if you've ever seen a row let will there are actually 18 red pockets 18 black pockets and only two green pockets so it's actually a lot less likely that a ball will land on so really what we want to do is wait these so that our random choices take these odds into consideration and we can set these weights of our choices by passing in an extra value here so we can pass in another argument called weight and this weights is going to be a list of what we want to weight these so the red as 18 the black as 18 and the green as 2 so here's how these weights work so our total weights here add up to 38 so we have 18 plus 18 which is 36 and then 2 which is 38 so red has an 18 out of 38 chance of being randomly selected and so does black but green only has a 2 out of 38 chance of being selected so we have two green results here in our current results but now if we run this then we'll see that green is a lot less likely to be selected so if we run this twice we can see that we got one green value here run through this a few more times and green just very rarely pops up so those weights seem to be working properly okay so now let's take a look at how we can

Randomly Shuffle a List of Values

randomly shuffle a list of values so let's say that we have a list of values from 1 to 52 now we can think of these as a deck of cards since there are 52 cards in a deck so first let's create a range so I will call this deck and set this equal to range of 1 and 53 and that's because the 53 is non inclusive so this will be a range between 1 and 52 now just so that we can print these out I'm going to convert this range to a list and we can see what this looks like so now let me print out this deck so if I run that you can see that we get a list of values between 1 and 52 so now let's use the

Random Module To Shuffle this List

random module to shuffle this list so this shuffles the list in place so we don't have to set another variable or anything like that we can just say random dot shuffle and then pass in the list that we want to shuffle so if we run this then we can see that now our list of 52 numbers was randomly shuffled around so now let's say that we wanted to get 5 random call from this deck now you might think that we should use the choices method that we saw a little bit ago but this wouldn't really work because with the choices method it could randomly grab the same cards multiple times so for example it could randomly select the one card multiple times and we only want unique cards so to do this we're going to use

The Sample Method

the sample method now it'll make sure that it only grabs unique cards from our sequence so to do this I'm just going to create another variable here and I'll call this hand and I'll set this equal to random dot sample and we want to get a sample from the deck and we want five random unique values so we'll pass in K as five and now let's print out our hand so let's run that so now we should get a random sample of five cards from our fifty-two card deck and if we run this a few more times then we can see that we never get the same card twice because these the sample method will make sure that it's only unique values okay so now that we've seen some random methods let

Practical Use Case

me show you a practical use case for what we've learned so for my videos I usually need some sample data so for example with my CSV tutorial I created a lot of fake names and email addresses and things like that and I used the random module to do this so let's I have opened a sample file here where I'm creating a lot of fake names and phone numbers addresses and email addresses now there are some more advanced packages online that create fake data for you but I didn't really need anything too complicated so I just went ahead and wrote my own but we have a bunch of lists here at the top of our module that just has a lot of common first names and last names and street names and fake cities and states now normally you'd want to break these into different lines to be pepp eight compliant but this is just something for personal use and I don't like all the extra space that they take up on the extra lines so I just keep these on one line here so those are my lists and I'm gonna be getting random values from and then if we go down here just a bit then here I'm just creating a loop for however much fake data that I want so if I loop through this 100 times then it will create 100 fake names and for numbers and addresses and emails so within the loop you can see that we're grabbing the first random name from the first names and then we're setting this last variable to a random dot choice from the last names now here for the phone number it's a little bit more complicated so we're using an EPS string now if you don't know what an EPS string is then you can watch my video on strings to learn more about that but basically within the F string here our first value we are getting a random three-digit number between 100 and 999 and then we are doing a dash and then a 5 5 since I want this to be a fake number and then another dash and then a random four-digit number between 1000 and 9999 and then for the rest of the values here it's basically everything that we've seen before so the street number is just a random integer between 100 and 999 the street is a random choice from our list of street names the city fake cities the state is a random choice from our states and the zip code is a random 5 digit integer between 10,000 and 9 9 9 and then for the address we're just using another F string to combine all of those together so we have the street number of the street then just a street with a period and a comma the city state and zip code now for the email address we're not using any random values here we're just using this first variable which was a random first name from our list plus the lower last name and then just tagging on this @ bogus email com to the end and then lastly this print statement I can print this out and any format that I want to print these random values out so I'm printing out the first and last name and then a new line and then the phone number and a new line then the address and then the email and then a new line to separate all those out so now if I scroll up here to the top and I run this then we can see what these random values kind of look like so we can see that just in you know about 30 lines of code here with the random module that we're able to generate a lot of fake names to fake phone numbers and addresses and emails so this can be pretty useful if you need some dummy data to practice against or anything like that okay so I think that's going to do it for this video now I hope that now you have a pretty good idea for some different ways that you can use the random module but if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoyed these tutorials and would like to support them then there are several ways you can do that the easiest ways to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in a description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник