# Python Tutorial: Simulate the Powerball Lottery Using Python

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=HZ8uXq5VG2w
- **Дата:** 09.01.2023
- **Длительность:** 38:56
- **Просмотры:** 154,018
- **Источник:** https://ekstraktznaniy.ru/video/11739

## Описание

In this Python Programming video, we will be learning how to simulate the Powerball lottery using Python. I have seen several lottery simulations online, but not many of them go in-depth to calculate all of the possible combinations. Here, we will create a simulation that goes through every win condition and simulates the lottery in the way it is played in a real-life situation. Let's get started...

The code from this video can be found at:
bit.ly/lottery-sim

Random Module Tutorial - https://youtu.be/KzqSDvzOFNA
List Comprehensions Tutorial - https://youtu.be/3dt4OGnU5sM
Set Methods Tutorial - https://youtu.be/r3R3h5ly_8g
JSON Tutorial - https://youtu.be/9N6a-VLBa2I

✅ 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 - 

## Транскрипт

### Segment 1 (00:00 - 05:00) []

hey there how's it going everybody now I know it's been a long time since I've released a video and maybe at some point in the future I'll go more into why it took me so long to get back into making tutorials uh but I'm not going to go into that here instead I figured we'd just jump right in and do something fun to get back into the swing of things so I was thinking we could do a simulation of some type and a couple of months ago the Powerball jackpot broke the record for the largest Lottery jackpot ever I believe it was even over two billion dollars if not close to that and ultimately I believe someone from California ended up winning that jackpot but it got me thinking that it might be fun to write a script to simulate playing the Powerball so I've seen a few scripts online that simulate your chances of hitting the jackpot but I thought that we could write one that takes all of the Lesser prizes into account as well that way you get a rough estimate of what you could expect to pay versus how much win after playing the lottery a certain amount of times so before we write this let me show you the output from our finished script and what that will look like so right now I have the finished script that we'll be writing in this video and right now I have it set to buy two Powerball tickets for each drawing and by a drawing I just mean when they draw the winning numbers and they actually draw Powerball tickets uh three times a week so if there's 52 weeks in a year times three then that's about 156 drawings per year so in this simulation here we'd be buying two tickets for every drawing of the year and one more quick thing for people who don't really know about the Powerball let me also switch over to the odds here to explain exactly how Powerball works so you can kind of understand what the output from this script is going to be giving us so basically in Powerball you have five white balls and they are numbered between 1 and 69 and they also have red balls that are numbered between 1 and 26 which is the Powerball so if you hit all five of the white numbers it doesn't matter what order as long as you get those numbers right and the Powerball then you win the grand prize but you can see that the odds of doing that are very low that's like one in 300 million but then we also have some lesser prizes here so if you hit all five without the Powerball then you win 1 million if you hit four plus the Powerball fifty thousand uh four only four white balls only is a hundred three plus the Powerball is a hundred and so on and you can see once we get down here if you just hit two by themselves then you don't win anything if you just hit one by itself you don't win anything you have to hit the Powerball with those to get anything and it's only seven dollars and four dollars so now let's go back to the script here and let me go ahead and run this and I'll explain the output of what we're going to have for this little simulation here so we played for an entire year and we spent uh 624 dollars it's two dollars per Powerball ticket I should say that so we spent 624 dollars our earnings were 67 and I also uh wanted to keep track of how many times uh we hit each of the prizes so 5 plus P would be the jackpot that's five white balls plus the Powerball uh this one's just five white balls four plus p um and so on so the zero here is just that we didn't get any of the prizes so you can see that the majority of the time 296 times we didn't get any of the prizes 11 times we hit the Powerball only um four times we got one plus the Powerball and you can see here one of the times we got three white balls but no Powerball okay so now that we've got an idea of what we're actually going to be writing uh let's go ahead and go over to an empty script here and let's go ahead and get started on writing this now I will say right off the bat that this script is probably going to have a lot more code than it actually needs because I want to simulate this in the way that the lottery is actually played so for example I'm going to be grabbing random numbers for each drawing and each ticket that we buy but I think statistically we get the same results if I only generated the winning numbers once and compared everything to that but I just want it to be as close to the actual Lottery as possible even if it does slow down the execution of our code a good bit okay so with that said in order to get started on writing a simulation like this let's first put in some constants so first let's define our options for the white balls and also the options for the Powerball and like I said the white balls range from 1 to 69. nice so we'll just make this a list of numbers by saying white underscore score

### Segment 2 (05:00 - 10:00) [5:00]

possibilities is equal to and we'll just do a list of range from 1 to 70 because this last number here is not inclusive and then we will also do the white possibles in the same way and the power balls range from 1 to 26 so I'll put a 27 there and let's just rename that to red possibles and now that we have that let's define how many tickets that we want to buy each time there's a drawing and also how many drawings that we want to simulate so I'll just say tickets per drawing is equal to one for now and then number of drawings is equal to one and lastly here to keep track of how much money we've spent and earned let's go ahead and do a couple of constants there so I'll say total spent is equal to zero and earnings okay and some of the code I'm going to pull from a Snippets file just because I'm a slow typer and I know that you all don't want to watch me type out some of these uh longer consonants here but I also want to keep track of how many times we hit different prizes and I'll keep track of this with a dictionary of all the possible outcomes so if I go to the Snippets file here then let me grab this dictionary and paste this in and all this is what we saw before times one is going to be for all the different prizes so five plus Powerball five four plus Powerball and so on and for anybody following along as usual I'll have uh the Snippets and the code in the description section below okay so with that set up in place we're ready to actually simulate some Powerball drawings so first of all uh we need to Loop through the number of drawings that we want to simulate and draw the winning numbers for each of those so we'll just say 4 drawing in range of our number of drawings and now we're at that we're at this point what we want to do is to draw our winning numbers now I'm going to separate them out into the white balls and the Powerball so for the white balls let's take a random sample of five balls from the list of possibilities that we made earlier first to do this we're going to need to import the random module and this is a built-in module so you don't need to pip install anything so here at the top of our file I'll just say import random and then back down here in our Loop to get a random sample of five unique balls we can just say that our white drawing is going to be equal to random dot sample and we want to take a sample from those white possibles and we're going to set k equal to 5 to say that we want a sample of five of those now if you've never used the random module and want to learn more about how to use this in detail then I do have an entire video on the random module and I'll be sure to put a link to that in the description section below so random. sample here is going to return a list which is fine there's ways that we can make that work but since this is a unique set of numbers let's just go ahead and cast this to be a set um so and this will also make it easier to help us when comparing our numbers to the ticket numbers in a bit so to cast this to a set we can just wrap that in a set now for the Powerball this is just going to be a single number so we can just use random. choice to get one value from those possibilities so we can just say red drawing is equal to random. choice and we want a choice from those red possibles okay so now we have the white balls the random white balls from the drawing and we have the Powerball and there's probably a lot of different ways that we could combine these into you know one winning drawing and honestly we wouldn't even need to combine them at all but I feel like this will be easier to read if we combine both of those into uh you know one value now I'm going to do this with a dictionary so that it's easier to read but you could also use a list or probably you know a few other ways so I'm just going to say that the winning numbers are equal to and I'm going to make this a dictionary have a key of whites here and I will pass in our set of white

### Segment 3 (10:00 - 15:00) [10:00]

numbers and then I will have a key of red here and just pass in our red drawing okay so now we have the winning numbers here from a single drawing now remember we also gave ourselves the option to buy multiple tickets per drawing so let's Loop through the number of tickets that we plan to buy for each drawing so first let's just go ahead and loop through these by saying four ticket in our range of tickets per drawing now since We're looping through our tickets here if you remember I have this total spent up here and these are two dollars per ticket so let's just increment that by two each time we go through this Loop and now this is going to be similar to what we just did up here because we're just going to grab some random numbers for our tickets now if you have some you know favorite lucky numbers or something then you can just hard code those in you can just set this to you know buy one ticket and then hard code in your lucky numbers or something like that but if you buy multiple tickets at a store then usually they just print you off random numbers if you don't ask for specific ones so this is going to be basically the same here but let's just change this to be let's see my whites for the white balls and then say my red for the red ball and just like before let's go ahead and put this into a dictionary and instead of winning numbers I will call these my numbers and we will set the whites key equal to the white balls for us my white and then for the red we will do my red now like I said before this code is going to look a little long most of you might be thinking that we can you know condense this down with a good bit of you know some clever list comprehensions and things like that and you'd be absolutely right and definitely feel free to do that if you're following along but I just think that it's easier to read this way for people learning to simulate something like this for the first time okay so now we have our numbers for a specific ticket now we want to compare our numbers with the winning numbers and calculate how much we've actually won from that ticket now before we think about how we're going to do this one thing that I like to do if I get stuck writing code is to kind of just move forward one step at a time so let's say for the sake of argument that we get stuck here and we don't really know the exact law logic of how to calculate how much money we win off of a single ticket well if we haven't figured that out yet then let's just simply write a function with the name that we're trying to do even just doing this alone can help our thought process start working on a problem so let's write a function and we want to calculate the win amount so I'll call this function calculate when amount abbreviated now this function doesn't actually exist yet so I want to comment this out for now and let's go ahead and create this function here at the top of the file actually I'll put it underneath our constants here so let's create this function of calculate one amount and in order to calculate how much we've actually won we need to know the numbers that I have on my ticket compared to the winning numbers in the winning drawing and we'll just set a win amount here to zero for now and then whoops that went to 50 000 for some reason and now let's return that win amount so like I was saying if we get stuck then I think that it helps just by defining a function with parameters and return values like this just because you know it still might not be clear of the exact logic that we want but at least we're putting the parameters in place so that we know what we're working with and at least makes it clear where we'll solve this problem uh once we are working on a solution so just a small tip there that helps me from time to time whenever I get stuck but now let's go ahead and finish writing this function and see how we can compare our ticket to the winning numbers and calculate our actual winnings now if you remember uh from our graphic over here all we're going to need to do is see how many of our white numbers match up with their white numbers and if we hit the Powerball or not so we're going to need a way to see how many of our numbers are the same as the winning numbers now if you remember we used

### Segment 4 (15:00 - 20:00) [15:00]

dictionaries as these values if I go back down here these here are what we're going to be passing into our calculate when amount function so these are dictionaries with the keys of whites and red so if I wanted to grab the white numbers for my ticket then I could just say my numbers and access that White's key and if I wanted to get the white numbers from the winning drawing then I can just say winning numbers and access that White's key there and also we have to remember that the values of these keys are these sets of numbers so we're working with two sets of numbers here now since this is a set and not a list we actually have a very easy built-in method for doing this called intersection and I have a previous video where I go over sets and talk about the different methods that we can use with sets so again if you'd like to see more of what we can do with that then I'll leave a link to that video in the description section below but for now if we want to get the matching numbers between these two sets then we can simply use a set method called intersection so right here I'm saying hey for my uh White numbers the set of my white numbers I want to run this intersection and I want to intersect that with the winning numbers uh whites and what that is going to return is it's going to return another set of the same values that are in both of those sets now we're not interested in the exact values we're more interested in how many numbers we matched you know so we can see okay I have one of the white balls is the same or two and so on so to get the number we can just wrap this entire thing into a length and get the length of that intersection so this entire thing here should give us how many white numbers we matched from our ticket to the winning numbers so I will just put this into a variable called White matches now in terms of determining whether the Powerball is a match or not is going to be a lot easier because all we're going to have to do is we'll have a conditional seeing if that specific number matches so we can just say power match is equal to and we just want to say my numbers and grab that red value and we just want to see is that equal to the winning numbers red value and let's go ahead and put these in some parentheses here well never mind my code formatter doesn't like those so we'll just keep going now all this is doing here is uh this conditional here is going to return a true or a false value so if they do match then power match will be true and if they don't false okay so now that we know how many white matches we have and whether we have a Powerball match all we need to do now is write conditionals that are the same as the powerball's rules and then assign the amount that we win for each of those conditionals now again I'm going to grab some of this code for my code snippet because these are just going to be a lot of different conditionals but these are mostly going to all look the same aside from the number of matches and the winning amount but first let's go ahead and write the first one here and then I'll paste in the others so first let's check if we won the actual jackpot so if our white matches is equal to 5 then that means that we matched all five of those white balls and now we want to check if we match the Powerball so if I say if power match within this conditional so if we hit 5 and we hit the Powerball then that's the jackpot and the jackpot varies but so we can put in you know whatever we want here this goes up and down depending on uh if anybody's hit the jackpot recently or not but since I decided to write this based on that two billion dollar ticket let's go ahead and make this big and make it a two billion dollar ticket just like we're playing for that one a couple of months ago now if you remember we're also keeping track of how many times we hit each of these prizes so let's go ahead and also increment this as well so

### Segment 5 (20:00 - 25:00) [20:00]

I can say times 1 and we want to access that key and that key was 5 plus p and we'll just increment that by 1. now I'll also put in an else statement here now we're still Within this outer conditional here we're still saying that we hit five of the whites but this else here is just saying okay if we hit 5 but we didn't get the Powerball then we actually still win something here but the win amount is set to let me check over here real quick yeah that is one million so we can just set that equal to 1 million and here instead of the times 1 being 5 plus the Powerball which would be the jackpot this is just going to be 5 without the Powerball so this right here is basically what each of these conditionals is going to look like with just a few changes to uh you know the numbers here and the win amounts so instead of boring you guys to death while I write all of these out I'm just going to grab these from a code snippet and paste it in so I have this down here so let me grab this and then we'll go over and kind of look once we're done here now the only difference here once I paste this in is that the second conditional here is an L If instead of an if because we you know if we hit five then we don't want to check if we hit four after that so this is going to be an L If instead of an if so let's just go through these really quick so uh after this conditional here if we didn't hit 5 then we're saying okay well did we match four if we did match four did we hit the Powerball if so that one amount is going to be fifty thousand we're in comparing the times one if we hit four without a Powerball we only get a hundred if we match three with a Powerball we get a hundred uh if we don't get the Powerball we only get seven and so on and down here if you remember we don't get anything for just matching two we actually have to match two and the Powerball to get any win so that's why we're just saying if white matches is equal to two and the Powerball and that's also the same thing for one if we get one match and a Powerball then we get four dollars back and also we get money if we hit just the Powerball as well which is also four dollars and then at the very end we're just saying else uh if we didn't hit any of these then I'm just saying that we didn't win and that we're going to increment um that we hit zero and uh go with that as well okay so with that we already have all of our win amounts assigned for each possible outcome and we're already returning the win amount down here at the end of our function so that's going to be all that we need for this function so now we're basically done with our simulation script here all the hard work is done and out of the way now we just have to wrap up a couple of things at the bottom of the script and then print this out okay so first since we actually created this function now and this function is returning the correct win amount for each ticket all we need to do is set this to a value so I'm going to say that our win amount is equal to calculate when amount function and we want to pass in my numbers and compare those to the winning numbers and since this is the win amount for a single ticket we are also keeping track of our total earnings for all of our tickets so let's increment that value as well now if I go up here to my constants that was earnings I forgot what I called that so we can say that earnings plus equals that when amount and that's basically everything now all we need to do is just print out our results and then run some simulations so outside of all of our Loops here all we want to do is print and we'll just do an F string here and we'll say that we spent and then put in a dollar sign there and that was total spent and then let's put in how much we earned so we'll say earnings and that was called earnings and let's also print out our dictionary where it shows how many times we hit each prize with all of our tickets now if we just print it out directly then it's going to be a little difficult to read so a good way to print out dictionaries where they're easy to read is just to use the built-in Json library and this is super easy all we need to do is come up here and import Json import Json and then down here at the

### Segment 6 (25:00 - 30:00) [25:00]

bottom we can just dump this dictionary to a string by saying Json dot dump s and that dictionary was called times one so times one and to make this look pretty we can set an indent equal to 2 to where it indents those values out and again as usual if you want to know more about the Json library and how to work with that then I do have a specific video on that as well so I will also leave a link to that video in the description section below okay so that should be everything that we need but let's go ahead and run a few simulations here and make sure that we're getting the results that we expect now the main thing that we're going to have to change here for different runs of this script is going to be the number of tickets that we want to buy per drawing and the number of drawings that we want to simulate so right now we have this set to one ticket for one drawing so let's say there's that big two billion dollar prize and we just go out and we buy our one ticket for that one drawing and we're going to see if we hit it big so let's go ahead red and run that and unfortunately it doesn't look like we won we spent two dollars we earned zero and we can see down here um that zero was incremented by one there so we didn't win on that drawing okay so let's say that we really want to win that jackpot so instead of just buying one ticket let's buy a hundred tickets so we're going to spend 200 trying to win this two billion dollar cash prize so we're buying a hundred tickets just for this one drawing let's go ahead and run that and we can see that we spent two hundred dollars we only earned 12 and 97 of our tickets were losses on one of them we hit just the Powerball one was one plus a Powerball or actually two or so that's how you would just simulate one drawing um but let's say you know maybe you're thinking okay well I'm not just gonna buy you know a lot of tickets for just one drawing I'm going to spread it out over the year so I'm just going to buy five tickets and let's see if I think there was yeah we said there was 156 drawings per year so we'll just buy five tickets for every drawing uh for an entire year let's run that and see how that looks so we can see in that entire year that we spent uh fifteen hundred and sixty dollars we only earned 215. we did get one here that where we matched um three white balls plus the Powerball so now let's take this and do some bigger numbers here so let's say that somebody has plenty of money and they really want to win a jackpot at some point in their life so let's uh buy 100 tickets for your entire lifetime so if 156 is one year let's say that you live a very long life so that would be 10 years if I had another zero on here that would be a hundred years so for every single drawing uh you're buying 100 tickets which would be 200 and you're going to do that for your entire lifetime for every drawing so this is 100 tickets for a hundred years let's go ahead and run this and see what we get this is going to take a little bit longer okay so we got our results here and we can see that we over our lifetime we spent three million dollars and one hundred and twenty thousand uh on tickets uh but we only made three hundred thousand dollars in return so let's see what's the best we did here so we can see that most of these uh we lost completely um we hit a lot of uh powerballs 40 000 of those and these numbers kind of go down as we go up and the best that we did was hitting four whites plus a single Powerball and we only did that one time in our life now that's the funny thing about the lottery because a lot of people don't really comprehend the statistics stacked against them when they play uh because you know like I said there was somebody who did win that two billion dollar jackpot in real life uh so people think well you know that could be me and it could be but statistically speaking it's almost impossible because we bought a hundred tickets for every drawing for 100 hundred years and never even came close to hitting the jackpot we didn't even get the one million dollar prize and that makes sense if you think about it because since we spent uh 3 million and 120 000 dollars uh at two dollars a

### Segment 7 (30:00 - 35:00) [30:00]

ticket that means that we bought you know roughly 1. 5 million tickets but the odds of hitting the jackpot are almost one in 300 million so we just get this warped perception of it being more possible than it is uh just because there's millions and millions of these tickets being sold each week and out of those crazy possibilities sometimes somebody does hit it big now it's actually easy to change around our simulation a bit here too if we want so for example um if you have some you know like I said personal lucky numbers then you could just code those in directly instead of randomly generating tickets like we're doing here also another way that we can change this script is to actually simulate how long it would take to hit the jackpot if we did buy a hundred tickets for each drawing so let's just assume that we could live forever and we want to know how long it would take for us to bring in that 2 billion dollars well if we wanted to see that then we could easily change this script around a bit here so if I go down to our Loop where We're looping over our drawings right here let's just change this to a conditional of while true so basically we're saying hey I don't care you know how many drawings I say I want I just want to keep going until I win and I'm going to code in a couple of other things here too first of all we just want to go until we actually hit the jackpot so I'm going to say hit jackpot is equal to false and I'm also going to keep track of how many drawings we go through and so I'll say drawings is equal to zero and years so we'll keep track of the number of years that it takes us to hit the jackpot as well so right inside of our conditional here um remember this is going to be one drawing each time it goes through this Loop here and then in our inner loop here where we are checking our tickets all I'm going to do here is I'm going to check this win amount so I want to say if that win amount is equal to that 2 billion that we are looking to hit oops and this needs to be double equals there for a conditional then we are going to set that variable of hit jackpot equal to true and since we finally hit that jackpot then I'm going to break out of this inner loop now we also want to break out of this outer loop but we can't do that from this inner loop here so what we can do is we can go to our outer loop here at the bottom and I can just say okay if after that run we hit the jackpot then break and break out of this outer loop as well now I also said I wanted to keep track of how many years it would take until we actually hit the jackpot so I can keep track of that by saying if drawings which is the number of drawings that we've gone through we can do a mod 156 on this equals zero and basically what this is here is we're just dividing this by 156 and if the remainder is zero then it means that's been an entire year because there's 156 drawings for each year so that's one easy way for us to tell so then I can say years is plus equals 1 and increment that and just to keep our sanity because this might take a while let's go ahead and print how many years have passed also this will just let us know that our script's actually running because sometimes it can take a long time until you hit the jackpot okay so that should do it so now if I run this code then it's going to start looping through and trying to hit the jackpot and it'll break out once we do now this could and likely will take a pretty long time so I'm just going to go ahead and fast forward until we actually hit the jackpot and check back in once we've done that okay so we finally hit a jackpot here we can see that we have one jackpot let's see it took us 7 385 years and remember that's buying a hundred tickets each drawing uh which even that is very unlikely uh that any

### Segment 8 (35:00 - 38:00) [35:00]

of us would ever do that because that's six hundred dollars every week and that's a lot of money but even under that scenario it still took us over seven thousand years to hit that jackpot so if there's one take away from this video only play the jackpot if you have the money and are looking to have some fun on a universally small chance of winning uh but if you're someone who can't afford it then don't go into it with an expectation of being that one person to hit it big because like we saw here that is going to be almost impossible now we ended up spending uh let's see here 200 and 30 million dollars but remember we had that two billion dollar jackpot so um once we hit the jackpot our earnings did outweigh what we spent but again that's also using the biggest jackpot ever in history so uh yeah I wouldn't expect to ever have your earnings go above your spendings here um now if I divide this by two let's see that would be what 115 million so we actually did pretty good we only bought 115 or 100 yeah 115 million tickets if we go back here to uh the odds then remember the odds are actually one in almost 300 million uh so we actually surpassed the odds there a little bit so normally with the situation that we've set up here you know you could even get into a scenario where you could play for 14 18 000 years or 21 000 years and still not hit the jackpot so it takes a long time but with that said I think that's going to do it for this video now like I said earlier this is not a very efficient script statistically I don't believe that it matters if we're generating random numbers for each drawing and that is going to slow down this simulation by a lot we could probably get to thousands and thousands of years much faster than we did here but I just like doing it this way because it's more true to how the actual Lottery is done and also doing it this way might give us some more ideas for how to simulate you know other examples like this in the future where those types of things actually would matter so I kind of like breaking the problem down to do it the way that it's actually done in real life so as for it being a slow script uh trust me I know that because I just sat there and watched that count up to 7 000 years until we hit the jackpot so yeah it could be a lot faster than it actually is uh also like I said I know that this has been my first video in a very long time but I hope that you all had fun with this one and possibly learned a little of something along the way but as far as new content I promise you all that I'm feeling a lot more motivated to get back into recording these and I hope that this year is going to have uh video releases much more often than there has been previously and I promise to keep you all updated on those tutorials that I plan to release but with that said if anybody 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 enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to Simply like the video and give it a thumbs up and 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 or YouTube and there are links to those pages in the description section below be sure to subscribe for future videos and thank you all for watching
