this video has over 9 hours of content and contains 21 unique python projects these projects go in ascending order of difficulty so the very first project in the video is pretty simple it's just teaching you python completely designed for beginners and as you go through the projects they get harder and harder and harder and harder until you get into some pretty advanced stuff we have games we have using apis we have scripting we have automation we have fun tools we have alarm clocks anything you can imagine is probably in in this video and there is definitely a project that you will enjoy and you can learn from in terms of navigating here all of the projects will be timestamped in the description I've made this so it's really easy to find the projects and all of the links in terms of code resources assets sound effects whatever you might need for the project will be linked directly below the Tim stamp so let's say you're at project number four well what you can do is go down to the description find Project number four find the timestamp for it and you'll see beneath there there'll be a link that contains all of the code code for that individual project now just for your information this is simply a combination of a ton of other python videos that I've done in the past I had so many on my channel many of which you guys didn't even know exist or new subscribers haven't seen so I wanted to make one massive resource that just had so much practice that you can save this video and come back to it for days weeks or even months and constantly have a new project to work on I hope you guys are going to enjoy this it's taken me a fair amount of time to edit it and I've chopped out all of the intro and the outros so you just get right into the content no fluff straight to the point and right into practicing your python skills if you guys enjoy this type of content and you like my teaching style I do have a software development course I'll leave a link to it in the description check it out and I hope you enjoy this video so this quiz game the idea behind it is we want to ask the users a bunch of questions and then if they give us the right answer to these questions we'll kind of add one to their score then at the end of the program we'll print out what they got out of the number of questions so if there was 10 questions we would say heyy you got you know three out of 10 or seven out of 10 or whatever and maybe we'll even give them a percentage or something like that so let's get started the first thing I'm going to do here is use the print command or the print function I'm going to assume you guys are familiar with this but when you want to print something to the screen output something to the console you say print you put some value in here the value you typically put is a string a string is anything encapsulated in double quotation marks or single quotation marks and then this will be what is outputed so the first thing I'm going to do is just kind of welcome my users to the game I'm going to say welcome to my and then computer quiz so the specific quiz I'll go with is a computer quiz please feel free to go with whatever type of quiz that you want all right now we've welcomed the user to our game let's just quickly test this out in vs code to run your code you press this little uh kind of run button right here you're going to see it should open up a terminal down here and then notice it says welcome to my computer quiz uh because the program just R awesome so now what I want to do is ask the user if they want to play my game if they say no I don't want to play then we'll just immediately quit the game so to do that I'm going to create a variable I'm going to say play is equal to and then I'm going to use this function called input now what input allows you to do is ask the user to start typing something in in the console so inside of input in here you put what's known as The Prompt now the prompt is kind of what appears before the user can start typing so for example if you're asking the user for their name you may have the prompt be name and then colon and then maybe a space and then right here after this space the user could start typing whatever their name was so in my case I would put Tim and then whatever they type after the prompt and then when they press enter that will be stored in playing so if I type Tim and then I press enter now playing will be equal to Tim because after the prompt that's what the user typed uh before they hit enter right hopefully that kind of makes sense and even if the user has a space they say like Tim and then r all of this Tim space r will be included in playing because this is all the stuff they typed after the prompt before they pressed enter so I'm going to ask them here do you want to play question mark and then I'm going to add a space here the reason I'm adding a space is because if I don't add a space then the user is going to start typing right on the question mark and that's going to be kind of all smooshed together and it doesn't look nice and so we're going to add a space to make sure the user starts typing one space after the question mark all right so now if I run my program so I press the Run button it says welcome to my computer quiz do you want to play notice the cursor is here and now I can start typing whatever I want when I press enter nothing's happening because we haven't done that yet we haven't configured that uh but that's kind of the basics that's how you get user input and just to show you here if I print out playing what this will do is give me whatever the value of this variable is so if I run this here it says welcome to my computer quiz do you want to play say yes and then it prints out yes right right so pretty straightforward okay so now that we know if the user wants to play or not right because after this line is done we'll have something stored in playing we want to check if the user typed yes right and specifically if they didn't type yes we want to end the program so what I'm going to do is use something known as an if statement now an if statement allows us to conditionally check kind of uh or compare values together and see if something is true or false and so I'm just going to write out the kind of entire if statement and then I'll uh run through it step by step I'm going to say if play does not equal to so an exclamation point and then the equal sign and then I'm going to say yes then what I want to do is I want to quit the program and there's this function in Python that you can use called quit this will just immediately terminate the program so what I'm doing is using if I'm writing what's known as my condition this is the thing that I want to check so I want to check if the variable play which is what the user typed in is not equal to yes the reason I'm checking if it's not equal to yes is because if they typed anything other than the word yes I want to quit the program whereas if they typed yes I don't want to quit and so what happens here is we're going to compare whatever the user typed in with yes and since we're using not equal to if what the user typed in is not equal to yes this condition evaluates to a Boolean which is known as true and then if this is true right so if whatever the condition is is true then whatever is indented after this here is going to be run so hopefully that makes sense I won't go too much more into the syntax I assume you guys can probably figure it out yourself but the idea is you put a coal in and then all the stuff you want to happen when this condition is true you indent here and an indent is kind of four spaces I would recommend you use tabs rather than kind of going one two 3 four you'll get some issues uh with your indentation if you try to do spaces and tabs together so anyways let's just see this now uh let's run this program okay I'm going to say welcome to my computer quiz do you want to play I'm going to type yes and well the program is going to end regardless cuz we're not doing anything after this if statement but if I go here and I print okay uh exclamation point and then let's play smiley face um oops okay I need to fix my quotations here yeah okay that's all good let's run this now it says welcome to my computer quiz do you want to play I'll type yes and it says okay let's play right and then it gives a really bad smiley face that I need to fix and if we run this one more time and then this time we type no notice that it doesn't say okay let's play because this condition was true and so the program quit all right so that's about if statements hopefully that all makes sense we're going to be using a lot of if statements in this video so now that we say okay let's play what we want to do is ask the user their first question and so what we're going to do is the exact same thing we did when we were asking the user if we want to play we're going to say some variable I'm just going to call it answer because that seems to make sense is equal to and then input and then I'm going to put whatever the question is I'm going to say you know ask something about a computer I'll say what does CPU stand for question mark and then what I'm expecting is that the user is going to type in the answer right and so what I'm going to do is just add a space here to make sure that again the user is not typing right beside the question mark they have a little bit of space and now what I want to do is check if the user's answer is equal to the correct answer so I'm going to say if answer is equal to and then I need to type out what the actual answer is now in this case this is central processing unit and I think I spelled processing correct obviously you're going to want to make sure your answers are actually spelled correctly because even if the user types in central processing unit but they like forgot the G or they spell something wrong or they have like a capital p uh they're going to have the question marked as incorrect because the answer has to match exactly with what the user typed in okay so now we have a colon and now we're saying okay well if the answer was equal to Central Processing Unit what do we want to do I'm going to print that they got it correct so I'll say correct like that and notice I'm using single quotes and double quotes kind of interchangeably uh doesn't matter which one you use so long as you're consistent with the starting and uh and ending quote awesome so let's just run this now and see if this works so I'm going to press run it says welcome to my computer game do you want to play yes okay let's play what does CPU stand for central processing unit and then it gives me the uh the output saying correct now if I run this again do you want to play yes okay let's play what does CPU stand for I type in just CPU it doesn't give me anything because well this was not true sweet okay so now the thing is though if the user gets this wrong I want to tell them that they got it incorrect right we need some output saying them saying hey no that was not correct and so what we're going to use now is what's known as the else statement so whenever you have an if statement like this and you are checking if something is equal to something else and that's what the two equal sign is doing or you have some condition here if this condition here does not evaluate to true you can put this lse statement here which means if this is not true whatever is in the else statement will run so if I go here and I say print incorrect exclamation point now if this is false so if the answer does not equal Central Processing Unit then we will print out incorrect if we type anything doesn't matter just so long as this right here that we typed out is equal to false whatever is in the LC here will end up run so let me just show you what I mean and then we can talk about this a bit more so let's run do you want to play yes okay let's play what is CPU stand for central processing unit and then it says correct and oops I I should have typed in the incorrect one but that's fine let's just type in no and then notice it gives me Incorrect and if I ran this one more time type yes and I type some other random thing it still gives me incorrect so if I type anything other than Central Processing Unit the else statement runs and again the syntax for the else statement is you write else you do a colon and then any stuff you want to run you do indented after the else and you can do multiple things as well I could do another print statement and then both of these print statements would run uh if we got this question incorrect sweet okay so now we have our first question and now what we can do is kind of just copy this to do the rest of our questions right so I'll copy this uh one more time I'll do four questions for my quiz please feel free to do more and it's totally fine if we want to leave this answer variable the same I don't need to change this to be something else uh we could if we want to but since we are done using the answer for this question after this if statement it's fine if we use the same variable to store the answer for our next question so now what we're going to do is we're going to kind of remove all of our answers and questions and we're going to type in well new answers and new questions and I'll show you some more things that we can do here and kind of some fixes and all that as we go through but let's just get our questions done first all right so now my next question I'll say what does GPU stand for question mark and then this will be and I'll copy this Graphics Processing Unit okay so let's go Graphics Processing Unit like that I hope that's correct and then the next question we can ask um I'll just do a bunch of acronyms what does RAM stand for question mark this will be random access memory like that okay and then lastly we can say what does PSU stand for question mark and we'll just say power supply like that sweet so now we've got all of our different questions here and we're kind of printing out whether we got them correct or incorrect so let's just quickly test this out let's make sure this is all working so uh do you want to play yes what does CPU stand for central processing unit what does GPU stand for notice I didn't add the space here and since I didn't add the space you're going to see when I start typing here that it's kind of smooshed with the question mark so I'll say Graphics Processing Unit what does RAM stand for Random Access Memory okay what does PSU stand for let's just type PSU and then notice it tells me incorrect so I'm going to start by fixing these spaces here you guys saw what happened when I didn't add the space for the input so now it should be all spaced out properly sweet so now we've got this all working hopefully you guys are all familiar with this if and kind of else syntax now uh it just needs to be in this structure whenever you have a colon typically in Python the next line after that does need to be indented if I did this and like I didn't indent this line here you can see we're getting this red highlight and it's reason we're getting that is because uh the indentation is all messed up this is supposed to be indented after we have the else statement in a small note you can only have the else statement after an if statement right so I can't just randomly come down here and put an else statement it needs to come after an if statement appears right so hopefully that's clear okay so now the one thing that I want to show you though is that we might be getting some kind of weird results from our program that we don't expect so I'm going to run my program and I'm going say do you want to play and I'm just going to type yes with a capital Y and notice when I do that it doesn't actually start my program right it immediately quits and the reason for that is whenever you have a capital that is different than lowercase right so if you have yes that is not equal to yes these are different strings and so if we want to check the person's answer regardless of the case right if they have a capital y or a capital e or a capital s or something or you know multiple capitals if we want y cap or capital y capital e lowercase s um to be valid and to allow the user to play we need to do something now there is this method in Python called Lower and what lower does is it takes whatever text we type in and it just makes it completely lowercase so if I go here and I print you know Tim is great like that and then I say do lower and actually let me do this in another way that's not as confusing let me say text is equal to this and then I say text. lower what this will do and make sure you have the parenthesis by the way is it will convert all of this text to lowercase so if I just run my program here and we have a look at our terminal notice that uh wait I have to type something let's just type that it says Tim is great all in lower cases and so we can use this here to convert all of the answers that our user types in to lower cases so I can say playing. lower and then if the user typed in something with capitals it will just all be lowercase and that way if they type yes with any different casing it will still evaluate to True uh because we're converting it to lower now in the same fashion there is something called upper if you say. uper it will convert everything into upper cases and so then what you would do if you're using upper is you would make your answer in complete upper cases because you know you're always going to be converting anything lowercase to uppercase so hopefully that's clear but we're going to just throw do lower on here to all of our answers I'm going to say do lower I'm going to say do lower I'm going to say do lower going to say do lower and alternatively if you didn't want to do it this way you could actually just do it at the end of this input here you could say input. lower and then you could just remove this because now your answer is already converted to do lower so you don't need to convert it kind of in this condition right here okay hopefully that's all clear but yeah that's just taking your answer converting into lowercase and then you're checking if the lowercase answer is equal to well the lower case answer you actually have all right so let's rerun this I'm going to open up my terminal I'm going to run do you want to play I'm going to type yes with a capital Y notice this works now and now I'm going to do some capitals so central processing unit that works right GPU Graphics processing unit and then you get the idea I won't do the rest of them okay so the last thing I want to do here is Implement some notion of score right we want to be able to tell how many questions our users got correct so what I'm going to do is make a variable here at the top of my program I'm going to say score is equal to zero this is going to allow us to keep track of how many correct answers they have now all we have to do here since we Define score equal to zero is every time the user gets a question correct we just need to increment score so add one to score so inside of this if statement here because this is if the user got it correct right I'm going to say score plus equals 1 what that says is okay take the value of score and add one to it that's equivalent to saying score is equal to score + 1 so hopefully that's clear but that's a way that you can just add one to the variable and so if we add one to score every time we get something correct that means that at the end of our program we'll have some number right we'll have two three zero whatever however many questions we got right we can then use that to display how well the user did so I'm going to say score plus equals 1 I'm going to do this inside of all of these if statements here okay and now we've added one to score so now what I can do at the very end of my program once we're done all our questions is I can say you got and then I need to use a plus sign this is a concatenation operator I'll discuss this in a second score plus and then questions correct exclamation point but I need to convert this to a string so let me go through what I just did here okay so I said you got I did a space notice I manually added the space here I then had a plus sign and then I said string score and then plus questions correct so the reason I'm doing this string here is because score is a number right score is an integer it's not a string and so if I tried to do something like you know Tim plus one well this doesn't really make much sense right because I'm trying to add a number to a string and like how do you add one to text that's just an undefined operation that doesn't exist so what I need to do instead is convert this one to a string because now that I have two strings when I add them together what I get in Python is Tim one right they kind of get combined and so that's what I can do I'm going to convert this score here into a string so then when I add it to the other strings that I have here it's valid this operation works and I'm not getting uh some issue popping up okay and then I'm adding the questions correct so I'm kind of putting this string score in the middle of the string right you got whatever the number is questions correct okay so let's run this and you want to play yes I'm going to say let's CPU stand for central processing unit okay Graphics Processing Unit okay PSU RAM and it says incorrect you got two questions correct right now it's giving me how many questions I got correct and so the very last thing we can do here is we can copy this line and we can give them kind of a percentage right like you got 50% or you got whatever percent and the way we do that is now we're just going to take our score we're going to divide it by the number of questions that we have is four and then we're going to multiply all of this by 100 right and if we want to be extra clear here what we can do is put parentheses around this score over four to make sure this operation happens first before we multiply by 100 but you'll see if we did it the other way around we didn't add the parenthesis it would still work fine because we would do the division before we did the multiplication but anyways we're going to say now instead of you got questions correct we're going to say you got and then we're just going to add a percent on here now notice I'm not doing a space and since I'm not doing a space it's going to be whatever this number is and then plus and then the percent sign so it will come right after and then we can do a period so now we've calculated the uh the percent again just taking the score dividing it by our number of questions which is four and then multiplying it by 100 now note here if you change the number of questions you got to change this number right so let's go here and let's run this and let's go to our terminal yes we'll play I'll just type something random okay Random Access Memory correct and then power supply and then it says you got 50% you got two questions correct and with that that is going to wrap up our first python mini project so I know I went really slowly through this and really explained everything in depth that's cuz this is the very first project I'm trying to make sure this video works for everyone regardless of your skill level and now I will go a little bit faster I won't re explain a lot of the syntax that I've already explained now as we move into the new projects just anything new that I kind of come across that we use uh I will explain but this is our first project this is the quiz game there will be some code that has or there will be a link sorry that has this code in the description if you want to download this yourself but I would highly recommend you modify this you know change around maybe add like more than one point for questions that are worth you know more than one point that are more difficult or something like that right and you guys can do this as you please regardless that is the quiz game now we're going to move on to do a number guesser I think this is the one I was saying I was going to do second so this one is pretty straightforward but what we're going to do is generate a random number and we're going to track how many times it takes the user to guess this number and so what I'm going to do is zoom in a bit here so that we can uh see our code the first thing I'm going to do is import this module in Python called red all right so first thing to mention here is that this right here is what's known as a module so when you import random you're importing the random module now this just lets you use all of the functionality that's kind of in here this is default this is installed by with python by default you don't need to install it or anything like that in quick note there is modules that are built by you know people like me or other developers out there and you can import them uh but you have to install them first this one is just built into python by default and so no installation is required anyways let me show you how to make a random number so there's a few different ways to do this but the two simplest ways are to do random Dot and then Rand range then you're going to do an open and closing parentheses and let me get rid of the print statement so we can see this better for right now and here you're going to put the start and then the stop of the range for your random number so you would do something like negative 1 if you wanted to start the range at negative 1 and stop at 10 excuse me and then what this would do is generate a random number that goes from netive - 1 to 10 but does not include 10 so that's very important the number you put here is the absolute upper bound you cannot have have the number 10 be generated if 10 is here if you wanted the range to generate a number between 1 and 10 you would have to put 11 again I don't know why they do that there's just some things in Python that aren't necessarily intuitive for beginners but with this is 11 it's not going to generate 11 it will generate up to 10 so make sure that's clear now there's another thing you can do here if you want the range to just start at zero you can say random. Rand range and just put the stop if you just put one thing here what this will do is generate a random number between zero and this number minus one so up to 10 and yeah there you go that's how that works uh okay so let's do something from -5 to 11 and let's say R is equal to random. Rand range and let's just print R okay so let me run this and we'll look at our thing here okay run and notice we get a five now if I run this again we're getting A3 I run a bunch of times we get a bunch of random numbers you see this is random and there you go that's working we got a enough we can just run a bunch of times we got a 10 notice we won't get 11 if we do this sweet so we're getting a random number so that's one way another way to do this is with a function called Rand int now Rand int works the exact same way as Rand range except now it will include 11 so the upper bound range now includes the number that you typed doesn't go up to but not include it so now if I do 5 to 11 11 will possibly be generated so if I run this now uh we get six right and we if we keep running it we might see that we get 11 um okay I'm not this could take a while yeah there you go so we do get 11 so that works okay sweet uh and same thing here if you decide to not include the start it will just generate up to and including this end number that you put right here so that's how you make a random number so what we want to do is generate a random number so actually let's let's leave this here let's say random uncore number and then we want to ask the user to guess this number and every single time they guess it we're going to tell them if they were above or below the number so that they can do it in like a reasonable number of guesses especially if we make this number like really large right so the first thing I'm going to actually ask the user is how large of a number they want to generate so we'll assume it starts at zero and then we'll ask them to type in a number and uh we'll generate up to that number so I'm going to say um let's say top of range is equal to and then input and we'll say type a number won't even tell them what it's for we'll just say type a number okay so now they're going to type a number so what we actually need to do here is we need to make sure that this uh thing they typed in here is a number because if the user types in like hello or Tim or some random string something that's not a number then we can't use that right and we also need to make sure the number they type in is greater than zero so I'll show you how we do that I'm going to say if the top of range do is digit okay and then I'm going to do an if statement inside this if statement I'm going to say if the int and actually we're going to do this we're going to say top of range is equal to int top of range and let me pause here and explain what I'm doing so first of all uh you can make a variable using underscores when you want to have multiple words it makes a lot of sense to make the name with underscores so like top underscore of underscore range you can't have a variable that's like top range that won't work you need to have it connected uh you can't have like two separate words like that anyways this is equal to input the user is going to type something again Now by default when the user types something in it's going to return it to us with double quotation mark so it's going to be a string so even if the user types in like 25 it's going to be returned to us like this and this here for python is not considered a number it's not considered an integer it's considered a string and so we need to convert this 25 so that it looks like this so that it's actually a number and the way you do that is you use this function called int so you surround the string with int and then it will convert this string into its numeric representation so it will give us 25 however if you try to convert something that's not an actual integer into an INT it's going to fail you're going to get an error and so we need to make sure that what the user typed in is a digit before we try to convert it into an INT and the way you check that is with this isdigit method so I say if top of range. isdigit what is digit will do is Return To Us true if this is a number otherwise it will return false and so if this right here is true we will convert top of range into an integer so top of range is equal to int top of range then we will check if top of range is greater than zero so we'll say if top of range is uh actually we're going to say less than zero less than or equal to Zer specifically then what we will do is we'll print out please type a number larger than zero next time and then we'll just quit so we'll tell them what they did wrong and then we're just going to quit the program right there otherwise if we make it through all this we're good but one thing we need to do here is we need to put an else and we need to put quit and we need to put a print statement that says please type a number next time so let me run through this what we're doing is checking if it is a digit if it's not a digit so in the lse statement we need to tell them hey you got to type in a digit just doesn't work if you don't type in a number right and then we quit now if that works if it is a digit we can convert into an INT we make sure it's greater than zero if it isn't then we tell them hey you got to type in a number and then we quit but if we make it through all of this and we don't quit so we've now converted the number to an INT we can now use that number to generate our random number so we can say random number random. Rand int and then we can put top of range as our variable for generating that random number and we'll now generate up to whatever number they typed in sweet so now that we have that let's just print out the random number and let's just test this and make sure it's all working so I'm going to run this type a number let's type five and we got one issue Rand in missing one potential argument B okay so this is my fault I was saying when we used Rand int we could just include the top of the range that's false we need to include the bottom of the range as well so I'm going to put zero there and now this should work so let's run this and let's type a number let's type five and there you go we generated a random number which was four if we run this again type five we get three you can see this is indeed working sweet so now that we have our random number we want to keep asking the user to type in a guess for the number until they get it correct and so I'm going to use a while loop here and I'll explain how this works in a second I'm just going to say while true now what this means is okay we're going to do whatever is indented after this wall Loop here after the colon while this condition whatever is at the top of here is true so right now if we just decided to like print 10 this would happen infinitely this Loop would never stop unless we actually like manually close the program the reason is because there's no way for this to end right I say while true well true is always true and so we're just always going to print 10 however there is this keyword it's called break and what break will do is immediately stop the loop as soon as this line of code is executed so what we can do is use this break keyword to break out of the loop stop running the loop as soon as the user types in the correct number so we're going to say while true this is the condition for the while loop we could do a a real condition we could say something like while um like input and actually we'll say like user guess is not equal to random number we could do something like that that would work as well but I want to show you using the break keyword so instead we're going to do well true all right so what we're going to do is we're going to start by asking the user to guess what the numbers right that's the very first thing we do every single time we ask them we say okay make a guess so I'm going to say uh user guess is equal to and then input I'm going to say make a guess Co now same thing here we need to check if the user's guess is actually an integer right so I'm going to copy exactly what we just did right here and I'm going to paste it down below and I'm going to say okay if the and now instead of saying top of range I'm going to say user guest. is dig then user guess is equal to int of user guess and then I'll even take this and we don't need to check if the number is less than zero that's fine uh we can just do this so I'm going to say and I'm going to get rid of this this quit Okay let me explain this what I'm saying is okay the user guess is equal to input make a guess they're going to type in some number this comes in as a string we need to make sure that what they've typed in is actually a number if it is a number we'll convert it to a number we're all good however if it is not a number then we're going to say please type a number next time and we're going to use this keyword called continue now what continue will do is automatically bring us back to the top of our Loop so it's a little bit different than break rather than ending the loop it just brings us back to the very top so if I did something down here like printed after continue if we hit this continue keyword this won't run we won't print we'll just go back up to the top of the loop and ask the user to make another guess and so that's what we're going to do however we're going to come down here now we're going to say if the user guess is equal to the random number we're going to print and we're going to say you got it you got it correct otherwise we'll say else print you got it wrong so if they didn't get it right they got it wrong obviously right whereas if they uh didn't type a number we'll just say please type a number next time and then we'll continue rather than doing this and telling them they got it wrong after they didn't even type a number in okay hopefully that makes sense we can test this out though and make sure it's working so save the program and run now type a number let's type a number let's say 10 okay make a guess we're going to guess three and wow okay we actually got it um that's great but notice that it's still asking us to keep making guesses and to quit this you can type contrl c on your keyboard if you get into an infinite Loop the reason it's telling us to do that is because we didn't break out of the wall Loop right we said you got it but we didn't stop and to stop we need to use the break keyword so now you'll see if we do guess it we'll immediately stop looping whereas if we don't get it we will continue looping because the break keyword's not here so let's run this now type a number let's just go up to five make a guess one you got it wrong okay we'll guess two you got it wrong three you got it wrong four you got it wrong five you got it sweet and then we exit the loop there you go okay so that's working fine now what I'm going to do is I am going to keep track of how many times the user actually makes a guess so to do this I'm going to make a variable similar to what we had with score before I'm going to say guesses is equal to zero and now every single time we start this wall loop again I'm going to increment add one to guesses so I'm going to say guesses plus equals one so at the very top of the loop we'll increment guesses so the first time this runs guesses will be equal to one we'll go through all of this then we'll come back up to the top guesses will now be equal to two the user will now make another guess and now when we exit this wall Loop once this is done we're going to print out how many guesses they got I'm going to show you a different way to do this this time I'm going to say you got it in and then we'll say comma guesses and then the string guesses so another way to print multiple things on the same line is to use commas so I'm going to say you got it in and then I'm going to say whatever the number of guesses is notice I don't need a space here whenever you have uh commas separating your different things that you're printing out it will automatically add spaces in between them and then notice here I didn't even convert this to a string and that's because the print statement is smart enough to say okay hey this is an INT I'm going to convert this into a string for you and kind of automatically add it to this string so what we were doing manually before the print statement can just do for us and so this time we'll let the print statement do it uh this line here is completely equivalent to just having the uh the plus the space the string uh the other plus and the space right it's the exact ex same thing okay so let's go back to what we had and there you go we are all good now let's just run this and I am going to show you how we can tell them if they got it uh greater than or less than because I did tell you that we were going to do that okay so let's run this and let's say type a number let's go five make a guess one you got it wrong two you got it and then it says you got it in two guesses sweet all is working so now the last thing we want to do is tell the user if they were greater than or less than the number so that they can kind of narrow down their guesses and so rather than just telling them you got it wrong now inside of the else statement we're going to check if the user was above or if they were below and there's a ton of different ways to do this I'm just going to do it this way I'm going to say if the user guess is greater than the random number then what I want to do is say print you were above the number exclamation point otherwise I'm going to say print and I'll say you were below the number all right so let's run through this we're just checking if the user guess is greater than whatever the random number is if it is we're going to tell them they were above the number otherwise if it wasn't greater than it must be less than and we're going to say you were below the number now some of you may have heard that statement if it wasn't greater than it must be less than you say no it could be equal to that's correct but the thing is up here we checked if it was equal to and so if it was equal to we would have uh gone into here we would not have hit this elf statement so if we're in this elf statement we know we must not be equal to the random number and so instead what we can do is just run this if statement that's inside of the else I'm going to show you a more elegant way to do this in one second but let's just run the program and see if this works now okay let's run this type a number let's type 20 make a guess let's guess 10 you were above the number okay so now I don't have to guess below 10 so I'm going to guess five you are above the number okay it's less than five uh Four 3 2 two one you got it in nine guesses okay so anyways that did work but it was telling us whether we were above or below uh let's see if I can guess something that's actually I guess I couldn't have guessed anything below one so let's run this again let's type 10 let's guess one and then this time it is telling us we're below the number okay great so that is working okay so the one thing I want to show you here is how we can clean this up a little bit using something new that we haven't seen yet which is known as an L if statement so an L if statement is something that kind of happens after the initial if statement is checked so I'm just going to type this out and then I'll show you how this works so I'm going to say l if okay so now what I've done is I've made this code a little bit cleaner and the way I've done this is I've removed that kind of nested if statement that we had and I've now implemented an L If instead so what the L if does is if the initial condition is not true it will then check another condition so it says okay if this is true we're going to do this we're going to skip all of this if this is not true we're going to check this if this this is true we're going to do this and we're going to skip whatever else is after however if this is not true then we're going to do whatever is in the else so we're going to check this if it's true we do this otherwise we check this if it's true we do this and otherwise if both of these things are false we do what's in the else and so that's just another way to do this rather than having what we have before which was the else and then all of this kind of indented in the else right this just cleans it up and small note you can have as many LF statements as you want so I get add another one like this if I wanted to do that but in our case it doesn't really make any sense to do that okay so that's actually it uh I'm not going to run the program just believe me this this does work and yeah that is going to be our number guessing game so I'll zoom out a bit so you guys can kind of see all of the code but that is how that works I guess there's not really much more to say about that and now we'll move on to the next one all right so now we're moving on to rock paper scissors now obviously you guys know how this game works what I'm going to do here is make it so that the computer keeps track of how many times the user gets it correct versus how many times the computer gets it correct when I say corrects I mean whoever wins uh rock paper systems so the first thing we're going to do here is import random uh now small note here when you are importing modules uh it's typically best practice to do it at the very top of the program I see some beginners import the module like right before they use it that's fine you can do that but it's just a better practice to have it right at the top so it's really easy to see what stuff you've imported and obviously remove it and then you can use it throughout the entire file where if I tried to use like random up here it doesn't work until after I've imported right uh so hopefully that's clear but anyways that's what we're going to do so what we need is we need two variables one for the user score and one for the computer score so I'm going to say user uncore wins is equal to Z and I'll say computer uncore winds is equal to zero as well all right now I'm going to have a while loop I'm going to say while true and the first thing I'm going to do here is I'm just going to ask the user uh actually yeah I'll ask the user to input rock paper or scissors and then I will also let them type in Q uh like the letter q and if they do Q then we'll just immediately quit the program so let's handle that first let's say user uncore input is equal to input and I'll say type and then we can say rock slash paper slash scissors is scissors with a with with two s's I think that's how you spell it okay rock paper scissors and well paper should be spelled correctly okay rock paper scissors or Q to quit okay all right so now that we have that we will go down and we will check let me just zoom out so we can see this here what the user actually typed in so the first thing I want to do is I want to see if they typed in Q so I will actually convert this to lower in kind of the way that I showed you we could do it previously we'll take whatever the user types in and we'll just convert it to lower and actually instead of a period let me do a colon and let me add a space so it's not all smush there okay so type rock paper scissors or Q to quit and now I'm going to say if the user input and this is converted to lower right is equal to Q then what I'm going to do is I'm going to quit otherwise I'm going to check if they typed in rock paper scissors or if they typed something else and now I'm going to show you how we can check if the user input is equal to more than one thing because previously I've been showing you how we can check if it's equal to just a string right but now I'll give you a little bit of a I don't want to call it a hack but a little bit of a trick so that you can see if the user typed in rock paper or scissors all in one line rather than writing three if statements so I'm going to say if the user input is in and I'm going to use a list you guys probably haven't seen this before if you're uh like a complete beginner in Python and let me just kind of fix this a little bit so p s I'm going to type it myself and I'll explain what's going on here okay so let's make this in quotes Okay and then this needs to be in quotes to okay I'm really messing this up quite badly but get the idea okay so what I've done is I've just created a list now a list is anything encapsulated in these square brackets um that is like separated by commas so I have this rock paper and scissor string in this list and so what I'm saying is if user input is in this list I'm checking if whatever the user typed in exists in either of these three strings so essentially we're just checking if the user typed in Rock paper or scissors now you can put any strings in here that you want uh but we're just checking obviously if this is in here and that's how we can check multiple things on one line there's other ways to do this too but this is kind of one nice trick that we can use so I'm going to say if user input and I'm actually going to say is not in now this is another keyword again that you may not have seen before what this is going to do is simply reverse the kind of thing that we were checking before so we were checking if the user input was in rock paper scissors so now when I say not in I mean obviously obiously as you would read it in English this is checking if the user input is not in here if it's not in here that means I didn't type in something valid and well what we need to do is have them type in something valid so what I'm going to do is say type continue here and what this will do is just re askk them to type in rock paper scissors or Q so we could give some error message saying that's not a valid option or something like that but what I'm going to do is just have it so it keeps asking them to type something in until eventually they give us something valid so when I hit continue that means anything after here is not going to happen right if this continue is hit we're it's going to go back up to the top of the W Loop sweet and actually rather than saying quit here what I'm going to do is say break so this will break out of the wall Loop and then that will actually automatically end the program for us because we'll be at the end uh we won't need to what do you call actually manually quit so the break breaks out of the wall Loop which means we'll go to wherever the end Loop is done or wherever the wall Loop is done and then we can actually just print something saying you know good no not not that uh goodbye exclamation point sweet okay so now at this point in time the user has given us valid input they've typed in rock paper or scissors so what we need to do is generate a random number that represents rock paper or scissors for the computer so I'm going to say Rand uh actually say yeah random uncore number is equal to and then this is going to be uh random. Rand int and we'll generate a number between 0 and two so if they type in zero that can be Rock if they type in one that can be scissors or paper they type in two that can be scissors so let's write that down in a comment uh to do a comment in Python you hit the pound sign or use the pound sign like the number sign and then type anything after it anything on a line that comes after a pound sign will not be read by your python interpreter and it's just there so that as a programmer it's easier to read and gives you like you know documentation or comments about what's going on so I'm going to say rock is one or rock is zero I'm going to say paper is one I'm going to say scissors is and then two sweet so the way that I'm going to do this now is I could do an if statement or I could write three F statements say you know if random numbers equal to zero then the computer picked Rock if random numbers equal to one if random numbers equal to two actually don't need to do that what I can do is uh H let's see here okay so what I'm going to do now here to actually assign uh some variable equal to rock paper scissors to represent the computer's kind of choice is I'm going to use a list now again this might be a little bit confusing but I think you guys will get the idea if I do this I'm going to take this list right here rock paper scissors I'm actually going to store it in a variable I'm going to say options is equal to rock paper scissors and I'm going to change this here to be options so this is the doing the exact same thing as before except we're just storing this list of values now in this options variable now if you haven't seen lists before these are actually very interesting they're known as a data structure and they are collections of elements right we have multiple elements multiple St stored in this list and well the way we access these different elements in this list let's say I just wanted scissors or I just wanted paper I just wanted rock is we use what's known an in known as an index so if you write the name of your list which in this case is options that's the variable starting the list you can put these square brackets and then you can put a numeric index that represents these different elements so in this case the different indices of this list are zero 1 and two and if we had another element right let's just go you know test then this would be index 3 so the way this works is you start counting at zero and then you just go up by one every single time so the very first element is indexed by zero second 1 3D 2 fourth 3 and so that's all that is so when I say options at zero that's going to give me rock when I say options at one that gives me paper when I say options at two that gives me scissors and so I have some random number that's between 0 and two right and z represents Rock one represents paper and two represents scissors let me get rid of test so what I can do is say uh let's actually change this here say computer uncore guess or computer uncore pick I guess is equal to and then this is going to be options at whatever the random number is because this will be between 0o and two and so we'll use that as the index to actually access the string the thing that the computer chose right rock paper or scissors so now what we can do is we can print out what the uh computer chose we can say computer picked and then we can say comma and we can say computer unor pick and then we will decide who actually won right so then we'll say who won and let me just do comma uh actually hm let's do plus and let's just add a period the reason I'm not doing a comma and then the period is because if I do a comma it will automatically add a space between this period and the computer pick which I don't want and so instead we're just going to add the uh the dot like that okay so we're going to say the computer picked that and then we need to decide who won right and so to decide who won we need to all compare uh the user's pick to the computer's pick so we're going to say if the user input is equal to and then I guess we'll say rock we'll then do kind of the winning condition for the user so if the user picked Rock then what do they win against well they win against scissors and so now we need to check if the user picked Rock and the computer picked scissors so what I'm going to do is use this keyword called and and say computer pick is equal to and then scissors so if that's the case we'll print out uh U1 exclamation point and then we will say user underscore wins plus equals 1 so that they get one more win so what this and does is it checks if the condition on the left side and the condition on the right side are true so what happens in this if statement or what's in this if statement will only happen if both of these things are true pretty straightforward that's how the and works alternatively there's an or and an or will kind of do the opposite it will check if either the left or the right is true or both of them are true if any of those three things happen this is true this is true or both of them are true then what's in the if statement will run whereas with the end it has to be both of these being equal to True For What the What in the if statement is going to run or if what's in the if name is going to run sorry butchering my English here okay so that's one of the win conditions for our user and then if that's the case we can just go ahead and say continue and we can go back up to the top of the wall Loop and keep going but we need to check the other wi conditions right and there's two more win conditions let's go here and let's fix the indentation okay and we'll say if the user input now is equal to paper and the computer picked uh what is it Rock then that means that we won right and so we would add one to the win and then the last one is we picked scissors and the computer picked paper sweet so the reason I'm doing this continue here is because after we've determined that we've one there's really no point in checking these other if statements so we could instead do these in L ifs so I could say if L if L if and then actually I could remove all these continues and in fact let's do this and uh then we will go down here and we will say else and then what we would do here is say print U lost and then we will say computer wins okay plus equals 1 so the reason this works now is because we check if we won with The Rock versus scissors we check if we won with paper versus Rock we check if we won with scissors versus paper and if none of those are true that means we didn't want win right there's no point in checking if the computer beat us in all the other uh scenarios we just need to check if our three win conditions were true if they are not true then we know that we lost and so we would print we lost and then we add our computer wins and this is an example of using multiple LF statements we'll check this one if it's false we'll check this one if it's false we'll check this one if it's false we run this if any of these are true we immediately stop and we do whatever is inside of here uh which is increment the user wins and print youu want great so the last thing I'm going to say before I do goodbye is I'm just going to print out the number of user wins versus computer wins so I'm going to say the user or I'll say in this case you U1 comma user wins times and then we'll print the computer one and then computer winds times period great so hopefully that is all good let's quickly run through what we've done because we wrote a lot of code here relatively quickly as you can tell I'm kind of picking up the pace a little bit as we go through this so we have our user wins our computer wins we're importing random which we've already discussed we have our list first time we've seen this called options has our three values in it it we have while true we have user input equals input and then we say type rock paper scissors or Q to quit we make whatever they type in lowercase we check if the user inputed Q if they do we break we're done we stop the program if they didn't then we check if the user input is not in the options if it's not in the options that means I didn't type a valid rock paper or scissors and so we press or we uh go continue which means we're going to start the loop again we're going to ask them to type something in then what we do if they typed in something valid is we generate a random number between 0 and two uh this is the like what it stands for rock is zero paper is one scissors is two we make our computer pick so computer pick is equal to options at whatever the index is of the random number we then say okay the computer picked this we then check if the user won based on what the computer picked right and uh yeah that's all good and then we increment computer wins or user wins and we will keep going until eventually the user hits Q once we're done we'll bring break out of the wall Loop and we'll print these three things let's run it let's see if it works okay type rock paper scissors or Q to quit let's just test Q okay you won zero times the computer won zero times goodbye nice works okay let's actually type something let's go rock it says computer pick scissors you won nice okay type rock paper scissors or Q to quit let's go paper uh computer pick scissors you lost okay that sucks let's go uh scissors uh computer picked paper you won nice let's go rock okay and let's go q and then it says the computer one one time you won three times goodbye all right so that is rock paper scissors keeping track of how many times with the user and the computer wins now we're going to move on to the next project which is the Choose Your Own Adventure game all right so this next project is one of my all-time favorite beginner projects and that is because it's so customizable there's so much you can do with this I'm really only going to talk about this for about 5 or 10 minutes because this is up to you guys to make this kind of as big as you want so this a Choose Your Own Adventure Ure game and I guess the best thing to relate this to if you haven't heard of this before is kind of these children books and actually they have books that aren't children versions too but they're kind of like pick your own story books where you'll go to a page right and it will say like if you want to go left turn to page like 42 if you want to like swim across the river go to page 97 whatever and then like it kind of brings you on all these different paths throughout the book based on decisions that you make so same thing here we're going to ask the user to make a bunch of different choices we'll start with something simple like do you want to play the game right and then if they say yes we'll say okay you know you come to some Bridge do you want to cross it or do you want to swim underneath it and then based on what they say if they cross the bridge maybe we'll say okay you come to a dead end do you want to turn around or do you want to search the jungle whatever like you can be as creative as you want them just coming up with stuff at the top of my head but then if they had instead decided to swim under the bridge maybe we say like oh you know there was a crocodile and your your journey ended whatever so you guys can make it as complex as you want but I'll show you like the basic structure and kind of the nesting of statements and how it works so the first thing we're going to do is I'm actually going to ask the user for their name this is one this is something I don't usually do but I think this will be cool so I'm going to say um name is equal to input I'm going to say type your name Co and then I'm going to say print and I'm going to welcome the user I'm going to say welcome comma name comma to this ad Venture exclamation point and then we'll actually get right into it and before I even ask them if they want to play what I will do is I will just say like I'll ask them for a choice I'll say you come to a dirt road or something do you want to go left or right whatever so the first thing I'm going to say here is answer in lower cases is equal to input um and I'll say h you are on a dir Road it has come to an end and you can go left or right uh and then I will say which way would you like to go question mark okay so let's just go here and notice that it's doing this autof formatting you guys don't have to worry about this just my IDE Auto formats my code when I save it and so you can see it's kind of going on a new line uh don't worry about it you can just do yours in the same thing but anyways that's like my prompt you're on a dirt road it has come to an end and you can go left or right which way would you like to go and I'm expecting them to type in left or right so the first thing I'm going to do is I'm going to check if they typed left or right I'm going to say if answer is equal to left and actually before I do that I'm going to convert this input here to lower and I realized I kind of messed something up hopefully that fixed it okay so we're going to say do lower and let me add the space here between the question mark okay so answer equals equals left so if the answer equals left then we'll do something else otherwise uh we will actually we'll say l if answer is equal to write and then else we'll say uh print not a valid option you lose so I'm just going to make it so if they ever give us something that's not valid they just immediately lose the game okay so if the answer is equal to left then uh we need to pick what's going to happen when they go to the left if the answer is equal to right we need to decide what's going to happen if they go to the right so I'll start by kind of doing the left path and let me just put a print statement here so I don't get an error um you'll notice that if you don't have something indented after it's expecting something to be indented it will like yell at you and be angry so you can just put an empty statement like print and that will kind of fix it okay so now what I'm going to do is I'm going to ask another question I'm going to say answer and you can name these variables whatever you want maybe it would make more sense to name them like Q2 or something whatever I'll say answer is equal to input and I'll say um okay like you come to a river and you can walk around it or swim across and I'll say type walk to walk around and swim to swim across and make sure that when you guys do this you're kind of like uh you know telling the user what they need to type in because sometimes it's not intive on what they should be typing and so I always try to give them the option like tell them explicitly like what I'm expecting them to type so they don't give me an invalid option uh like not intentionally you know so now I'm going to check inside of here if the answer is equal to swim L if the answer is equal to walk and then else I will print not a valid option you lose right so we'll do that okay so now I need two things to happen here so print and print okay so I'm going to pause for a second hopefully you're getting the idea of what's going on here right if they go left I ask them a different question and then I check inside of this if statement what they answer for that next question and then I do something else whereas if they go right I'm going to ask them a different question and so it's cool because there's like all of these different paths that people can explore and like if they only go left at the beginning they're only exploring like half of the potential paths and then as soon as they go right there's all new different options now you could have the same options for different um things they type right if they decide to go left or right you could in theory ask them the same question if they go left or if they go right but I like to do it differently I think that's more fun so let's just kind of continue on this path here we'll say if the answer is equal to swim then I'll print um you swam across and were eaten by an alligator is that how you spell alligator maybe you guys can tell my spelling is not the best okay eaten eaten there you go buy an alligator nice now if they decide to walk across I'll say you walked for many miles ran out of water and you lost the game okay so both of these options here were invalid so if they decide to go left doesn't matter what they chose they were just going to lose and so instead they have to go right and so we've kind of ended the path now on the left but if we wanted to maybe swim was like the correct answer quote unquote we could add another path here and we don't have to have them lose on one of these options I could add another path for walk too right like hopefully you're getting the idea you can just chain these kind of if statements in as far as you want so now let's do something for going right and actually before we do that let's let's test this out and let's make sure you guys understand what's going on here okay so type your name I'm going to say Tim says welcome Tim to this adventure you're on a dirt road it has come to an end and you can go left or right which way would you like to go let's go left when I go left it says you come to a river you can walk around it or swim across type walk to walk around and swim to swim across you're going to type swim swim says you swam across and we're eaten by an alligator and then there you go boom you lose right okay so now let's go and do something for right so for right I'm going to say answer is equal to input um I'm going to say you come to a um Bridge it looks wobbly do you want to cross it or head back question mark and and then the options I'll put here I'm just going to put them in Brackets I'll say cross slashback to kind of really indicate hey that's the two things that you're supposed to be typing Cross or back and then here I'm going to just copy this if else structure just so I can fill it in I'm going to say if the answer is equal to back if the answer is equal to cross and then I'll continue so now I'm going to say if answer equals back uh you go back to the um I don't know like main road whatever we can make this whatever you want now you can decide to drive forward I don't know drive to the left or go to the right or you know what we can make going back just just be the wrong option we'll just say you go back and lose I I don't think you guys need me to uh to give too much detail here because I'm having trouble coming up with this okay so we're going to say that Crossing is the correct option so if they decide to cross then what we're going to do here is now we're going to ask them another question we're going to say answer is equal to input we're going to say you cross the bridge and meet a stranger do you talk to them we'll say yes comma no question mark okay and then same thing here we can say if answer is equal to Yes uh L if answer is equal oops is equal to no and then else we'll say not a valid option you lose so let me copy that okay not a valid option you lose and then here again we can decide what we want so we'll say print maybe yes is like the correct answer and it ends the game we can say um you talk to the stranger and they give you gold whatever you win exclamation point uh otherwise no we could say print um you ignore the stranger if I could spell stranger correctly and they are offended and you lose okay so again I'm just like randomly coming up with this stuff I'm sure you guys are laughing at the the options that I'm I'm going with here but I'm just trying to show you the structure of this program and kind of how like the nest thing works that you can make this as advanced as you want so now we've kind of implemented something for the right so it ask you a question uh obviously you lose if you go back uh if you go to decide to cross then you asked another question you cross the bridge meet a stranger do you talk to them if the answer's yes you Lo or you win if the answer's no you lose if you answer something that's not one of those then uh what do you call it uh you lose and then of course if you wanted to keep going from here rather than telling them they lose or they win you would just ask them another question and you would keep doing this and keep nesting this if and else and you can make multiple options too you don't have to just do two options you can make it so they could give you three options you can make it so that you store one of their options in a variable like name right and then you use that variable later on like maybe they picked up a I don't know like a weapon or something really early and if the weapon they chose really early is not correct when they go down a certain path then maybe they lose whereas if it was correct then maybe they can continue on or something like that and so lastly I'm going to say print thank you for trying comma and then this is going to be their name okay so let's run this and I'll just go through a few of the paths but that's pretty much going to wrap up this game there's not really much more to to show you uh this just a cool one and I always find this fun and obviously you guys can come up with better stories than I can so type your name and say Tim welcome Tim to this adventure you're on a dirt road it's come to an end you can go left or right I'm going to go right okay you come to a bridge it looks wobbly do you want to cross or head back I'm going to cross you cross the bridge and meet a stranger do you talk to them no says you ignore the stranger and they're offended and you lose thank you for trying Tim right there you go and we could try this again type your name Tim uh you're on dirt road let's go left right you come to River let's walk and it says you walked for many miles right under water and you lost the game I'm not going to go through all the options I think you guys get the idea now that is the Choose Your Own Adventure game again this code will be linked in the description if you want to download it but this is kind of the template use the if L if and lse structure and you know make this as advanced and complex as you want now let's move on to the last project which is the password manager all right so now we're moving on to the last project which is a password manager now the point of this program is to kind of organize and store your passwords so we're going to store all of the passwords along with the username or the account they're associated with in a text file but we are not going to store the passwords in plain text we're going to encrypt the passwords now even though we're encrypting these passwords which means they're going to need a kind of password to be able to decrypt them so like there's like a master password for all of the passwords this is not a secure way of storing your passwords do not rely on this for anything other than like a fun python project and I personally would not recommend storing at least any of your very sensitive password uh in this method it's just like a cool thing and I wanted to show you how to do it and it's kind of a more advanced project out of the five that we've done so the first thing I'm going to do here is I'm going to going to write the code that's allowing us to actually ask the user whether they want to list out their passwords or whether they want to add a new one and we're going to store all of these in a text file so I'll do this project first without encrypting any of the passwords and then we'll go and and encrypt them so the first thing that we need to do is ask the user for like a master password so we're going to say uh PWD is equal to input and we'll say what is the master password question mark now we're not actually going to validate this password is equal to something we're going to use this password to encrypt our uh our passwords so if they type in the wrong password here it's still going to work like the program will operate but it won't show them the correct password and you'll see how that means when we kind of get later into the uh into the video uh regardless what I'm going to do now is ask them what mode they want to go in so whether they want to add a new password or whether they want to view their passwords so I'm going to say um mode is equal to input and we'll say would you like to add a new password or view existing ones question mark and then the uh two inputs I'll allow will be I guess View and add okay so that's what I'm expecting them to type in now what I'm going to say is if mode is equal to view we will do something uh otherwise L if mode is is equal to what I say add we will do something else otherwise else will say print in valid mode and I'm going to take all of this and I'm going to put this inside of a wup so I'm going to say while true because we'll allow them to like add a password then view them and like so on and so forth and so in this l here I'll just say invalid mode and I'll say continue and what this will do will bring them to the top of the wall Loop and then I'm also going to add something here that says uh press Q to quit and then I'm going to convert all of this to lower and then I'm going to check at the very top here I'm going to say if mode equals equals Q then break the wall Loop okay sweet and then we could make this an LF but we don't have to make it an L if since we have a break here uh if this is true it just won't even bother checking these so up to you but I'm not going to add the uh the LF okay so now that we have this what I'm going to do is show you something called a function so I'm going to create two functions here I'm going to say Define uh View and I'm going to say pass and then I'm going to say Define and this is going to be add okay so what a function is is an executable reusable block of code so the way you call a function is you write the name of it which is this okay and then two parentheses so the basic syntax is you write defa to define a new function space name of the function open and closing parentheses and then any parameters that you want inside of here I'm not going to really talk about what that is because I'm not trying to teach functions here I'm just trying to show you how we can kind of split our code into different sections and anyways the way you call a function is by its name and then the open in closing parentheses so if I put say like print Tim inside of here then I could call this function a bunch of times and every single time I called this function it would do whatever is inside of here which would print Tim so if I had you know print Tim twice every single time I call the function it's going to print out Tim two times whatever's indented inside of here just happens when you call the function pretty straightforward but the point of me creating these two functions is that rather than writing all of the code related to The View mode and the ad mode in the while loop I'm going to put them in this function so it's a little bit more organized and easier for me to kind of separate my program so I'm just going to have pass inside of here right now now pass is a keyword that literally does nothing it is just there to make it so you don't get any like indentation error because you need to have something indented after the and so for now we're just going to write pass and you can see we've done that here too so now instead of just using pass I'm going to call the view function I'm going to call the ad function so now depending on what mode you select it's going to call these two functions which will then perform the operations for that mode it's just a cleaner way to write the code it makes it a little bit more organized okay so let's start with the uh the ad function what I want to do is create a new file if the file storing our password is doesn't doesn't already exist and add the password into it so the first thing I need to do is get the user account or whatever the username and then the password and then I want to add it into the file so I'm going to say uh I guess name is equal to input and we'll say account name like that and then we'll say PWD which stands for password is equal to and actually sorry this should just say password because we already have PWD up here and in fact let's call this master PWD and then we can call this PWD so PWD is equal to input and we'll say password colon like that so now they're inputting their account name and their password now what I want to do is open a file or create a file if it doesn't already exist and add this password in so I'll explain what this is doing in a second but I'm going to say with open the name of my file which in this case is going to be uh passwords do txt we're going to just use a text file for now then we're going to say comma and then we need to define the mode to open this file with now the mode we're going to use is a which stands for append we're going to say as F and now I'll explain what I just did so when you use this wi thing right here this allows you to then do some things indented after it and the point of this width when you're opening a file specifically is that as soon as you are done doing all of the operations with the file since we use this width it will automatically close the file for us so you can open a file like this you can say file equals open and there you go now you have file but the thing is if you do this you need to make sure you manually close the file after you open it because if you don't do that your python process will still be kind of like holding on to and using this file and it's going to cause problems if you try to open this file somewhere else and so it's just better and safer to kind of use this with keyword because now you don't have to manually close it it will automatically close the file for you so anyways I'm going to say with open password.txt in a mode now so this is the name of the file the next thing is the mode to open the file in now there's a bunch of different modes the main ones are w r and a now w means write and what this will do is create a new file or override this file if it already exists very important you understand this if password.txt already exists and you open in W mode it will clear that file and make an entirely new one so only use W mode if you want to always override a file that potentially already exists okay then there's R mode this is just simply read mode you can't write anything into the file if you open it and read mode all you can do is just read the file that's our mode and obviously this is not going to destroy a file if it already exists in fact there'll be a problem if you try to open the file and it doesn't exist in R mode then you have a mode this is a pend mode this is probably the most flexible mode what this allows you to do is add something to the end of an existing file and create a new file if that file does not exist so if password.txt does not exist a new file will be created called password.txt and then we can write to the file if password.txt already exists we are able to write to the file and read the file from the very end uh so sorry we can write to the file from the very end and we can just read the entire file when we open it in a mode and so for adding something we're going to open an AE because if it exists we append to the end if it doesn't we create it awesome so now what we're going to do is say f. write that's the name of our file because we said as F and then we are going to write in the name plus the pipe plus PWD so what this is going to do is take the name it's going to separate uh the password with the pipe oper Ator and then it's going to put the password and then we will have user and password inside of the file so let's actually try this out let me run this you can see it says what is the master password I just type whatever for now just type hello and would you like to add a new password or view existing ones view comma add press Q to quit Okay I'm going to type add and this says account name let's just go Tim password let's go isore great okay so now I'm just going to quit notice this password.txt file has been created if I open it I now have Tim and is great and if I were to do this again it would add the next line in so actually let me rerun this let me say add account name uh Joe password is Billy and then notice it gets added in here the thing is though it got added on the same line and I don't want this to be added in the same line and so what I'm going to do is I'm going to quit here and I'm going to make it so that I go to the next line after I add each password and the way I do that is I add what's known as a line break uh I think this is actually called the carriage return maybe a line break at the end of the line so every single time I add a line I tack on this little invisible character back sln this won't actually appear on the line you won't see this on the line uh but we will add that on and what that tells the text editor to do is to go to the next line so now the next time we write something in it will be on the next line so if I look at this um and and we run this now add Tim a and 5432 and now if you look here it goes to the next line okay so hopefully that makes sense but uh there you go I'm just going to delete everything in that file I'm going to quit this and now we are able to add uh passwords and usernames into the file what I'm going to do now is make it so that we can view all of the passwords so to view all of the passwords I need to again open this file so I'm going to copy this I'm going to say with open and then this is going to be password. txta as F I'm going to change this from a to be R because I don't want to potentially create a new file or anything like that I just want to read the existing file and then what I'm going to do is I'm going to Loop through the lines of the file and just print them out so I'm going to say four line in F I'm going to say read and actually read lines is what I want to do now what read lines is going to do is just exactly what it says it's going to take the file sorry this should be F it's going to read all of the lines for it and then what I can do is use a for Loop to get all of the lines of the file so let's just look at this I'm going to say print line and let's just see what happens now if we go to to view mode and then I'll kind of walk through this more so let's run uh master password doesn't matter let's say View and then oh there's nothing in the file so it didn't show us anything okay so let's go add uh account name let's go Tim password test and now let's say View and then notice it shows us Tim and test but it's printing a new line after it shows us this account name and this password and so I'm going to show you how we can kind of fix this now so the thing is remember how I told you we're adding this kind of invisible back sln the carriage return now when we read the file we actually read in that carriage return and so we need to strip this carriage return from our line and the way we do that is we use this thing called R strip now what R strip will do is it will strip off the carriage return from our line so that's all you have to know just our strip that's what it will do there's also something called strip and strip will strip off the carriage return as well but R strip is like more specifically exactly for this so what I'm going to do now is run the file or run the program master password doesn't matter I'm going to say View and now notice that is not printing that new line after we print this line uh because we stripped off the character return great so now the thing is though I'm printing Tim pipe test I kind of want to figure out or separate the username from the password so how are we going to do that well I'm going to say that my data is equal to line. rstrip and then I'm actually going to split lit this data so I'm going to say my user and pass is equal to and sorry this should be pass W is equal to data dosit at and this is going to be a pipe operator now this might seem really confusing uh because again this is a beginner project I know a lot of you guys haven't seen this syntax before what split will do is it will take a string it will look for this character right here and it will split the string into a bunch of different items uh every single time one of these characters is found so if you had like hello pipe Tim pipe yes Pipe 2 whatever what would happen is this uh data dos spit would actually return to you the following it would return to you a list that says hello Tim yes and two so it remove all of these pipe characters and it would give you all of the unique strings that are between these pipe characters in a list format and so to access these different elements you would use index zero 1 2 3 so on and so forth now the thing is we know we're only ever going to have one pipe operator right unless the uh the password or the username contains a pipe operator we're just going to assume that it doesn't contain a pipe Operator just to make our life a little bit easier if it did contain a pipe operator there'd be some more steps we have to do I'm not going to do them for right now anyways we know we're only going to have one pipe operator which means the list that's going to be returned to us will only have two elements in it in fact it will always have two elements in it so what that means is that we can actually just grab both of those two elements by saying user comma pass W so when you do something like user comma pass W this assigns the first element in the list to user and the second element in the list to pass W and since we know our list always has two elements that means we can do this right whereas if we had three elements we would then have to add another variable right and then X would be assigned to X hopefully that makes sense but that's why we can do what we're doing and that's kind of what the split operator does so now what I'm going to do is I'm going to print out user colon comma user and then password Cola comma password or passw right so now it'll look a little bit nicer so let's go ahead and try this I'm going to quit this program I'm going to rerun it it's going to say what is the master password say test I'm going to view so now when I view it says user Tim password test and I think I should do like a separator between the user and the password and so what I'm going to do is just add a comma like that okay so now if we run this let's quit let's rerun master password test would you like to add a new password I'm going to say view it says user Tim comma password test and there you go and we could actually even split this up with a pipe operator I think that will look cleaner I'm not going to run it now but we'll do with the pipe sweet so now we're able to add passwords and we're able to view them but the problem is I can just look at this file and I can see what the password is and well that's not very good we don't really want to do that so we need to encrypt these passwords all right so how do we encrypt a password well this is where gets a little bit more difficult that's why I've kind of waited until this point to do the encryption so you guys could at least follow along with this part see how to write to files read from files all that kind of stuff there uh so the way that you encrypt a password we could write a manual encryption algorithm but I'm not going to do that that's a bit beyond the scope of this tutorial is we use a module by someone way smarter than all of us who knows how to do encryption and the way that we use this module is we need to install it so remember at the beginning of the video I was telling you when we imported random that hey we there's also other modules that are built by random people right uh that we can use but the thing is we have to install them because they're not by defa installed with python so this is where a lot of you are probably going to have problems if you haven't done this before but open up your terminal or your command prompt depending on your operating system doesn't matter which one and just type pip install and then type cryptography if I can spell it like that pip install cryptography just press enter and pray that this works now if this doesn't work for you don't worry I'm going to show you how to fix this uh but for some of you that should have worked if that works for you you're good you can kind of skip probably the next minute of this video because I'm just going to explain how to fix this if this doesn't work for you try the following command Okay pip three install cryptography pip 3 install cryptography press enter see if that works if that doesn't work for you try python hyphen M pip install cryptography if that doesn't work for you try Python 3 hyphen M pip install cryptography if none of those work for you this means that pip is not installed on your system pip is uh actually a recursive acronym that stands for pip installs packages and well what it does is it installs packages for you and by default when you install python it's not included in the installation I don't know why they don't just include it by default you have to like check a little box to say to install it so you could just reinstall Python and check that box that says uh fix pip or you can follow the two videos that I have that are linked in the description one for Mac one for Windows showing you how to fix this command now they're not directly called like how to fix pip they show you how to install a module called pygame but when it comes to installing the pame thing just instead of doing pame do uh do cryptography okay so you need to install this cryptography cryptography module sorry once you have that installed we're good to go if you know what a python interpreter is and you have multiple on your system this is going to be a bit more complicated you need to make sure you're using the right python interpreter when you're running your code the one that you install cryptography into okay so at this point in time I'm going to assume you've successfully installed cryptography uh once you've done that what you need to do is import it so you're going to say from and then cryptography like that dot and you're going to uh type this thing called furnit uh yeah furnit like that and then you're going to import F now I'm looking at a cheat sheet I have because this is not something I do very often so I don't have this memorized uh but this is a module that is going to allow you to encrypt text essentially now the first thing that we need to do when we use this is we need to Define what's known as a key so essentially what this is going to do for you and I'm not going to talk about it too much is it is going to um take a string of text and using a key turn it into a completely kind of random string of text that you cannot get back to the original text from without knowing the key now this key is something that we're going to combine with our master password so imagine you have this key okay and then we have our password so the key plus this password is what we're going to use to encrypt our text now that means that if you type in the wrong password when you go to decrypt the text what's going to happen is you're going to get something that makes no sense it's not going to be the original text because you need the key plus the password to be able to get back to the original text so it's kind of key plus password plus you know text to encrypt and then that equals like random text okay and then you have random text plus key plus password equals and then text to encrypt now this is obviously like a vast simplification of what's going on here uh but that's kind of what we're going to do with this module so the master password in combination with the key that we're going to store will be able to encrypt and decrypt our text if you type in the wrong master password you will have a wrong decrypted text okay so what we need to do is write two functions one function that can create a key for us and one function that can store a key so I'm or sorry retrieve a key so I'm going to say Define wror key and I'm just copying this from my sheet over here that I have on my other monitor I'm going to say key is equal to fernet Dot and then generatore key I'm then going to say with open and I'm going to say key. key this is a key file uh and then WB this stands for write bytes mode as key file and then I'm going to say key file. write key okay so what this is doing is going to open a file it's going to create this file called key. key in WB mode which means write in bytes you don't really have to know what that means it's just a special file format and then you press as key file and or sorry as key file and then key file. WR and you're going to write in this key that was generated by this thing called fnet okay that's what we're using up here that we've imported so you're going to write or sorry you're going to run this function one time and when you run this function one time it's going to create this key file for you so let me show you when I just call right key here uh after I input the master password it will then create this so let's run this and just type some random thing and then notice here we get this key file okay and inside of here you have this key boom good now remove the call the right key you can keep this function in if you want but you don't need it anymore because you already have the key uh and so what I'm going to do is I'm going to comment it out so to do a multi-line comment in Python you use three uh quotation marks single or double just make sure they the same on both side uh you do three at the start of the comment three at the end and so now I've commented out this function to make sure I don't use it again because if I use it again uh it's going to be a problem okay now that we've done that we need a function to load this key so in a similar way actually I'm just going to copy this I'm going to change this now to be load key like that and actually I probably shouldn't have copied that I'm just going to say return open and then this is going to be key dokey and then do read and the mode is going to be RB mode now the thing is I need to take this here I need to say file is equal to open I'm then going to say file. read I'm going to store this in uh key and then I'm going to say file. close just to remind you that you got to close your file every time you open it okay so I'm opening the file in WR or sorry read/ bytes mode so it's reading I'm then going to read the file I'm then closing the file and then I'm returning the key again you don't really have to understand exactly how this is working this is just part of the decryption stuff okay so now we have the key so now that we have the key what we're going to do at the top of our program here is we're going to load it we're going to say key is equal to load uncore key which means this function needs to go above where I'm calling so this is another interesting thing let me copy this right key as well and put it up here whenever you want to use a function it needs to be defined before you use it so I couldn't have this function defined below this line if I did that that would mean that uh I wouldn't be able to use this function because it wasn't yet created when I tried to use it so I got to create it first then I can use it obviously okay so now that we have that what I'm going to say is uh fur is equal to fernet I'm going to pass key now this is just initializing this kind of encryption module so you're writing fernet you're going to pass it the key okay so actually I'm realizing I made a mistake here I just got to take this stuff and I got to put this below the master password so I'm going to say uh master password then key equals load key fur equals fet key but then I'm going to change my key to be key is equal to load key plus the master password two bytes now you probably don't know what this means uh bytes is kind of a different way of storing information you've probably heard of bits and btes before not the snack but like in terms of uh in terms of computing right you have bit and then you have bytes and well regardless we have our key in bytes and so we need to convert our master password into bytes so that uh this works that we can add this together now just like when you add two strings together that's exactly what's happening here we're taking the key which is in this file and we're just adding uh this master password in its bytes format to this key and then using that as the actual key okay hopefully that's clear that's like a lot of the hard stuff now encrypting stuff is really easy so what I'm going to do now is when I go ahead and write my password I'm going to first convert this password into its encrypted version so I'm going to say uh F Dot and then encrypt and I'm just going to surround my password with that but first I need to encode my password now the reason I need to encode this is because encoding my password will convert this into bytes and actually I'm realizing here that this is going to be better I'm going to say master password. encode rather than bytes again all encode does is it takes your string turns it into bytes and so same thing here I'm taking my password I'm turning it into bytes with Dot and code and then I'm encrypting it and I'm going to store that uh beside the name and I also realize that now I need to convert this to a string so I'm going to say string fur. encrypt PWD do incode and this will now uh encrypt and encode our password okay so now when we store these passwords they should be stored in an encrypted format so now the thing is we need to decrypt them when we show them so to do that is going to be literally the exact same thing we just had here so I'm going to copy this except instead of encrypt it's going to be decrypt okay so we're going to say decrypt like that and then instead of PWD this is going to be uh pass W okay so I'm hoping this is going to work I have a feeling it's not I think I made a small mistake here but we'll we'll worry about that when we get to it okay so now we should hopefully be storing encrypted information and reading non-encrypted information so let me go in passwords and let me delete this because that is not encrypted and so that's going to give us a problem right now and let's go here and let me rerun this app okay what is the master password we now need to pick the master password that we want to use to encrypt our data so I'm just going to make mine Tim make your whatever you want would you like to add a new password yes want to add account name we're going to say maybe just like Facebook password we'll say Tim is great okay would you like to add new password or view an existing one I'm going to say View and then we get a problem it says invalid token okay so let me have a look here and see what's wrong but if we go to password.txt you can see that we are storing this in the file and now I've actually already determined what's wrong but uh let me just collect my thoughts and I'll be right back so I've realized the problem here and it is that we are writing in this B uh what is it I guess this is a quotation mark and then another quotation mark here and we can't be doing that so I'm actually going to clear this file so the the thing here in Python and this is I guess I can teach you about byes now when you write a b and then you have uh something after this like I say B and then hello this is a b string this is different than the string hello when you have this little b before this means btes so the thing is we were writing in this little b and we don't want to do that because when we do that that means when we try to decrypt this it's all wrong because we have this B and this quotation mark and well just incorrect we can't be writing that into the file and so what I did before is you saw I had a string surrounding this in our ad file we can't have that instead of having a string we need to decode this so I forgot that we have this thing called decode it's the opposite of incode it's going to take bytes string and decode it to a regular string so now if we decode this all should be good and same thing here I had a what do you call it string like that and that's no good I couldn't do that instead I just have to have fur. decrypt and then pass w. and code so I'm going to take the string in because I'm writing in a string that's not bytes it's just a string and then what I'm going to do is convert that string into bytes and then decode that by string and then that should work so now let's see if this work works I'm going to rerun the program apologize about that mistake I'm going to say what is master password we're going to go Tim would you like to add I'm going to say add account name let's just go Joe password 1 2 3 4 5 6 7 okay now I'm going to say view when I say view it gives me uh user Joe password B and then 1 2 3 4 5 6 7 so it's showing me this bytes thing if I want to remove this bytes thing I need to decode this so I'm going to decode like that and now if I quit here and I rerun and I type in the master password which is him and I press view or type view uh non- type object has no attribute decode um hm okay what is the problem here I was printing out this oh sorry guys I added the dcode at the end of the print statement not at the end of this fur thing so I had it like after this bracket it needs to be after this second closing bracket so let me rerun this let me type in Tim let me type in View and now notice it gives me the correct password 1 2 3 4 5 6 7 however if I I go to password.txt you can't see the correct password right it's storing this like random string of gibberish that really like means absolutely nothing and so if I actually quit this let me just clear the screen and rerun uh let's go to password manager let's go to run and I type in the incorrect password I'll just type Tim 2 and I type view notice it still gives me the correct password okay it's interesting that that's giving me the correct password shouldn't be giving me the correct password so let me look at this for a second okay so I'm going to apologize here because I've made a mistake I thought that we were going to be able to use a master password in combination with our key and just do some kind of like hackish manipulation to get this to work unfortunately it looks like doing that's way more complicated than I thought I just was looking on the internet right now in fact I'll bring up the documentation that I found um so we're using this thing called feret right and there's a way to use passwords with feret but I mean you guys can kind of read this here it's a little bit complicated and I don't really want to put you guys through all of this because this is just a beginner project so I will leave a link to this documentation in the description if you'd like to have a look at how to do this but for now I think I'm going to end the video here so I'm just going to remove this master password feature obviously that's pretty important right like you would want to have a master password so I really do apologize about that but if you do this now and you just use the key as you used it before um everything will still work so right now if you run the program and and I'll show you and we don't have a master pass says would you like to add a password to view I type view it gives me the correct passwords right even though we use technically a different key that had the addition of our master password to kind of encrypt them previously this still works so anyways that is where I'm going to leave it again I'll leave a link to that documentation that shows you how to implement the master password in the description just too complicated for me to feel comfortable going through it in this kind of beginner tutorial so we want to build Pig now first we need to understand what this project is so how does pig work well it is a multiplayer game first of all everyone plays a little bit different but the way that I play is that you essentially get a turn so it comes your turn and you get to roll to die when you're will to die you're going to get some number from 1 to six if you get anything other than one you take that and you add that to the score of your turn so let's say you get a five now you're at five roll it again you get another five you're at 10 and you can decide how many times you want to roll the dice now the catch is as soon as you hit a one whatever you got on your roll is going to be done whatever you got on your turn is is zero like you completely remove the score so you can roll five times three times four times 10 times 20 times as much as you want but every additional roll you're gambling the possibility of Los losing your score so you need to decide when you want to stop as soon as you stop whatever your current score is assuming it's not zero is going to get added to your total score and then you can determine the number of total roles you want to have or it's whoever reaches like 100 first or 50 first whatever you want to do and our case we'll say like the max score is something like 50 whoever hits 50 First is just the winner of the game okay so how we going to build this up well let's break down the individual things that we need to do first we need to allow the user to roll the dice this means we need to come up with a way to roll so we have to have some random number generator giving us a number between one and six we then need to ask the user if they want to continue to roll so either roll again or stop their turn if they stop their turn we need to take whatever their score is and add that to some total score then we need to constantly check if either player has a score that is above 50 if it is above 50 then we need to end the game and tell someone that they want there's a few other things that are involved but those are the basic steps let's start by generating a random number so what I'm going to do is import the random uh module now random allows you to Generate random numbers what I'm going to do is just Define a rule function now a function in Python is a reusable block of code you make it using defa standing for Define you then put the name of the function and then a set of parenthesis we're then going to put it inside of here uh in an indented block after a colon so notice I'm kind of one tab over any code we want to run whenever we call the function so what I'll do here is I'll say Min or Min value is equal to one max value is equal to six and then I'm going to roll the die in between them now there's a few different ways to do this with the random module but I believe we can say roll is equal to and then this is going to be random. Rand and then int like that and then this is going to be the Min value and the maximum value of our die then we're simply going to return roll now the way the return keyword works is it's going to give whoever called the function this value kind of back it's going to return it to them so if I come down here and I say value is equal to roll the way I call the function is I use my set of parentheses and then I can simply print out the value here and you'll see that if I bring my terminal up and we run the code we get the value three we can run it again we're getting 6 3 6 5 5 five 2 let's see if we can get a one okay it looks like it really doesn't want to give us a one this would have been a fantastic turn okay and there you go we got a one so that would have ended our turn all right there you go that is how we generate a random roll okay so now that we have that we want to kind of set up the game and we might Begin by asking how many players are going to be participating and then we can keep track of all the different players maybe we set it to say a maximum of four or something like that so let's go down here I'm just going to zoom out a little bit and let's set up a wall Loop while we say actually not wall loop we're going to say input so we'll say players is equal to input and we're going to say enter the number of players and we'll say kind of one to four like that and then notice I'm putting a space here at the end just so we have a little bit of padding between where the user is going to give us the answer so the idea is we're going to ask the user okay give us some value between 1 to four then what we need to do is we need to check if this is a valid number so I'm actually going to kind of put a while loop here and I'm going to say while true and then I'm going to put this inside the reason for this is I want to continue to ask the user to input a number until they give me one that's valid so I say while true and then I'm going to break out if they give me a valid number so I'm going to say try or actually we can do the following we can say if players Dot is digit now is digit is going to tell us if this is a digit or not so if it's a number if it's a valid whole number specifically is what it will give us so I'm going to say if players is digit I'm going to say players is equal to int and then players now what this does is convert what's going to be a string here into an integer and the reason I need to check if it's a number first is because if I try to convert a string into an integer and it's not a valid integer it's going to give me an error so I don't want to crash the program so I'm saying okay if this is actually a valid number let's convert convert it into that number the reason I need to do that is I now need to check if this number is greater than one and less than four if it is I can then break out of this wall Loop because I have a valid number of players otherwise I need to continue to keep asking them to enter a valid player so I'm going to say if 1 less than or equal to players less than or equal to four okay then I will simply break what the break keyword will do is immediately exit outside of this wall Loop meaning we'll have access to the players variable down here and we can just print out what the number of players is if we don't encounter this break keyword we will continue to ask the user until they give us a valid number of players now we could give them some output and say something like print invalid try again and we could do something here where we say something like print must be between one to four players and actually it can be one has to be two right so we'll have two to four like that and we'll put a two and we'll put a two because we need to have at least two players to be able to play the game all right so let's try this out let's run our code enter the number of players let's enter one says we need to do it again okay so it didn't actually print anything out um I don't know why that happened oh sorry it's cuz Okay I'll fix that in one second that's an error anyways we enter two it says must be between two to four players which is a mistake and then two so notice I made a bit of an error CU I put this inside of the if statement when I wanted to put an else statement here and then put this here because if this is valid we break which means we a to the wall Loop otherwise we tell them okay that was the error so we just need to make that quick fix there with the if statement okay in case you're confused by the way if statement checks if something is true if it is we kind of enter in this indented block which happens after the colon otherwise we have this else statement which will trigger if the uh if statement is false okay so I'm going to clear and run and let's go one okay must be between two and four let's go five let's go hello let's go three and we're good to go okay so now we have the number of players and what we want to do is essentially simulate each player turn where we ask them you know do you want to roll the dice yes or no they tell us yes or no they roll and then we start kind of calculating their score so let's do this first of all let's make some variables here and let's say our Max score is equal to and then we can do something like we'll go with maybe yeah let's go with 50 for now we'd probably want to make that larger but just kind of for the sake of time when we're testing this we'll make it small then we want to have our player undor scores and what we'll do for our player scores is we'll just have a list which contains all of the individual scores now we don't know if we're going to have two players three players or four players so we're going to have this list kind of change size based on the number of players that we have now the way that we can kind of create or initialize this list based on the number of players is we can say 0 4ore in and then something like this in range the Len of players now what this is is actually a uh list comprehension I was thinking of the name there what this does is it essentially puts a zero inside of the list for every single player that we have so what I'm doing is saying for underscore now I could put I here but the thing is I don't actually care about what the variable is I just want to do this the number of player times so I can put an underscore essentially saying hey I don't really care what the variable is so like you know we need to have something there but I'm just going to put an underscore because I don't really want to use this and then I'm going to say in range the line of players so what this range function will do is Loop the number of players or the length of actually sorry we don't need Len just players here it will Loop the number of players times that we have notice that our players is going to be in int right so if it's three this will happen three times if it's four it will happen four times Etc I ignore the Len that I had there I don't know why I put that there just a silly mistake okay so now we can print out our player scores and you'll see that we'll get an array filled with zeros based on the number of players that we have so if we do three gives us three zeros if we run it again four we get four zeros so now we are able to store each of our players scores inside of this array fantastic okay now we need to go through our player turns so we're essentially going to say while the maximum of our player scores is less than the max score then we'll keep looping now what Max will do is give us the maximum value from this array or from this list so if it's 23 gives us 23 if it's 55 gives us that we're saying okay as long as it's less than the maximum score it means no one's reached the max we'll keep going as soon as someone does reach the maximum score we need to stop and then tell uh the user whatever the um sorry tell the players whoever kind of won the game all right how we going to do this uh well let's go here and we will say first of all R we'll say should uncore roll is equal to input and we'll say would you like to roll question mark and we're just going to put here A Y which means we want the user to input the key y so then we can come here we can say if should roll lower is equal to Y the reason I'm converting this to lowercase which is what lower does is because if they enter a capital Y I still want them to roll right so this is just checking is it capital or lowercase doesn't matter we're going to convert it to lowercase and then check if it's equal to the lowercase y if it is then we're going to roll the dice for them so we're going to say roll is equal to and actually I can't use roll because that's the name of my function so I'm going to say value is equal to roll okay otherwise I'm simply going to break and actually a better way to do this that's going to be a little bit cleaner for me is I'm going to say if should roll. lower does not equal y then I will break out otherwise I will say my value is equal to the ru so the reason I'm doing this is because I want to have all my code kind of not indented if I don't have to have it indented so I'm saying okay if you didn't hit Y that means we're just going to stop your turn otherwise we're going to roll the dice now there's a lot more code we're going to need to to write but I'm just kind of going through this um you know as I normally would and then we'll kind of stop and fix things as we need to so we're going to grab that rule and we're going to check if that rule is equal to one if it is equal to one then whatever the player's current score is is just going to become zero and we're going to move to the next person's turn now we still need to simulate the turns and all of that which we'll do in a minute uh but for now just kind of bear with me so we're going to say if value is equal to zero then we can simply say print or sorry not zero we're going to say you roll the one turn done exclamation point otherwise we'll print you rolled a and then whatever the rule is so we can say something like actually value like that okay so let's put a call in you rolled uh and then whatever the value is all right so now that we have this and we're kind of printing out what they rolled I'm I'm just going to go up here and I'm going to Mark the current score equal to zero because we need something to keep track of what the player's score is now if they didn't roll a one then what I'm going to do is I'm going to say the current score plus equals whatever the value of the die was I'm going to tell them what they rolled and then down here I'm just going to print your current or your score is and then we'll print out whatever the current score is and then we'll kind of continue men now here I'm just going to break this because the idea is all right well if you roll a one your turn's done so we're going to break out all right so this kind of simulates one's per one person's turn story but again we haven't really kind of handled uh the fact that we have multiple people going at once and allowing someone's turn to continue multiple times so what we actually need to do is we need to use a for Loop here what we'll do is we'll put a for Loop kind of right here and we'll say four I in range players so I is going to represent the current player so we'll say player uncore index or player idx so player 0 1 2 3 or Player 1 2 3 4 whatever you want to call it and in this for Loop we'll then simulate one person's entire turn so we'll mark the current score but then all of the stuff that's going on here needs to happen until the player stops their turn so what we'll do is we'll have a wall Loop and we'll say while true and then we'll put all of this here then outside of the wall loop we're going to say that the player undor scores at index player idx is going to be plus equal to whatever their current score is so like the current score is kind of the score per turn and then the total score is what we're going to be adding to after they finish their turn so what we'll do after we add that is we'll say print your total score is colon and then we will say that this is going to be the player scores at the player idx okay we'll go through this again in one second but for now I we're making a good progress on the terms all right so I'm just reading through this uh it's looking okay however I'm realizing that if the value is one then we're going to have to set the current score equal to zero just so that we make sure we don't add what their score was before they rolled a one all right so let's kind of run through this here we have our for Loop we say four plus player index in range players which means We're looping over all of our different players so they each get a turn we probably want to print out something like player and then let's say player idx + one turn has just started just so they know that it's now their turn and what I'm going to do is print a back sln right here and a back sln what this is going to do is just add a line break so that we have a bit of separation when the player's turn starts so we say okay player and then we're doing plus one because this is going to be 0 1 2 3 well we probably want to show 1 2 3 4 so that's what we're showing so we say player whatever it is turn has just started we could say player number turn has just started okay we said the current score equal to zero for the turn we simulate the turn we ask them if they' like to roll if they say yes or if they don't say yes sorry we break out otherwise we roll if they get a one we say they rolled a one their turn is done their current score is zero we break out otherwise wi we take whatever the current score is and we add to that the value that they ruled because it wasn't a one and then we continue this whole process again so we tell them this is what you rolled and then we say your current score is this which is going to be the sum of what they rolled plus you know what their current score is okay then eventually we're going to get outside of this wall Loop when they roll one or when they tell us that they don't want to roll anymore we're going to take that score add that to their total score and then print that out now we're not quite finished but this will simulate most of the game so far all we really need to do is determine when someone wins so let's zoom out a bit just so we can kind of read most of what we have here we have our role function we ask the player or we ask to input the number of players we want we have the maximum score generate kind of an empty list for storing the scores and then we have this code which is going to simulate the terms let's run this and see what we get here okay so let's zoom in a bit and the number of players let's go with two player number one turn has started okay would you like to roll yes you roll a six your score is six would you like to roll yes you rolled a four your score is 10 would you like to roll okay yes let's keep rolling yes yes yes yes I'm trying to get a one here and it says you rolled a one your turn is done your total score is zero player two's turn has started would you like to roll yes five okay let's roll again and we rolled the one all right and you'll see that we can continue this right so I'm going to try to get a pretty high score although this isn't working too well for me okay let's stop there now our total score is 15 player two turn okay yes yes yes yes yes really gambling here okay let's stop the roll okay yes roll to six your score is six yes yes yes yes no okay total score 42 let's roll roll roll roll and no total score is 51 and then notice the program ends here because all of the players turns have finished and someone had a score of 51 so we end we should really be telling them you know know that you won which is what we're going to do now but that kind of simulates the program there's a few things we'd probably want to do to make this a bit better for example at the beginning of the turn we should probably tell them what their score is so that they know that before they go into the turn so they can stop um you know once they hit what the max score is okay so let's do this uh we're going to say player one's turn has just started and then we're going to print here your total score is colon and then the player scores at the player idx okay and then we're going to begin the turn so we can actually just move that back sln and we'll just put one right here just so that we kind of go one line down okay do all of this and then as soon as this ends what that tells us is that at least one player has a score above 50 now multiple players can have a score above 50 and the reason this works is as soon as someone hits 50 we don't end until every player gets a turn the reason why that's fair is cuz whoever goes first would have an advantage so in this case we let everyone have at least that last role and then we see whoever has the max score after the last rule so what we can do now is we can just find what that maximum score is we can actually get the index of that score inside of our player scores and that will tell us which player won so the way we do this is we simply say Max score is equal to the max of our player scores and then we're going to say player winning idx is equal to or actually we can just say winning idx is equal to the player scores do index and we can index the maximum score what that does is give us the index either 0 1 two or three of where that maximum score is which tells us player zero player one player two Etc so then we can just print player comma winning index plus one so we'll say player number and the reason we're adding one is because again we're going to start at zero so we want to make sure we're going from 1 to four not 0 to 3 and we'll say is the winner with a score of colon and then what the maximum score was okay so that should wrap up the game let's give this one last run here okay Enter the number of players let's go with two player number one's turn has just started your total score is zero would you like to roll yes roll to five let's roll again roll again roll again and no okay 16 would you like to roll yes okay that ended fast you like to roll yes yes yes yes no okay and tot score zero would you like to roll yes yes yes yes yes okay yes yes and no okay now it's player two's turn so let's roll yes okay that ended fast yes okay now we have the max score so let's say no player two still gets a turn even though we now have a score of 51 I'm just going to say no and it says player number one is the winner with a score of 51 okay so that completes that first project all of this code will be available from the link in the description by the way in case you want to download this but'll kind of scroll through it quickly so you can get a sense of how we wrote this that was Project one hopefully you found that interesting and useful now let's move on to project number two all right for project number two we're going to do that Mad Libs generator the idea is we'll have some type of story the story will have replaceable words like an adjective or a location or a weather condition whatever ever it may be what we'll then do is we'll ask the user to give us all of the different words we'll then inject them in the story and then read the story back out to the user now the first thing we're going to need for this is a story so the process as I kind of described there is have a story with those injectable words essentially grab what those words are ask the user to input them and then place them in the story now I'm going to show you that there's a lot easier way to do what I'm about to do or I'm going to mention this's a lot easier way to do what I'm going to do but I want to show you a way that we can do it with any story so that means that you can make this program really Dynamic and you could have like 20 stories 50 stories 100 stories or you can just replace them without having to write any additional code the way we're going to do that is by taking the story and placing it inside of a text file that way as long as the story is written in a specific format we can read in the story do the operations we need to and then kind of run the program as we see fit now what I always do whenever I need something like this is I don't write it from scratch because I'm a lazy programmer I go to gbt so what I actually did here is I asked it using this prompt I'm making a Mad Libs generator in Python let's make this full screen I'm going to need a story where the user can give me some words can you give me the story even though I spelled that correctly and for all of the words where the user needs to give them to me make them like this angle bracket word now it gave me a nice long story and it had all the different words and it kind of listed them all out that was a bit long for me so I said that's okay but can you make it in less words please and then it gave me uh kind of a shorter story so the idea here is that whenever we have these angle brackets we're going to kind of treat that as a word that needs to be replaced so what we'll do is we'll take the story from chat gbt so I'm just going to copy this on my clipboard we'll put it in a text file we'll load that story in for all of those individual words we'll then kind of grab them figure out what they are ask the user to give us a word for them and then replace them in the story all right how do we want to do this well the way I will do this is I will copy that first of all and I will go here to vs code and I will make a file called story. txt and I will paste that inside of here now make sure when you do this that you put your story in the same directory where your python file is so here I have project 2py and I have story. txt in the same directory very important that you do that otherwise this isn't going to work for you okay and if you want this story you can go click the link in the description and just download the story from GitHub I'll make it available for you um after okay so how do we do this first thing we need to do is load this in now I want to load this in as a string essentially and then be able to kind of parse through that string and look for all of those different words now there's a few ways to do this but the way I will do this is I will say with open I'm going to open story. txt in read mode as F and then I'm going to put a call in now what I've done here is I've used the open function and the open function allows me to open a file so I can open a text file a Json file really any type of file I want and the mode here which is what I've placed second uh is the way in which we're kind of reading it in so I'm going to read it in in read mode which is R mode if I put W this stands for write mode where we'd actually be creating a new file and overriding a file if it already existed with the same name so we don't want to use W mode we want to use R mode this now allows me to read this story. txt file in and the reason I'm using this with syntax is what this does is provide something known as a context for this file which means I can do any file operations on this variable F inside of this indented block and as soon as I get outside of that indented block python is automatically going to clean up the file for me which means it will close it and make sure everything's good with the file so kind of best practice in terms of opening files here so what I'm going to do is say my story is equal to f. read now when I do do read all this does is give me all of the text inside of the file so I can simply print out story here and you'll see if I run this that I get my story appearing here in my terminal okay so now that we've read that in what I would like to do is look for all of the words in my story now there's a bunch of different ways to do this but essentially what we need to do is find the presence of this angle bracket as soon as we find that we want to find up to this closing bracket right so we want to find every individual word take that word store that in some kind of uh list that we're going to have access to ask the user to give us a word to replace it with and then go and replace all of the instances of this word with whatever the user told us okay so let's do that what we want to do is Loop through our story now our string we can actually access all of the individual characters as an index so what I can do let's zoom in here is say for I comma character in enumerate and we're going to enumerate the story now what enumerate does is give us access to the position as well as the element at that position uh just makes it a little bit cleaner for us here so now I'm just going to check essentially if this is equal to an angle bracket if it is equal to an angle bracket then I kind of need to do something to Mark the fact that I found the start of a word and then I need to go until I find the end of it so we're going to set up a few variables here and we're going to say words is equal to this because we want to store what all of these different words are and then what should we do here we should say start of word is equal to1 okay so we're going to have this variable and this variable is pretty much going to tell us if we've currently found the starting index of a word if we have that means we can then look for the end if we haven't then we're going to wait until we find that starting index so what we'll do here is we'll say if Char is equal to and I'm going to make another variable I'm going to call this target unor start this is going to be equal to the open angle bracket and I'm going to have my Target end equal to the closing angle bracket just so that if we were to change the format of the story we could easily adjust this by changing the value of the variables so I'm going to say if the Char is equal to the Target start then what I'll do is I'll say the start of the word is equal to index I so if I found that opening angle bracket okay we just found the beginning of the word let's mark that by indicating that in our variable now what we'll do is we'll say if the Char is equal to the Target n and and the start of word does not equal -1 the reason why we're doing this is we're saying if we found the ending angle bracket and we had the starting angle bracket right which will be marked by the start of word variable which if it's equal to negative 1 means we haven't yet found the beginning if it's equal to anything else that means we did find the beginning then we can take that entire word and add that to our words list so what we'll do now is we'll say word is equal to and this is going to be story at index start of word up to the index I plus one now what this gives us access to is a slice which is a subsection of the string so this is the slice operator here in Python where we indicate the starting character so the character we want to begin taking a slice from and then the ending character that we're going to go up to but not including or the ending index so in this case we know the start of the word so we put that here and we know the end of the word because that's the current index that we're on that we just found but we need to add one to it to make sure that we include this ending index uh in our word so we're going to grab that we're going to put that inside of our uh word or word variable sorry we're going to say words. append word which means we're going to now add this word into our words list and then we are going to set our start of word equal to Nega one because we've now found one whole word so now we reset the start of word so we're ready to handle it for the next uh character that we find which is that opening angle bracket so this code here will actually find all of the different words for us in the story so let's test this by printing our words okay let's run the code and I think my terminal is a little bit cut off but you can see that we get all of the different words now what you might notice here is that we have duplicated words now the reason we have duplicated words is because this word could appear multiple different times now that's fine if it does but I only want to have the words that are unique now the way that we can essentially do this is we can change from using a list and instead we can use a set now a set is a data structure which will only contain unique elements so if I add the same element in it's not going to do anything we just have one instance of each unique element the way to do that is just to write set here instead of a list and then rather than aend we're just going to say add now add will just add this to the set and you'll see now that when we run this we'll just get all of the different unique words perfect okay now that we have those words what we want to do is ask the user to give us a value for each of the words so the way we'll do this is we'll set up a dictionary so we're going to say answers is equal to a dictionary the idea is we want to have the word as the key so something like name and then the value in our dictionary will be whatever answer they gave us so something like Tim the reason we'll do this is so we can very easy easily look up the value of a word so we say name Tim blah blah blah okay and then what we'll do is we'll take whatever these values are and replace them in our story later on the way the dictionary works is you add a key by doing something like this answer is key is equal to and then whatever the value you want and you can access the key by just using the square bracket syntax like this okay so we have our answers this is going to be an empty dictionary what we'll now do is we'll Loop through all of the unique words that we have and we'll ask the user to give us a value for them so we're going to say forward in words iterating through our set and we're going to say answer is equal to input enter a word for and then we're going to do plus and then whatever the word is now notice we can't do a comma here because we're using the input statement not the print statement so we need to concatenate which means add two strings together so we take the word add it to enter word for and then we can just put here a colon with a space at the end so that the user knows where to start writing okay so that gives us an answer we're then going to say answers at word is equal to answer and let's spell answers correctly okay that will now create a dictionary that has all the words associated with all of the values so let's now print out answers okay so let's come here says enter a word for object uh let's go something like chair weather condition Sunny adverb uh I don't know let's see gently place School emotion to sad animal bear place to um I don't know house terrain what is this grass okay character Tim adjective one jumps emotion happy and there you go it gives us now all of the different words and their answers now that we have that we can take every single instance of these words and essentially kind of replace them in the story so now we're going to have another for Loop and we're going to say forward in words now the great thing in Python is that we have this method called replace all or replace I don't know which one it is I think it's replace all either way what this is going to do is replace every single instance of one string with another so that's super convenient for us cuz we know the string we want to look at which is that kind of angle bracket and we want to replace that with our answer so now what we'll do is we'll simply say story. replace I think this replaces all instances of it we're going to check that in one second and we're going to replace our word which is that angle bracket string with the answers of our word and then we can just print out our story and we'll be good we'll have the entire program finished so let me quickly run through the code and then I'll show you how this works so we open up our story. txt we read this in we create a set of all of our unique words we then say the start of the word is equal to 1 we have our Target uh kind of opening bracket Target closing bracket and this first block of code here goes and locates all of the uh different words that are inside of our story so we say for I character and enumerate story getting the index as well as the value we say if the character is equal to that starting kind of open angle bracket let's mark that by saying the start of word is equal to I then down here if we found the end bracket and we have the start of a word we've just found the end of the word so now what we can do is grab that word using our slice syntax add that to our set and then reset start of word then we have all of our words so we need to generate an answer for them which we ask the user to do and then we simply go through and replace all of the instances of our word with the answer the user gave us awesome let's give this a shot let's make this full screen and run uh animal bear adverb gently character t I probably should do lowercase for but that's fine weather condition Sunny terrain grass Place School adjective one um I don't know throw emotion two sad place two let's go with soccer field emotion happy object chair okay and unfortunately it seems as though this actually didn't work so I'm going to have to look at what the problem was here ah I already know what the issue is so I said story. replace however what this does is this gives me a new string so what I was doing is I was just kind of generating a string that I wasn't storing anywhere so story didn't change this gives me a new string so what I actually need to do here is say story is equal to and then story. replace and then do this now there's more efficient ways to go about doing this but this will be perfectly fine for our purposes so if we fix this up now and let's save that so again just we kind of are now changing the story every time by updating that variable what I'll do is run this again emotion sad adjective throw character Tim Place School terrain grass place to soccer field object chair adverb gently emotion sad animal bear weather condition Sunny okay in the throw land of school oh adjective okay I I probably used the wrong thing for an adjective there anyways in the throw land of school a bear was feeling sad the bear had lost its chair suddenly a Tim appeared I will help you find the chair they said together they journeyed through grass and faced the sunny okay I probably should have said like raining or something finally they found the chair in a soccer field the bear was so sad and thanked the Tim they lived gently Ever After are you know what that's not so bad I think there was a few words that I probably messed up writing but there we go we get the story and yeah there you are now if you wanted to you could store that in a text file but I think that that pretty much wraps up this project that was pretty cool and obviously if you kind of change the story around give some better words you can get some pretty interesting results there regardless hope you guys enjoyed let's move to the next project all right so let's get into project 3 now the idea for project 3 is we want to randomly generate a bunch of different math questions ask the user those questions and then not let them continue until they get it correct well then time how long it takes them to answer all of the questions so the first thing we need to do is be able to randomly generate these problems now there's a bunch of different parameters we can use right we have a set of operators we can use it's like plus minus addition multiplication we could even use exponent and stuff if we wanted to uh and then we have kind of the max values as the operan like the min max value Etc so what I'm going to do is write a few variables that we'll use as constants that we can change that will make this either easier or harder depending on what you want to do now first of all we're going to need random because we're going to be randomly generating operand then we're going to need the operators so I'm actually going to do this in all capitals I'm going to say op operators is equal to this and I'm going to say Min operand and Max operand okay we'll say for the Min maybe we have a Min value of three and for the max go something like 12 for the operators I'm going to use a string and I'm going to put in python operators okay it's important that these are ones that could actually be used in Python because I'm going to show you the way that we'll actually figure out what the answer is this is not going to be that long of a project but it'll show you a cool function that you might not have seen before in Python so what we're going to do is write a function called generate problem okay now what this is going to do is generate a problem for us that uses one of these operators and then a random operand on the left and right side so we're going to say left is equal to random. randint and this is going to be the Min op Rand and the max op Rand we're then going to say write is equal to random. randint and again the Min opend and the max oper now I'm actually going to remove division because I'm realizing that the way I'm going to write this is not going to work too well with division we'd need like a separate set of parameters so for now we'll just use these three operations which I think is fine okay we're then going to randomly select an oper opor so we're going to say operator is equal to random and there's actually this function called Choice what this does is just randomly pick one of the elements from a list so I can say random not Choice operators and that'll just give me randomly one of these then I'm going to say my expression which is uh XPR or exp here is going to be equal to the left plus the right plus the operator however I need my left to be a string and I need my right to be a string okay so this is going to give us the expression which will be the left hand side plus the right hand side and what we'll actually do is we'll just add a space in between here so I can print this out and you can just see kind of what it looks like so let's add a space like that okay so now let's call generate problem and let's just print out the expression and then return it just so we can see what that is okay so clear and python project 3 and I got an error can only concatenate string not into string okay ah sorry that's because I put this in the wrong order so operand or operator sorry plus the right okay so let's fix this and run again and we get 12 + 9 let's run a few more times and you can see we're kind of getting random operands and random values sweet all right that's working now the question becomes okay we randomly generated this but we need to know what the answer is right since we're randomly generating it it becomes a bit more difficult to calculate the answer now what we could do is just use a bunch of if statements right and I can say if the oper end is plus add them together if it's minus subtract them if it's multiplication multiply them that's fine however I want to make this a bit more Dynamic such that we can kind of make this a bit larger and we don't have to do all those if statements now the way to do that so we can actually do this we can say answer is equal to a function called eval now what eval does is evaluate a string as if it was a python expression now notice we have an expression that is valid python code like 6 minus 12 is valid code that we can evaluate so all I have to do is put this expression inside of the evaluation and it actually just tells me what the answer is so now what I can do is I can return my expression and the answer like that and if I go here and say exp answer is equal to that I can print them out so I can print the expression excuse me there sorry but I can print the expression and the answer and it will tell me what it is so I'm just showing you how we can kind of avoid having like if it's this do this otherwise do this that's fine that's valid to to evaluate it that way but we can use this eval function so if I run this I get 7 - 3 that's four right 12 - 4 8 10 + 5 15 so I figured you guys would find this eval function kind of cool hence why I wanted to show it to you all right so that is our generate problem and that's really most of the coding done what we need to do now is determine the total number of problems we then essentially need to set the timer when the user begins and we need to ask them to answer it right so what I'm going to do is say total problems is equal to 10 set this to whatever you want but the idea is I'm putting all of these capital or all capital variables at the top of my program these are constants meaning they're not going to change and we can simply change them around like once we're kind of going to run the program a second third time to make this more challenging easier like we can set the parameters of the program from these variables right up here okay so now that we have that what we'll do to begin is we'll kind of just ask them the number of problems then we'll set up the timer so we're going to say for I in range and then this will be the total problems and then we'll print something like this so we're going to say expression answer is equal to generate problem so that gets us a unique problem we're then going to print problem number and then we'll say plus I + 1 inside a parenthesis and this will need to be a string so what we're doing is we're converting I +1 to a string so so it'll be like problem one problem two problem three so that they know then we're going to say plus a colon now notice the reason I'm using pluses here is because I don't want to have a space between my different values I just want to have them kind of in line so I'm saying problem number one colon space plus and then the expression okay and then we'll put actually I'm realizing we're going to put this inside of an input statement sorry so we're going to switch this around and we're going to say guess is equal to input and then we'll have plus the expression plus a equal sign like that so now what we're doing is we're saying okay problem number one here's the expression so here's the problem equals and then the user can type in their answer and then what we'll do is we'll keep asking them this until they get it correct sweet so then inside of here we'll do a wall Loop we'll say while true we'll do this we'll say if guess is equal to answer then we will break now the thing is our answer is going to be an integer but our guess is going to be a string so we're going to convert our answer into a string so that we can compare the same types because if you compare an INT to a string even if they're the same value like the string 10 the number 10 it's going to say false now I want to convert the answer to a string not the guess to an INT because if I tried to convert the guest to an INT to match the answer type and they had typed in something that wasn't a valid int then that would crash my program which I don't want so this way I'm kind of solving for that I'm going to make sure that I don't have any potential crashes okay so if they get it right break otherwise we're just going to keep asking it to them we don't need to give them any feedback they can just keep attempting the answer okay so that's good and I think that's actually going to be it for all of our problems all right so let's run this now give this a shot now I'm about to embarrass myself I haven't done m in so long so let's hope it gives me some easy ones okay 9 5 5 * 8 40 okay 20 10 8 * 7 I always mess these ones up uh not 6456 okay 88 and there we go we finish the problems all right so that was actually pretty good did I get any wrong no I didn't okay let's try it again let's get one wrong this time and noce is going to keep asking until we get this correct and then we continue okay I'm just going to hit contrl + C to exit out of that and now what we'll do is we'll set up the timer now I would love to make it so the timer like it shows you the timer it's going to be a little bit difficult to do without going into some more advanced code so what we'll do is we'll just start the timer as soon as they say like they're ready to start and then we'll tell them what their time was at the end and we can also tell them like number of correct answers so let's do something like this we'll say wrong is equal to zero and every time they get it wrong so we can just go here and say wrong plus equals 1 and then that way we can tell them kind of what their accuracy was at the end all right so wrong we're also going to import time all right and now before we start doing all of this we just want to ask them like okay are you ready to begin as soon as they hit enter then we start the timer just they have a second to like gather themselves before it begins so I'm going to say input I'm going to say press enter to start okay really they can press anything they want and it's going to continue as long as they go to the next line so they can type something in if they want doesn't matter so press enter to start will print out like this okay and then it will begin and I'm just going to take this and print it once they're done and then we'll print nice work and then whatever else we want to do okay so as soon as we do this so as soon as I hit input we're going to start the time now I imported this time module and what I can do is I can say the start time is equal to time.time now this is going to give me what's known as the unex time yeah I think it's that's what it's called let's see here so actually sir it says return the current time in seconds since the epoch don't worry too much about exactly what that means but it's going to give us some kind of time stamp in seconds so what we do is we kind of Mark the start time then we just need to figure out what time they ended at then we subtract the two times and that to tells us the total amount of time so as soon as they finish the for Loop here we say end time is equal to time.time and then we just say total time is equal to the end time minus the start time and then we can print out how long it took them so we'll do that down here nice work you finished in comma total time and we'll do comma seconds like that now we could parse this and do minutes hours Etc but I think just doing the number of seconds is fine and that will be our program okay let's give this a shot so run the code press enter to start okay so that's 80 that is 17 -2 -6 11 77 fortunately it's giving me some easy ones here 16 -3 uh 36 okay nice work you finished in 16.95 blah blah blah whatever seconds we could probably round this off if we wanted to to make it a little bit better so let's do that and we will take this and round this to the nearest two digits okay let's do this one more time see if we can beat our time of 16 seconds that was pretty fast I don't know if I'm going to be able to do that okay -21 1 oh what am I one okay definitely not going to win Now 49 14 30 -4 uh 12 0 10 21 17 oh I was pretty close even with that mistake I was reading it as 7 - 8 not 8 - 7 hence why I made the mistake three times anyways that was pretty good all right so that completes our program and all of our projects so you're probably wondering now what kind of project are we going to work on now I wanted to pick something that was unique and that I haven't done before so we're actually going to build a text based slot machine now the way this will work is the user will deposit a certain amount of money we're then going to allow them to bet on either one two or three lines of the slot machine just to keep it pretty simple I know in real slot machines they have a lot more lines than that and then we are going to determine if they wanton so if they got any lines we're going to multiply their bet by the value of the line add that to their balance and then allow them to keep playing until they want to cash out or until they run out of money so this is actually a fairly complex project because we need to do a lot of things we need to collect the users's deposit we need to add that to their balance we need to allow them to bet on a line line or on multiple lines we then need to see if they actually got any of those lines we then need to spin the slot machine or we would have done that before right we need to generate the different items that are going to be in the slot machine on the different reels uh and then we need to add whatever they won back to their balance so there's quite a bit of stuff going on here and this should be a challenging enough project to make it interesting for you guys so before we even get into this I just want to mention I obviously am not supporting gambling here this is just kind of a cool thing that we can do we're not using any real money and I think it's a good project so just keep that in mind do not gamble I'm not supporting that by making this video and before I write any code what I like to do here is just think of the different things that we need to do in this project and kind of pick a good starting point the place where I like to start usually is collecting some user input and for this project we need to get the deposit that the user is entering as well as their BET right those are kind of the two things we need before we can start actually using the slot machine uh and generating you know whatever the slot machine spun so to do this I'm I'm going to make a function here called deposit now I'm just inside of Visual Studio code you can work in Ed any editor you want sorry and I have this main.py function open I assume you guys can open your own python file and kind of work in your um preferred environment so this function here is going to be responsible for collecting user input that gets the uh deposit from the user Now function if you're unfamiliar is just something that we can call that's going to execute a certain block of code and then can potentially return us a value and you'll see how this works in a second so what I'm going to do here set up a wall Loop and the reason I need a wall Loop is because I'm going to continually ask the user to enter a deposit amount until they give me a valid amount so if they don't give me a valid amount then they need to keep typing in until eventually we get one so to do this I'm going to say my amount is equal to input and then inside of input I'm going to pass a prompt which is some text that will happen before we allow the user to start typing so for the prompt I can say uh what would you like to deposit question mark and then I can put something like a dollar sign and then allow them to start typing after the dollar sign okay now what I need to do is check if this amount is actually a number because they could type in anything here right they could type in a low World they could type in nothing and just hit enter they can do whatever they want so I need to make sure that the amount actually is a number before I get out of this wall Loop so I'm going to say if the amount do is and then digit like this then we can do something inside of here now is digit is just going to tell us if this is a valid whole number so if it's something like a thousand you know 10 whatever if they type in a negative number it actually won't be true so if they do something like9 then uh it's not going to be true and we call is digit anyways this is a method you can use on strings to determine if this is a valid number so if this is a digit then what I'm going to do is I'm going to convert this into and uh an INT so I'm going to say amount is equal to int amount and that's because by default this comes as a string and we want to have a numeric value for our balance or for our deposit so we need to convert this to an in however I can't do this before I make this check because if I do that then this could potentially fail because if they try to type in something like Hello World then this here is invalid I can't convert hello world into an integer so that's why I'm first checking if they did actually enter a valid number if they did I then convert it to a number now what I need to do is check if this number is greater than zero so I'm going to say if the ount is greater than not equal to but is greater than zero then I'm going to break out of this wall Loop if it's not greater than zero then I'm going to put an lse statement here and I'm going to say print amount must be greater than zero dot okay there we go now I'm just going to add one more else statement down here and I'm going to say print uh please if we could type this correctly enter a number okay then finally here we are going to return our amount all right so let me go through what we just did here so we wrote a function deposit this is a wall Loop so we're going to continue to do this until eventually we break out and this break keyword just ends the wall Loop and then will bring us down to this line I ask what is the amount you want to deposit they enter something if this is a digit then I'm going to convert this to an integer and I'm going to check if this is greater than zero if it is it's a valid amount we can work with this we'll break out and then we'll return that amount and we can use that later on okay otherwise I'm going to print this amount must be greater than zero because if it's not greater than zero well we need to tell them that and then get them to try again all right so that handled this first if statement now if the amount is not a digit then what we're going to do is uh print sorry please enter a number and we're going to continue this until we get a number and until we break all right so that's that function now to call the function if we spell uh deposit correctly here I don't even know how I messed that up so badly okay deposit uh to call the function we simply write the name of the the function and we put our two parentheses and now as soon as I run my code this function will run and we'll be able to actually enter a number so let's do this you can see in my terminal that's asking me what would you like to deposit let's go with something like $10 and all is good now if I run this again and I enter something like Hello World it tells me please enter a number okay let's enter zero all right amount must be greater than zero enter one I'm good to go so there we go we've written our first dep positive function and I've tested it it's working good we're all good to go all right so now what I'm going to do is I'm going to say my amount is equal to my deposit and actually we're going to call this balance and this is kind of the start of our program here and in fact I'm going to put our program in this function main so that if we end our program we can just call this function again and then it will rerun the program right so I can say do you want to play again and then we can rerun the main function and we'll be good to go so we've done that now I need to call the main function so that we start running Main and then it's going to do everything inside of here okay so now inside I made the next thing that I want to do is I want to collect the BET from the user so there's actually a few ways I can do this but I need to determine how much they want to bet and then how many lines they want to bet on and then I would multiply their bet amount by the number of lines so it probably makes sense to ask the number of lines first and then ask them how much they want to bet on each line so it's not confusing if I say how much do you want to bet they put $10 and then they say three lines that ends up being $30 you see what I mean so let's say Define and we'll say get number of of lines like this and inside of here we're going to ask them to pick a number between 1 and three because that'll be the number of lines that we have and to keep this program nice and dynamic I'm going to add what's known as a global constant at the top of my program and I'm going to say maxcore lines is equal to 3 now I'm doing this in all capitals because this is a constant value something that's not going to change and this is a convention in Python you do it in all capitals I'm making it equal to three okay so now anywhere in my program where I'm referencing the number of Maximum lines in my slot machine rather than writing three I'll just write this and then later on I can easily change this to be five and the whole program will update based on that right so let's make this three for now okay so get number of lines uh obviously the minimum lines will be one we don't need to write that in okay so we need to ask them to enter this so we can actually just copy everything we have in the deposit function and just change a few values here so we're going to say while true rather than amount we're going to say lines and we'll say enter the number of lines to bet on okay and then I want to put inside of here kind of the options so like one to three so I'm going to write one dash and then I'm actually going to do a concatenation here plus and then I'm going to convert my number of lines or my max number of lines to a string and then I'm going to say plus and then I'm going to put a ending bracket here question mark and then a space okay I know it seems a little bit confusing but what I've just done here is I have now added Max lines inside of this string there's a few other ways to do this but this is the most basic so that's how I'm doing it and I need to convert this to a string because if I add two strings together they get squished together but if this was a number and I tried to add it to the string then this would cause an exception in my program so enter the number of lines to bet on one dash and then I'm going to put in whatever the string version is of the maximum number of lines end my bracket put a question mark and then I'm putting a space so that when they start typing they're not like connected to the question mark they're off by one space and it looks easier for them to read right okay so now same thing I need to make sure that they actually did enter a number so I'm going to say if lines do is digigit then I'm going to say that my lines is equal to int lines like this and I'm going to check now if the lines is within the bound that I had so within one and three so the way to do this is I'm going to say if and I'm actually going to say zero um actually we'll say one less than or equal to lines less than or equal to and then this will be the max lines all right so this is something you can do in Python you may not have seen before if I want to check if a value is in between two values I can write it like this so what I'm saying here is if my lines is greater than or equal to one and is less than or equal to the maximum lines then I'm okay I can break otherwise I need to tell them uh to enter a valid number of lines so I'm going to say enter a valid number of lines okay otherwise same thing we'll say enter a number and then rather than returning the amount we'll return the lines okay perfect so now we have a function that gets the deposit amount and the number of lines so now in our main function we'll say lines is equal to get number of lines like that and now what we can do is print out the balance and the lines just so we can see what this is when we run the program okay so now let's go here let's run and how much would you like to deposit let's go with $100 okay Enter the number of lines let's try four okay it doesn't work let's try zero doesn't work let's try H doesn't work let's try two valid and notice I I now have a balance of 100 and the number of lines is two the next thing I need to get for my user input is the amount that I want to bet on each line so let's do this and we'll have a maximum bet as well so we'll say Max bet is equal to let's go with something like $100 and let's say the minimum bet is equal to $1 and again we're putting these as constants so that we can use them kind of anywhere in our program so now let's just write this function from scratch let's say toine get bet so we can add our Co in and continue and for get bet we'll just ask them how much they want to bet uh and honestly actually now that I think of it let's just copy the same thing from deposit I don't like repeating all of this code but they are slightly different so it's fine to do something like this so for the amount we can actually use the same value and rather than what would you like to deposit we'll say what would you like to bet question mark again we're going to check if the amount is a digit we're going to convert this now to an integer and now we need to check if the amount is between the minimum and the maximum bet so I'm going to say the Min bet less than or equal to the amount less than or equal to the max bet okay and then break and here I'm going to say the amount not must be greater than zero amount must be between and now I'm going to show you a second way that we can actually um kind of put variables in our string so I'm going to use an F string here only available in Python 3.6 and above I'm going say amount must be between I'm going to put my uh sorry squiggly brackets like this and I'm going to say Min bet and then Max bet so this is actually a very easy way to um embed values inside of your strings you put F before the string and then you put your curly braces like this and inside of the curly braces you can write any variable and it will automatically be converted to a string for you if it can be converted so in this case I don't need to convert Min bet to a string or Max bet it's automatically going to get converted by Python and I've just put my dollar signs here to make it look a little bit better when I say you know between the m and the maximum bet okay uh otherwise please enter a number that's fine and then return amount okay perfect so now we're going to say bet is equal to and then this is going to be the getor BET all right uh now we should actually make this a bit more clear what would you like to bet on each line okay so now that we've done this and we've gotten the deposit gotten the number of lines and gotten the bet we're probably want to print out here in our main function kind of what they've said so far right so we'll say you are betting you know five on three lines your total bet is $15 something like that right so we're going to say print you are betting and let's do an F string here as well and then let's do a dollar sign and we're going to say whatever the bet is so we're going to say you are betting whatever the BET amount is on and then this is going to be lines like this and then we'll write lines and we'll say total bet is equal to and then we'll put a dollar sign and we're going to put inside of here a variable I'm going to say total bet is equal to bet multiplied by the lines okay and we'll say this is the total bet all right so let's run this now and let's see what we get we no longer need to print out the balance in the lines by the way all right so let's run this how much would you like to deposit let's say $100 enter the number of lines to bet on let's go with two would you like to bet how much would you like to bet on each line or what would you like to bet on each line let's go with $10 and now it says our total bet is $20 great so this is okay but I just realized that we actually need to check if the amount that they're betting is within their balance because they can't bet more than whatever their current balance is so we need to check that and we could check this in a few different places but since I've called this get bet I'm not going to put it inside of here I'm just going to do the check here and then I'm going to recall get bet if they entered an invalid bet so I'm actually going to put now this inside of a wallet but I'm going to say while true I'm going to say bet is equal to G bet and I'm going to then say total bet like this inside of here so we put total bet okay now I'm going to say if my total bet is greater than my balance then we'll say print you do not have enough to bet that amount and then we'll say what their current balance is your current balance is and then we'll put dollar sign we're going to put our F string here and this is going to be their balance all right and then otherwise we will simply break out okay so hopefully that makes sense I also could just put uh condition here for the wallo but I think this is okay for right now all right so let's try this now let's run our code how much would you like to deposit okay $100 uh let's bet on three lines let's try to bet $40 and since you do not have enough to bet that amount your current balance is $100 okay uh how much you like to bet on each line let's go with $20 you're betting $20 on three lines the bet is equal to $60 okay so we have now successfully got the number of lines the betting amount the deposit amount now what we need to do is we need to actually run the slot machine now this is where it gets a little bit more complicated and I'm going to start importing some modules so the first module I'm going to import is the random module because we need to generate um the slot machine values kind of randomly right so how are we going to do this well the first thing we need to figure out is how many items we want to have in each reel and how long we want the lines to be now slot machines can get a bit complicated in terms of how the lines work I'm going to keep this really simple and we're going to imagine that we have a 3X3 slot machine and that you only get a line if you get three in a row okay if you get three in a row then you win this might not be the most balance slot machine it might not be one you want to play on but for this project it's fine so again I'm going to set some values here that specify the number of rows and columns we're going to have in our slot machine so I'm going to say rows is equal to three and calls is equal to three and if we wanted to make this a little bit better we could say I guess actually you know what row and call is fine for right now I don't know exactly what they would call uh like I guess it'd be like real count and number of reals or something like that for now though this is fine all right now what we need to specify is how many symbols are in each of our reals now it should be the same at least from what I know it should be the same number of symbols in every single real we're not doing anything really complicated when I say real I'm talking about kind of one column right so how many symbols are in that column because we're going to have to randomly select out of those symbols and then we need values for our different symbols so we need to pick kind of first of all how many symbols do we want to have in total and what do we want those symbols to be uh now to keep this easy we can do something just like you know a b c d like those are probably fine as the symbols um yeah we can do something like that so let's say symbol count is equal to and let's make a dictionary here now for our dictionary I'm going to have the symbol be a string and I'm going to have the count of this symbol in each real so I guess what we can have is characters that are like at the beginning of the alphabet like a be the most valuable so maybe we only have I don't know something like two A's in every single reel and then for B's we could have something like four of those for C's we could have six and for D we could have eight now again I don't think this is going to be a very balanced slot machine I'm not going for the best odds here I'm just trying to kind of make something work so let's see if this actually works for us if every single reel we have 2 A's 4 B's 6 C's and um what do you call it ads to choose from now the thing that I think is going to happen here is we're going to get a lot of situations where it's just D's that are being in the reals but let's see if this works at all in terms of randomly selecting okay so that's what we've done here now what we need is something that's essentially going to generate what the outcome of the slot machine was using these values here so to do this I'm going to say Define and we'll say getor slot machine undor spin okay and inside of here what we're going to take is we're going to take the rows called and symbols and this will be the symbols that we pass so these are three parameters that we're going to pass to this function and then inside of here we can use these parameters so inside of this function again what we need to do is generate what symbols are going to be in each column based on the frequency of symbols that we have here so we essentially need to randomly pick the number of uh rows inside of each column so if we have three rows we need to pick three symbols that go inside of each of the columns that we we have and for each column we're doing kind of a new random pick right a new random generation of the symbols now this can be a bit complicated now the easiest way to randomly select um values here for each of our columns is going to be to create a list that contains all of the different values we possibly could select from and then to randomly choose three of those values and when we choose a value we'll remove it from the list and then we'll choose again now what I'm going to do here is not going to be the most efficient algorith but since we're dealing with small values this is fine so let's see how we work with this okay so what we're going to Define here is allore symbols okay now this is going to be a list and what we're going to do is write a for Loop that's going to add however many symbols we have here into the all symbols list so I'm going to say four and since we're iterating through a dictionary I can do the following I can say four symbol comma symbol count and then this is going to be in symbols. items now when you use do items what this does is give you both the key and the value associated with a dictionary so I can get the key here and the value and I can just use both of them rather than looping through the dictionary only getting the keys and having to manually reference the values okay so now that I have the symbol and the symbol count I want to add this many symbols to the um what do you call it symbols list now there's a few different ways to go about doing this I think the easiest way to do this is just going to be to run another for Loop so that I don't confuse anyone so we're going to say four and then this is going to be let's do this I in range and then symbol undor count and actually we don't even need I we're going to put underscore now this is an anonymous variable in Python so whenever you need to say Loop through something but you don't actually care about the count or the iteration value then you just put an underscore and then you don't have an unused variable anymore so I'm going to say four underscore in range symbol count I'm going to say allore symbols Dot and then this is going to be append and I'm going to append whatever the symbol is so what's going to happen here is I'm going to Loop through this dictionary let's imagine on the first key value pair my symbol is going to be a and my symbol count is going to be two all right so then I have another for Loop inside of here where I'm looping through the symbol count so the symbol count is two and what I'm doing is doing this two times so I'm going to add this symbol twice into my all symbols list all right now that we have the all symbols list we need to select what values are going to go in every single column so how do we do this well let's make a for Loop that is going to do this for every column so I'm going to say my columns is equal to a list and inside of here I'm going to place a bunch of lists which are going to contain all of the values inside of my columns now this may seem a little weird to any of you that have used a nested list before because typically when you write a nested list uh you kind of have all the interior lists here that are representing your rows so if I had like 0 0 then these this would be the values that are in row zero right or in the first row and then this will be the second row and Etc however here we're doing it the other way around where each of these nested lists is going to represent the values in our column so keep that in mind I'll explain how this works in case any of you are a bit confused later on but I just want you to know that we're storing The Columns not the rows inside of here okay so we have all of the symbols and now for each of the colums that we have uh we need to generate what is it the values inside of the columns and how many values do we need to generate well however many rows we have that's how many values we need so we're going to say four and this is going to be call in range and then calls like that and then we need to say four and this will be Row in range rows okay so for every column we need to generate a certain number of uh symbols so inside of here I'm going to say that my column is equal to an empty list this is actually not going to have our columns inside of it I'm just was putting that there for an example and now I need to select a certain number number of values sory from our all symbols list so let's see how we do this so we're going to say value is equal to random. choice and I'm going to choose from all symbols now I can use random because I imported random here now what we're actually to do though is we're not going to use the all symbols list we're going to use a copy of this and you'll see why but what we need to do is once we pick a value we need to remove it from this list so that we can't choose that value again right so if there's only two A's we shouldn't be able to Select Three A's we should only be able to select that most too so if we select one a we need to remove it so then the next selection doesn't have that as a chance so that means we need to make a copy of this all symbols list because if I start removing from this all symbols list then when I try to do the next column it's it's going to have values removed so that's what we need to do we need to make a copy so I'm going to say current uncore symbols is equal to all underscore symbols and the way you copy a list is you do this you put a coal in here this operator here is referred to as the slice operator because if I just did this and made it equal to all symbols what happens is current symbols stores the same object as all symbols now that means anything I do to all symbols affects current symbols and anything I do to current symbols affects all symbols so this is not what we want we don't want what's referred to as a reference we want a copy so the way you do the copy is you put a CO in here make sure you add this otherwise it's not going to work okay continuing here now what we're going to do is Select from our current symbols and then we're going to remove whatever this value is from our current symbols list so we're going to say current uncore symbols do remove and then value now when you do do remove it's just going to find the first instance of this value in the list and get rid rid of it okay now that we've done that we want to add this value to our column so we're going to say column do push and sorry not push I'm not in JavaScript right now I'm in Python do append the value all right and I just realized here we don't actually need the column and we don't need the row so we can just put underscores there now what we're going to do after this is we're going to say columns. append and we are going to append our current column now let me run through this cuz I understand it's a little bit confusing we start by defining our columns list then we are going to generate a column for every single column that we have so if we have three columns we need to do everything inside of here three times that's why we have this first for Loop then inside of here what all this code is doing is it's picking random values for each I guess Row in our column right for each value that we're going to have so we say column is equal to an empty list we say our current symbols which are the ones we can currently select from is equal to a copy of all symbols then we Loop through the number of values that we need to generate which is equal to the number of rows that we have in our slot machine then we say the first value we're going to get here or a value we're picking is random not Choice current symbols this picks a random value from this list okay we then say current symbols. remove the value so we don't pick it again and then we add the value to our column okay once all of that's done so this for Loop is finished we now should have however many rows there are symbol inside of our column we now add our column to our column's list then finally we can go here and we can return our columns okay and remember that when we're looking at this list here every interior list gives us the value of the items inside of our column I know a little bit confusing this was quite a bit of logic especially if you're a beginner programmer but I told you I wanted to make this challenging enough to be interesting for you and show you some new stuff so don't worry if this doesn't make complete entire sense maybe read through this a few times pause the video go back and listen to the explanation again uh but this is you know how we generate the items that are going to be in our slot machine now that we have this we want a way to print this out we want to look at this because I can't even really test this yet until I can print out what's inside of all of my columns and I want to print this in like a nice way so I'm going to make a function here and say Define printor slot machine and what we're going to take here is our columns now when we have our columns it's not really in a format that's easy for us to print because we have all of our columns kind of laid out as rows almost right like we have maybe actually this isn't going to be good but we would have like a b c and one maybe we have like a a a and again these are our columns not our rows so what I need to do is kind of flip these around so rather than having like a b c a a a it would go a b c right in the First Column and then this would say a a and then a like that I know that I kind of butchered this example the way that I wrote it out we need to change it from being this way to be this way right that's how we need to print it out so how are we going to do that well this operation is actually referred to as transposing because we have what's known as a matrix we don't need to get into all the fancy words but understand this is known as transposing so the way we're going to do this is we're going to write a for Loop and we're going to say four and then this is going to Row in range and then we need to determine the number of rows that we have based on our columns now the number of rows that we have is the number of elements in each of our columns right because that's the number of vertical spaces we have so we need to look at a column and get the length of that so we're going to say the length of columns zero now this assumes that we have at least one column and we should always have one column so it's fine to put this here but understand that if we did pass something that had no columns this would crash because there be no column at index zero to access so I'm saying four row in range the line of columns zero then what I'm going to do is I'm going to Loop through all of my columns and only print the first value in it or whatever the index of my current row is again I'll explain this a second I know this is a bit confusing so I'm going to say four and this is going to be column in and then columns like that and when I do this now I'm looping through all of the items inside of column so it's giving me every individual column so now that I have a column I'm just going to print the value that's at the first row of that column so I'm going to say print and then I'm going to print column at row and I'm just going to put a comma here and put a pipe operator and the reason I'm going to put a pipe operator is so that we have some separation between uh the different items right now I just want to make sure though that I only put this pipe operator here if we're not printing the last column because if we're printing the last column then we don't want to have the pipe like off right we only want to have two pipes in the middle not one at the very end so the way I need to check this I need to say 4 I comma column in enumerate columns now when you enumerate what this does is give you the index so 0o 1 2 3 as you Loop through as well as the item so now that I have I what I can actually do here is I can say uh there there's a few ways to do this let's actually go back to this we'll say if I does not equal and then this is going to be the Len of columns minus one will do this otherwise we'll print the same thing we just won't print the pipe now there's a bunch of different ways we could have done this but this is just the way that I think is going to be easiest so that's how we'll do it so the reason I'm checking if I is not equal to l of columns minus one is because the Len of columns minus one is the maximum index we have to access an element in the columns list right if we have a columns list with three items the length is three the maximum index is two so if I is not equal to the maximum index print the pipe otherwise don't print the pipe that's how it's going to work okay so now we have print slot machine and get slot machine spin that's all this is all we need for printing the slot machine so we Loop through every single row that we have for every single row we Loop through every column and for every column we only print the current row that we're on so we're going to print um what is it row zero so all of the elements in row zero first then Row one then row two and this essentially transposes or flips our columns from being this way to be vertical this way all right so let's try this now and then we'll kind of finish the program because we're actually getting quite close now all right so once we determine what they're betting down here what we need to do is generate the slot machine so we're going to say slot we'll say just slots is equal to and then this is what do we call this function we called it get slot machine spin okay so get underscore slot machine Spin and then it autofilled this for me we're passing the rows columns and symbols so rows is all capitals actually calls is like this and the symbols I believe we called this the symbols count uh or we call it symbol count so let's go here and make that symbol count okay so now we should have all the columns in our slot spin right that's what that did for us now what we need to do is we need to print this so we're going to say print slot machine and we're going to pass to this are slots and really this is the columns but I'm just calling them slots because each one is like what's in the slot right okay let's give this a shot guys there probably will be an error because that's usually what happens when you write this much code from scratch but let's see if this works okay so we are depositing let's deposit $100 enter the number of lines to bet on uh let's bet on two and then how much we like to bet on each line let's do $10 okay now already we got a bit of an error here because I forgot to do something which I'll add in a second but if I scroll here you can see that what's happening is we're printing everything correctly we're just not printing it um on the same line which is what we need to do so ideally want Da and D on the same line CB and C on the same line and BC and a on the same line so the way that we fix that my apologies here guys is we go back to print slot machine and here we add this thing called end equals and we just make this a um what do you call an empty string and in fact let's actually do this end is equal to a pipe with spaces all right so what end does is it tells the uh print statement what to end the line with Now by default end is equal to what's known as the new line character or the return character or whatever you want to call this carriage return there's different names for it I call the new line character now back sln if you ever print this out it's what tells the um console to go to the next line so we don't want to print that because if we print that at the end then that means that we move to the next line after every single row we only want to do this sorry after every single column we only want to do this after every single row so I'm going to change this to be a pipe so now we'll just print this pipe at the end of our print statement so after we print this here we're just not going to print anything and now we need one more check to see if we should go to the next line or not because every row we want to go down to the next line so I'm actually going to say here uh print and we can just do an empty print statement Now by doing an empty print statement it just brings us down to the next line because it prints a new line character by default at the end of the empty print statement seems a bit weird that's kind of how this works we're going to print the first row this will go on the same line then we're going to print a new line character so it brings us down to the next line print the next row new line character next row new line character next row Etc right so let's have a look at this now okay let's go here let's let's run how much you like to deposit $100 uh let's bet on two lines how much would you like to bet $10 and there we go now we have our slot machine excuse me and this is correct right so we have all of our columns uh and then all of our rows and what we' now be checking is if we have three in a row right that's what we're going to have to check okay so we have our slot machine we've spun it we probably should have some input that asks like do you want to spin the slot machine and then they can hit spin blah blah blah be a bit more Interactive but that's how it works and just to be clear here we're going to check if we have three in a row and if we do based on the value of the symbol we're going to multiply their bet and then give them that amount all right so let's write a function that can do this now when we're checking if they want or not we need to know what their bet is which lines they bet on right and then we can actually check now the way the lines works again I know this is not exactly how like a real Casino slob machine would work we're going to make it so that if you bet on one line you just bet on the top line if you bet on two lines you bet on the top and the middle if you bet on three lines you bet on all three I'm not going to let the user pick like where the one line is they want to bet on we'll just say one is top two is both the top two three is all of them and that's how it'll work okay so let's do this let's go Define check winnings okay now to do this we need the slot machine itself we need the lines so we're going to say lines and we need the BET okay so how we going to do this well we just need to look at the rows that the user bet on so let's start with that and then we can check each row and determine a value also for the symbol so we're actually going to take one more thing we're going to say values now I'm also going to make the values here so I'm going to say symbol uncore value and I don't know what actually makes sense again to do for this but we're going to say that D is going to be a two times multiplier C is going to be a three times multiplier this will be four and then this will be five so you know the more rare the symbol is the higher your bet gets multiplied again I don't think this is a fair slot machine but that's fine okay so check winnings now we have columns lines bet and value now let's look through only the rows that they bet on so the lines that they bet on so to do this we're going to say four uh and we'll say line in range then this is going to be lines like this now the reason this will work is because if they bet on one line then we're going to go up to one line but not include it so that means line will be equal to zero right so if bet one line then this is one and that means this is only ever going to be zero if they bet on two lines then line will go to zero and one so we'll check the zeroth row which is line one and the first row which is line two if they bet on all three lines then line will be zero then one then two so we'll check all three of those rows right and this will work dynamically even if there was more lines to bet on so inside this for Loop we need to check that every single symbol in the line line or row that we're checking is the same so we can get the first symbol that's in this row and then just make sure it's the same for the rest of the symbols so to do that we're going to say symbol is equal to columns 0 at the current line now the reason we're using columns Z is because we have all of the columns not all of the rows it makes it a bit more complicated so we need to look at the First Column because that's where the first symbol is always going to be for each row and then get whatever line we're on so First Column and then either you know line zero line one line two Etc going down that First Column gives us the first symbol and we're going to assume that we always have at least you know one real right so at least one column so now that we have the symbol we're going to Loop through all of our columns so we're going to say four column in columns like that now what we want to check so the symbol toore check is equal to the column at whatever row we're looking at so if we're looking at row zero we're checking the first symbol in the column if we looking at Row one checking the second symbol in the column Etc symbol to check we're then going to say if the symbol is equal to the symbol to check and actually we'll say if it is not equal to the symbol to check then we are going to break okay now the reason we're breaking is because if we found one of the symbols is not equal to the previous symbol uh or equal to all of the symbols that should be in this um row then we just break out of the for Loop and what we'll do is we'll put an else statement here and what this else statement will do is it will tell us if we didn't break out of the for Loop so I'm sure you probably haven't seen this before but you can do a four else where if you break this else statement does not run but if no break occurs within the for Loop then this else statement executes so in the else statement here what we'll do is we'll figure out how much they won so we'll say winnings is equal to zero okay and then here we're going to say winnings plus equals and then this is going to be the values at the symbol multiplied by the BET and then we can go here and return the winnings okay so let's look at this because I'm sure this is confusing we have every line in the lines which means We're looping through every row essentially that we're going to be checking that the user bet on we then say the symbol that we want to check is whatever symbol is in the First Column of the current row because all of the symbols need to be the same right we then say for column in column so we now know the symbol that we're going to check now we need to Loop through every single column and check for that symbol so we go to each column and we say the symbol to check is equal to the column at the current row that we are looking at so if it's row zero we're doing row zero if it's Row one row one Etc we then check if these symbols are not the same if they are not the same we break out which means that we're going to go check the next line because they didn't win because symbols were not the same if they are the same then we don't break and if we get to the end of this for Loop and we've not broke out which means all of the symbols were the same then that means that the user won and what they won is whatever the multiplier is for that symbol times their BET right and this bet is the bet on each line not the total BET right so they could win on one line but lose on the other line that's how it works okay hopefully that's clear uh I can't explain it much more than that just understand symbol values here right uh gives us you know 5 4 3 2 so that's what I'm using I'm saying values at whatever the symbol is multiplied by the bet that's how we're adding to the winnings okay so that's it for determining how much they won so let's run the game one full time now and then we'll figure out how we can run it multiple times and reduce the balance and all that which is easier than what we just did okay so we print the slot machine and now we're going to say winnings is equal to and what did I call this uh Che check winnings okay check winnings we need to pass to this our slots the number of lines so I think we called that lines right the BET which we have right here and the values which is called symbol value so let's go symbol uncore value all right then we're going to print U1 and then whatever the amount is that they want so let's make this an string okay and then U1 and then this is going to be winnings like this and this could potentially be0 right okay so I think that's good I'm thinking that we might want to also tell them how many lines they want on or what lines they want on so let's actually return that as well from this function so get uh check winnings we're going to do one more thing here we're going to say winning uncore lines is equal to to an empty list and if they win we're going to say winning lines plus equals uh actually not plus equals do append and then this is going to be whatever the current line number is but we're going to have to add one to it because this is an index and we want like line one 23 not 012 so we say winning lines do a pen line plus one then we go here and we put winning lines and now we're returning two values the total amount they won as well as what lines they won on okay now let's go here to winning lines and and we're going to say winnings and winning uncore lines you won these winnings and then we'll say U1 we'll print another line like this F U1 on and then this is going to seem a little bit weird but I'm going to do asteris and then I'm going to pass my winning lines now again I promised I was going to show you guys some new stuff so I'm I'm showing you some Advanced syntax here but what this does is it's actually called the Splat operator or the unpack oper operator and it's going to pass every single line from uh this winning Line's list to uh this print function so what that means is if we have lines like one and two it's going to pass both one and two so it's going to say U one on and then one two so I'm going to say you want on lines like this and then it would say one space two if we want on all three lines say one space two space three if we didn't want any lines then it's not going to say anything okay you you'll see when when we print this out how this works so let's run this here let's make this full screen now and let's go through an example so deposit $100 uh how many lines four invalid okay let's bet on two lines how much would you like to bet on each line $10 all right so we won $0 because none of the symbols are the same so let's try again all right deposit $100 uh two uh two lines sorry how much would you like to bet $10 you won 0 okay so this is going to happen a few times so rather than continuing to do this and hoping that we're going to win let's make it so that we can run this multiple times without having to constantly rerun the program so we have this main function we have the balance and we have the lines now the balance is going to stay the same but all of this stuff here needs to happen multiple times right and we'll reduce from the balance and all that stuff so let's copy all of this into a function and let's say Define let's say game okay we'll put this inside of here so this kind of executes one game now what we can do is write a w Loop here and this W Loop can kind of handle running the game all right so I'm just thinking here if we do this we need some way to determine like from this instance of the game so like per spin so actually let's just say this is maybe spin we need to know how much they won or they lost so I'm just going to return here the winnings minus the total bet and that will tell us how much they won or lost from this spin because if they won $100 but they bet 15 then they only won 85 so then here we would update and we would add 85 right but if they didn't win anything then it's going to be negative whatever the total bet is so like 15 bucks so we'd subtract 15 from the balance okay so here I'm going to say while true and we'll print um current balance is and then we can just put comma actually let's do this as an F string so we can put a dollar sign current balance is and then we'll do dollar sign and then balance okay and then we'll play game so we'll say spin equals input say press enter to spin okay so they'll press enter to spin so actually we don't even need to put a value here because we don't care what they type in or actually we could say this spin is equal to press enter to spin and we'll say Q to quit so if they type in Q then we'll quit so we can say if spin is equal to Q then we will break the wall Loop which will just end the game okay otherwise we'll spin so we can say spin like that and we'll say balance plus equals spin so the way that this works now is that spin is going to return to us however much they won or lost it will tell them like what they won or lost so then we'll just update the balance based on the result of that spin and then we'll run this again to say okay current balance is this press enter to spin blah blah blah and then when they spin they're going to have to uh enter this info and actually press enter to spin probably doesn't make sense to go here right because you only want to spin after you enter your information although we can just have this works we'll say press enter to to play that's fine and then they can do it inside of there uh okay now that we have that I think that's actually all that we need I'll just make one last print statement here that says you left with and then we'll put it inside dollars and then this will be the balance and we'll put an F string here all right let's run this and give it a shop okay so run go here how much you like to deposit let's deposit $1,000 okay current balance is $1,000 press enter to play Q to quit Okay enter uh and we go an object here balance plus equals spin all right looks like we need to fix this so balance is equal to deposit balance plus equals spin we have winning lines subtracted by total bet and what is the problem all right so the issue here is that I accidentally have the name of my function spin the same name as this right here so we're just going to change this to be answer so now this will work properly okay so my apologies guys let's go here and fix this and let's say $1,000 current balance is a th000 press enter play okay Enter the number of lines to bet on let's bet on two lines let bet 10 bucks okay uh balance is not defined looks like we need to fix another error so what we need to pass here is balance to the spin function so that it can actually check this when we make a bet so of of course that makes sense just forgot to do that so let's pass balance here and now we'll actually be able to check that all right so let's try it again third times a charm $100 current balance is $100 press enter to play okay number of lines let's go three let's go $10 and you are betting on $10 you're betting $10 on three lines total B is equal to $30 okay you won $0 you won on lines and it has an issue here UNS support opin for list and int okay my apologies that's cuz I put winning lines this needs to be winnings all right fourth times a charm so let's make sure our variable names are correct that was just a silly mistake let's clear and run $100 enter three lines $10 okay you won $ Z you won on lines your current balance is $70 okay let's play again three lines $5 okay did we win anything no we did not all right let's play again I'd really like to try to win something but as we can see the slot machine is not in our favor today $10 you won 0 okay current balance is $25 all right three lines $2 you won $4 okay nice so how did we end up winning uh $4 we bet $2 and we got a line here of D's so that gave us uh times two multiplier so 2 * 2 four so we won four bucks there you go and then our balance get up gets updated sorry to 2 $3 because we were at 25 uh subtracted six add four yes okay so that makes sense all right so let's play again let's go three lines $1 okay you won nothing let's play again three lines $1 you won nothing three lines $1 uh oops uh this is let's go $3 you won nothing okay play again one line $3 you won nothing all right well I won't continue to play but you get the point we have just created a slot machine and now if I hit q and and enter we leave with $11 all right so I think I'm going to wrap it up there I'm going to zoom out a bit so you guys can read more of this code I'll just kind of scroll through it I'll also put it in the description in case you want to reference it on GitHub but you can see this is what we wrote so we did about 150 lines of code in I guess about an hour now I walked you through my thought process I showed you a bunch of different python features we did actually some fairly Advanced logic in terms of looking through rows and columns and looking at nested lists I showed you about functions I showed you about the anonymous variable you saw this uh Splat operator here and when we went on a line you saw it said we won on whatever the line number was so hopefully this was helpful to you guys hopefully this showed you kind of how to structure a program notice that we put everything in separate functions we've kind of spread our code out we've made it very readable and now we know if there's a bug anywhere it's really easy for us to go and kind of figure out where that is because we've separated everything into different units right different blocks of code anyways I will wrap W up here I hope you guys enjoyed this video everybody and welcome to a brand new YouTube video so it's been a while since I've done a kind of beginner project something that really anyone can follow along with regardless of their background in Python and so I wanted to do one for this video so what I'm going to be showing you how to do is actually create a graphical application so this is not just going to be text although it looks like that right now and what's going to happen is we're going to create a turtle racing program so essentially the user will be asked to decide how many turtles they would like to race based on their answer a screen will pop up as I will show you in one second and then it will race that many turtles by just randomly moving them on the screen now this is a great project to learn about how to build something a little bit bigger than a really simple hello world application I guarantee if you're new to python you're going to learn a ton here I purposely used a bunch of different syntax and functions and kind of showed you how we can lay out a relatively large program for beginners this is not a large program by any means in kind of a nice structured way where everything is just done in kind of the proper format so anyways let's go ahead and get started here I'm just going to show you a demo of what we're going to be building so it says welcome to Turtle racing please enter the following information how many turtles would you like to race you can enter between two to eight Turtles I'm going to select eight when I do this it's going to open up the turtle window this is built into python there's nothing fancy you need to install it's going to initialize all of our Turtles and then it's going to start racing them on the screen so it looks like the red one is going to win here let's see and oh maybe not so it says here the winner of the race is pink and then it waits 5 seconds and then it stops now I will show you how we can run this multiple times if you'd like to do that that's the basics behind this program now let me show you one more time if I race say three Turtles notice how they are evenly spaced out on the screen so I'm going to be showing you how we can do that and there you go they race nice and it says the winner anyways let's go ahead and get started so the first thing that I want to do here is I want to ask my user to input the number of turtles that we are going to have so what I'm actually going to do here is I'm going to create a function if you never seen a function before I'll explain them they're pretty straightforward but I'm going to say Define and the name of this function is going to be get uncore number uncore of uncore and then we'll say erasers like this or Turtles whatever you want to call this and then inside of here this is where we are actually going to ask the user to insert the number of racers that they want to have now the reason you're going to see me kind of write things in this way in different functions and kind of different blocks is because it really separates out what every single aspect of our program is doing and it's just good practice when you're writing code to really have all of the different separate things happening kind of in different areas so later on if something goes wrong or you want to add something or change something it's really easy to do that you're not looking through a huge mess of code and well you'll see how this kind of evolves as we go through here so what I want to do is I want to ask the user for a number so I want them to insert a number between 2 and 10 and so I also need to validate that the number there typing in is correct so what I'm going to say is Racers is equal to zero and then I'm going to say while true now the reason I have a w Loop here is because I want to continue to ask the user to insert a number until they insert a valid number so if they insert something invalid then I'm going to keep asking them and say hey no that wasn't valid give me something that's valid because we can't start our program until we know how many turtles we're going to be racing so I start with Racers equal Z I say well true now I'm going to use an input so I'm going to say Racers is equal to and then input like this and I'm going to say enter the number of racers and then I will do kind of a little 2 to1 thing here to indicate the fact that I would like them to type a number that is between 2 to 10 now you don't have to do it like this you can write whatever you want this is what I'm going to prompt the user with and then notice that here I've added a space so after my I have a space the reason I have a space is because the user starts typing immediately after this prompt so this text will be printed to the screen so I want to separate it from the colon so that it doesn't look like they're typing like right beside this line there's like a little bit of a space uh anyways what I'm now going to do is I'm going to check if this what they inputed is a number the reason I need to check if this is a number is if the user didn't input a number obviously that's invalid but also I want to convert what the user types in into a number if I can do so so in Python by default when you use this input statement it's going to C capture whatever the user types into the console and convert that into a string so we need to take that string and potentially convert that into an actual integer a numeric value so that we can use that in our program so I'm going to say if Racers Dot and then is digit this is a method you can call on strings and this will tell you if the string is completely numeric or not so if the string is numeric then what that means I can do is I can convert this into an INT so I can say int eracers if you tried to just do this line without checking beforehand if it it was numeric then this would crash the program because if you had a string that was typed in that was not numeric you say you try to convert say int of Tim to a int right you're trying to convert the string Tim into an INT this is inval that's going to crash you you can't do this so anyways let's move on now if this is not the case so if erasers are or if what the user in input Sur is not a digit then what we want to do is tell them hey this is invalid please try again right so I'm going to print and say uh input is not numeric dot dot dot try again exclamation point and then I'm going to say continue now what this continue does is immediately brings me back to the beginning of the Wallop so we don't really need this continue well we will based on what I write next but think of it this way as soon as we hit this statement it immediately jumps right back up to the top of the loop so anything below this say I had a print statement saying like print high this print statement wouldn't run if we hit this continue before this print statement so that's why I have the continue here all right so if the racers is a digit so if what they inputed is a digit then we are going to convert it into an integer which is valid otherwise we'll tell them it's not numeric they need to try again and then we'll continue now if we make it past this so we don't hit this else and we did make this conversion now we want to check if this number is within the range of 2 and 10 so I'm going to say if 2 is less than or equal to Racers less than or equal to 10 then what I will do is I will just return the racers like that otherwise I will tell them that this number is not valid so the idea here is I check if Racers which is now a number that's why I wanted to convert it to a number so I could do this comparison is less than or equal to two or less than or equal to 10 so if it's within our range of 2 to 10 this is fine what I will do is return Racers so whatever the user typed in we're going to return that from this function which means whatever called this function will now have access access to it otherwise though if this was not valid what I want to do is I want to print number oops not in range 2 to 10 try again exclamation point and then I could put a continue here but there's really no need to do that because nothing comes after this continue in this wall Loop and so by default we will just go back up to the top the reason I have the continue here is because I don't want to check if the number that is not a number right so what the user typed in I don't want to check if that's between 2 to 10 because if I do that and we haven't converted this into a number we're going to get an error let's say you know what the user typed in again was Tim I can't check if two is less than or equal to Tim this is just undefined this operation makes no sense and so that is why I'm continuing to make sure if I don't get a valid number I don't do this comparison and crash my program all right so now we have this function so I'll show you how we can use this right we can just call the function so get number of racers and we can say something like Racers is equal to get number of racers and then we can just print out Racers down here now what will happen is all of the code that we wrote inside of here notice it's indented after the colon right uh it's going to run all this code when we call the function and then as soon as we hit this return statement what will happen is we will actually return back to where we called this function so back to this line and we will pass whatever the value of racers what so Racers will be equal to down here whatever is returned from this line so whatever number the US typed in that was numeric in between 2 to 10 then I'm going to print out those number of racers that the user typed in and that's kind of the start of our program then we've got a few more stuff few more steps sorry to do after that so let's try running our program I'm going to say python turtler R tutorial. piy again if you're an idle just press F5 and come on enter is this going to work uh okay something's wrong with my terminal python Turtle race tutorial. P okay Enter number of Racers 2 to 10 let's enter five and and then it prints out five now let's try something inval let's try Tim now it tells me input is not numeric try again let's try uh Joe not numeric try again let's try 11 number is not in range let's try 10 boom that works we get 10 awesome so this is indeed working we just did a few tests here and you can see that down here we are getting access to whatever this function returned so now that we have the number of racers what we want to do next is actually set up our total screen so I will show you what I mean by that but let's start by importing the turtle module so the turtle module is built into Python and this allows you to perform very basic 2D graphic operations with this thing called a turtle so you'll see it in a second but essentially it's like a little kind of header on the screen and you can kind of move it around it will draw lines and it's a really great way to just learn the basics of python in a nice visual way so now we have the number of racers now we've imported turtle and let's actually just see what happens now when we run the program after importing turtle so we're going to run this uh let's import our number of racers we can go four and we actually see that nothing happened hm I was thinking the turtle screen might pop up but it's I think it's because I haven't used this module yet so anyways that that was a poor example what I'm going to do next is show you how we can create a turtle screen so ignore that last example uh what I was expecting to happen didn't happen often times when you import a module like something will happen when you import it so what I'm going to do now at the top of my screen is I'm going to Define first of all the width and the height that I want my turtle screen to be so usually whenever you're working with Graphics you need to define the size of a screen or the size of the canvas you're going to be working on so in this case I'm going to say in all capitals width comma height is equal to and then 500 comma 500 if you haven't seen this notation before this means width is equal to 500 height is equal to 500 you can separate as many variables by commas as you want and then do the assignment with commas as well so the reason I'm doing this in all capitals is because these are constant values so in programming whenever you have a constant value in a language where you can't explicitly Define that you usually have all capital letters to denote the fact that this value width and this value height will never change they're just here so that we have easy access to the width and the height all right so now that we have the width and the height we want to set up the turtle screen so we're going to start by creating a screen so we're going to say screen is equal to and then Turtle Dot and then all capitals screen now what this is going to do is initially a screen for us with this Turtle module and then we can kind of set some properties of this screen the first of which is going to be the width and the height so now that I have my screen I'm going to say screen Dot and then this is set up and here we're going to pass the width and the height so this method right here takes two arguments a width and a height of the screen and then it makes the screen that size so now that we have that let's run the program and let's see what we get so python Turtle race. pi and and notice you can see a screen pops up here immediately and then it's asking me to input the number of racers so I can input say five and then the program ends and the screen automatically closes great but when I do this notice that uh we get python Turtle Graphics as the name of our window we might not want that we might want to change the name so let's actually go ahead and do that so I'm going to close this uh probably should have left the CMD open but that's fine and now I'm going to say screen. tile and in here I'm going to put whatever I want the name of that window to be so I'm going to make mine turtle racing exclamation point now let me go and open up my command prompt again uh you can kind of ignore what I'm typing I'm just trying to get to where my file is so python Turtle race tutorial. py when I run this notice now the title has changed to Turtle racing awesome so let's just input a number and end the program there let me make this guy a little bit smaller okay so now we've gotten the number of racers we have set up the turtle screen and what we want to do next is actually create our Turtles right we want to start racing them on the screen so I'm going to start by showing you kind of the basic commands of a turtle so how you kind of move a turtle around the screen some of the things that are associated with it and then we'll create a bunch of different Turtles and then obviously Ras them so what I'm actually going to do though is I'm going to take all of this code related to The Turtle stuff so the screen setup the screen title all of that and I'm actually going to move that to underneath where my Racers are and in fact I'm actually going to make a new function I changed my mind I'm going to call this a nitor turtle and inside of this function we're going to set up everything related to our kind of turtle screen now the reason for this again is that we just want to kind of structure our program nicely so we won't show the turtle screen until we call this a knit Turtle function so after we get the number of racers then we can pop up the turtle screen because I don't really want it to be shown until we've picked the number of turtle erasers that we have so after we get the number of erasers we can say a knit turtle that will just run all of the code in here so we'll set up our Turtle screen so let's actually go ahead and run this uh and let's see what happens notice that the turtle screen hasn't popped up this time but then when we type four it kind of popped up really quickly and then it closed because as soon as we pop it up the program ends there's nothing more that we need to do we're on a good start now that's kind of what we wanted to do okay so now I'm going to show you how we can kind of move a turtle around the screen so to do this you need to start by creating a new turtle object so to create a new turtle object what you need to do is say and in this case we'll just say eraser is equal to and then Turtle Dot and then with a capital T this time Turtle so what this will do is actually create kind of a drawing object for you on the canvas that you saw that white canvas that popped up and then what you can do with this is you can move it around so I'm going to say eraser Dot and then just to show you one method you can use forward I'm going to move it forward by 100 pixels now I'm going to do something here that may seem a little bit confusing but I'm going to import a module called time at the top of my program and down here this is really the only new code that we've added right after I move my racer forward by 100 pixels I'm going to say time do sleep and then five what this will do is pause the program for 5 seconds so that after we move our Turtle we have a second to actually see where it went we don't just immediately close the turtle window although we may or may not do that um immediately close the turtle window anyways we'll we'll see here after this happens so let's run this code right now and let's see what happens we'll say four and then notice it opens this Turtle window and then it moves this kind of pointer over here by 100 pixels and then it closes obviously because now uh we are no longer sleeping so hopefully that kind of made sense but you you would have seen uh let's run this one more time that it opens up the window it moves our little pointer here which funny enough isn't actually a turtle right over 100 pixels and then it closes so this is one of the methods you can use with your turtle the turtle will start in the middle of the screen the turtle is really that drawing kind of arrow that you saw and every single time you move it it will create a line so you don't only have to move it forwards you can move it backwards and you can also change its directions you can set it to move maybe in 90° you can set it to go left you can set it to go north east west whatever Direction system you want to use you can set it to go in that direction so I can say racer. left and then I can make it go left by 90° and then I can say racer do forward move it forward 100 again and then I can say raser dot and then let's just go left we can go left another 90° and then we can say eraser dot backwards uh is it backward or backwards well I guess we'll see when we run this then by 100 pixels so let me run the code now python tur race. pi and there we go oh so it's saying Turtle object has no attribute backwards that is because this is backward not backwards with the S so just don't add the s for the plural there and let's give this a shot now so python Turtle eraser and there you go that's what happened see we went right uh or sorry went straight then we went left then we turned uh left again but then instead of going forward we went backwards and so we went the other direction so you can kind of mess around with these uh forward left there's also right and inside of these methods here what you're placing is at least inside of the right method is the angle at which you want to turn the turtle so if you want it to turn 90° you put 90 if you want to turn 180° you put that if you want to turn 45 de you put 45 I'll let you guys mess with that on your own and then this the number of pixels is well how far you're moving the actual Turtle so when we open up the turtle window and let me time. sleep for say 20 seconds here just so we have lots of room so I can explain kind of the coordinate system so let's run this let's open up the turtle window all right so this Turtle window is 500x 500 pixels so the height is 500 pixels and the width is 500 pixels now the very middle of this turtle canvas it has the position of 0 0 so the top of the canvas has a position of 250 the bottom of the canvas has a position of -250 the left of the canvas is -250 and the right of the canvas is 250 let me open this up again uh the way this works right is that if the middle is 0 0 and we have a height of 500 then the top y position on our canvas when we're talking about just a standard 2D graph is going to be 250 whereas the bottom y position is going to be -250 so as you increase your y you go up as you decrease your y you go down as you decrease your X you go to the left as you increase your X you go to the right hopefully that makes sense and again - 250 and positive 250 the reason that's the top in the bottom is because the height is 500 I just divided 500 by two and then applied a negative to one of the bounds hopefully that's making sense but that is the coordinate system the reason that's important is because when I say I move 100 pixels uh well we need to understand where that's actually going to move us to and what scale this is on so when I'm moving 100 pixels I'm really moving 1 of either the height or the width of the screen depending on the direction that I'm moving in so we're going to rase our Turtles going up the screen but you could totally erase them going to the right going to the left whatever Direction you want now a few more methods that are useful when we're talking about turtles here are things like the actual icon that's representing the turtle as well as the speed of our Turtle so what I can do here is I can change my Racer Speed so I can say racer. speed and then set this equal to say two now let me actually check what the racer speeds are okay so I just checked what the different Turtle speeds are here you can see that these are the potential speeds we have so we can insert a speed between 0 to 10 and let me just show you this method again we have the turtle object that we've created do speed so we can set the speed of it to be slow or fast because you kind of saw how it was moving around the screen right so if we go here uh oops let's go back to Google we can see 0 to 10 where zero actually means we're going the absolute fast fast as we can possibly go one is the slowest and then 10 is fast so really it's 1 to 10 and then if you input zero it's saying just go as fast as the turtle can possibly move so let's try putting in a value of say two or even one and let's see how slow this Turtle gets when I change its speed so I change it speed let's run and now notice it's moving much slower than it was before there we go that is our Turtle uh oh yes it's going right now because I put that right 90° awesome so let's wait for this to close and then I will show you that we can change say the color of the turtle and we can change what the actual icon looks like and all of that in fact I'm not going to wait for it let's just do it now so if I want to change the icon of the turtle what I can do is say raser dot and then I believe uh I'm actually going to have to look at my other screen here for a little cheat sheet this is the shape that's what it's called so I've been referring to this as the icon it's actually the thing you're seeing on the screen but there's a bunch of different shapes that you can choose for your turtle so I want to make mine turtle but some other valid ones I think are uh Circle we have arrow and then you're welcome to look up the other possible shapes that you have for turtle I can't remember all of them but I know that at minimum two of them that exist are turtle and uh Circle and then obviously there is Arrow as well so sorry those are the three that I know that exist okay so let's change this to a turtle now and let's see what happens this time when I run my program I'm going to remove the sleep because I've slowed down the turtle so hopefully we have enough uh time to see it now so let's run this enter some number and now notice we get an actual turtle moving around the screen awesome so that is good now I will show you how we can change the uh color of the turtle so to change the colors pretty straightforward you can say racer docolor and then inside of here you can put a string that represents the color you want to change this too so there's like a ton of different possible colors here I won't go through them all but for example one is Scion we could do red we could do green we can do blue we can do yellow black orange so on and so so forth so let's just change this to Scion so let's run our code here and notice that now we get a Scion turtle and that the line that it has is Scion as well now there's a ton of other stuff you can do with turtles uh if you want to see all of that I would just recommend you just look up Turtle python like that and then you can see if you go to the turtle documentation here that there's a whole list of all of the possible stuff that you can do with your turtle so I'll be showing you some of this but I won't obviously go through all of it okay so the next thing to show you is what is called turtle. pen up so whenever the turtle's moving around the screen you notice it was kind of drawing that line right and we're calling that the pen so as the turtle moves it's kind of a pen and it's drawing this line on the screen now if we want it to not draw the line but we still want it to move we can bring its pen up so we can say eraser. pen up like that and now you're going to notice when I run this program after I've moved the pen up is that as we move this Turtle around the screen scen no line is being drawn right because its pen is up so what I can do is I can move the turtle with its pen up I can put its pen down and then I can continue drawing so let's copy this line let's move the turtle uh forward by 100 left by 90 and then let's put its pen down so we're going to say eraser. pen dep so let's do this now python Here and Now notice that as soon as it turns that corner then the pen goes down so all this stuff I'm showing you you can change at any point in time you don't have to change before the turtle starts moving or something like that all right so now I've showed you pretty much everything I need to in terms of the different methods for the turtle object just keep in mind you can make as many Turtle objects as you want so I said racer equals turtle. Turtle I can make a second uh Turtle right say Racer 2 and then I can move these turtles in different directions so just to give you a quick example we can copy all of this and then we can just change this to be say raser two and we'll just make racer two a different color so instead of Scion we'll make it say brown like that maybe we'll make it speed a bit faster and then we'll change it so it goes forward like 150 just so you can see the difference in these two turtles so let's change that to be 150 again notice I just had Racer 2 we can kind of copy this and put it down here to separate these things out all right so let's try this now so let's go python turtler race tutorial. py uh let's enter a number of racers three and then notice the first racer is going to move around and then our second guy kind of started moving really quickly right because we wrote All this code after we wrote this code so I'm going to delete all of this just wanted to show you that and now what we are going to do is we are going to pick the colors of the different Racers that we have so once we know how many racers we have we need to kind of create all of these Turtle objects and we need to pick their colors so I'm going to create a list of colors up here in all capital and I'm just going to type out a bunch of them I have a list on my other monitor in case you see me looking over there so I'm going to say red uh we're going to say green we'll say blue blue uh we'll say orange we have if I can get my cursor here correctly yellow we have what's another one black purple we then have pink and I do yellow yes I did what's the last one we have brown and Scion okay Brown and then Scion now note that there is a lot more colors in this I'm just doing 10 for right now so we can have at most 10 turtles so now that we have all of these colors we kind of need to pick after we've uh gotten our number of racers what Turtle colors we actually want to use so I'm going to show you a cool way that we can do this so we can randomly select a bunch of colors from this color list that are unique so at the top of my program I'm going to import random all of these modules are built into python you don't need to install them or anything like that and then down here what I'm going to do is I'm going to say random. Shuffle and I'm going to shuffle my list of colors so all this Capital list right here now what this is going to do is it's going to take the list and just randomize all of the items inside of it so I have no idea where these items are going to go but all of the items that I have here will just be kind of randomly placed around in the list then what I'm going to do is I'm going to select the first number of racers item from this list that that are there and we'll use that as our colors so I'm going to say colors is equal to and then colors and then this is going to be a slice up to the number of racers that we have so let me just quickly explain this we've gotten the number of racers we've initialized the turtle we're shuffling that CS list so just randomizing the order of all the elements there and then what this does is this gives us the first Racers item from the list so if we had a list say 1 2 3 comma 4 and then we put this little slice operator this is what it's called when you use the colon and we set up to say two what this would give me is the first two elements in this list so I would get a new list that looks like 1 comma 2 two now if I did the slice of say three then this would give me the first three elements so 1 2 3 that's kind of the basics of a slice so the reason we're doing that is we're randomizing the list and then just taking the first say number of elements that number is equal to whatever the number is the user types in so now let me show you this we're going to print the cols after the user types in the number of turtles they want to race so let's do this python Turtle race let's in insert five and then notice it kind of popped open that Turtle window closed it and then it printed yellow purple green orange brown now if I do this again and I type five you're going to notice we get different colors right and they're in a different order so black red orange brown scon now this uh 100% will always select unique colors for us so we'll never have turtles that have the same color all right now that we have all of the colors we want to create all of these turtles so we're going to make a new function here we're going to say Define and then create uncore Turtles now inside of here we're going to create a list of turtles and then we are going to kind of place them on the screen in their starting position so ideally we want to have all of the turtles evenly spaced out at the bottom of the screen and kind of pointing upwards ready to start racing so let me show you how we do that well the first thing that we need to do here is we need to determine what colors our Turtles are going to be and how many turtles we're going to have so this function as a parameter is going to take in colors so we are going to pass this function when we actually decide to call it the number of colors that we have and then what that's going to or not the numberers sorry just the colors that we've actually selected and by having this list here we will also know how many turtles we have because the number of elements in this list will tell us the number of turtles that we want to race so now what we're going to do is we're going to say that Turtles is equal to an empty list then we're going to Loop through all of the colors that we have and for every single color we're going to create a turtle and add it into the list the reason I'm creating a list is because I don't know how many turtles I'm going to have so I can't just Define variables with like you know I can't find four variables for four different turtles or five variables for five different Turtles I need to kind of dynamically create these turtles because again I don't know how many I'm going to have so I'm going to Loop through now all of my colors I'm going to say 4 I comma and then color in a numerate and this is going to be colors and what a numerate does is it gives me the index as well as the value of all of the elements in colors so if I'm looping through colors let's say like red and then green then what's going to happen is on on my first for Loop iteration I will be equal to zero that's the position of this color color will be equal to red and that's great then on my next iteration I will be equal to one and color will be equal to green and if I had one more iteration say this was blue then I would be equal to two because this is the third element or the second index SL position and then the color will be equal to Blue so that is what a numerate does gives us both the index and the value now what I want to do is create a turtle so I'm going to say raser is equal to and notice you can name these variables plus whatever you want and I'm going to make this equal to turtle. Turtle just like we saw previously and then immediately I'm going to change the color of this Turtle to be whatever color this is so I'm going to say eracer do color and I'm going to make this uh oops if my Sublime Text stops crashing okay it's crashing so I'll be back after this stops crashing all right so I am back that was really annoying Sublime Text just crashed on me but I have eraser docolor and I'm going to set this color to be equal to color the reason I'm setting it equal to color is because this will be a string this string will come from this list of colors right here and so every one of our eracers will be a different color then what I need to do is set a few other things I want to set the shape so I'm going to say eraser. shape and this is equal to a turtle then what I want to do is place this racer in its starting position now before I do that I'm going to show you where they placed initially but I also want to turn these Racers so I want to say eraser. left by 90° now the reason I'm doing this is because by default the kind of arrows or whatever are pointing to the right so if I want them to point upwards cuz I want to race my uh Racers upwards and my turtles upwards then I need to turn them left by 90° so I'm going to take my Eraser or make my Eraser which is just a turtle I'm going to set its color I'm going to set it shape I'm going to set it's kind of heading so it goes in and is facing upwards and then I'm going to add it to this list so I'm going to say turtles. append and then I will append my Eraser this way I have access to all of my turtles and then later on I can actually say move these Turtles forward right and we'll move them by a random amount and that will kind of simulate these Turtles being raced now I'm just looking at my other screen here one more thing that I'm going to do here is I'm actually going to put my Racer's pen up so I'm going to say eraser. pen up and then immediately going to say racer. pen down and inside of here I'm going to set the position of my Eraser so we'll just say set pause and we'll do that in one second all right so now let's run this code here so python Turtle race tutorial Pi let's insert a number let's say three and what happened ah well we need to call this function if we want to see anything happening so after we get our Colors Let's call create Turtles and let's pass our colors so now we'll have all the colors here we'll Loop through them and create our Racers for each all right so let's run this python Turtle race let's go five and notice when I do this it kind of spins up five Turtles they they you know Spin To the Left they're all different colors and then it's done so obviously this is not ideal right all my Turtles start in the middle of the screen and so I need to move them so they are at the bottom of the screen now I could move them like backwards turn them left move them to their correct position but that's kind of a pain so there's this method for our Turtles called set position uh actually let me make sure it's called that yes it's called set pause so eraser. set pause and this takes an X and Y value and will set the position of your turtle to well this position so this is why I'm putting the pen up then I'm going to set the position then I'm going to put the pen down so when I move this Turtle to its position I don't draw a line from the middle of the screen to wherever it goes because that's just not optimal that's not ideal that's not what we want to do here so inside of set paw I need to choose an X and A Y value for my turtle now the Y value is pretty easy because all of my turtles will start at the same Y and then they'll kind of increase their y as they race upwards so we know what the yv value will be or we can just pick some random yv value but what is the x value going to be well I want to space these Turtles out completely evenly right so let me open up my kind of Windows ink pad here uh where even is Windows Inc H okay so I've just opened up paint here I unfortunately couldn't find the windows ink thing that I normally use I don't know where they would have HIIT it from me but anyways apparently it's gone so go easy on me I'm just using my mouse but I'm going to illustrate what we're going to do here so we have our canvas right now our canvas is of size 500 by 500 but to make math a bit easier we're going to say it's 400 uh by 400 again my Mouse is really hard to draw with okay so 400 by 400 now we want all of our Turtles to kind of be placed near the bottom of the screen so to pick this position is pretty easy we can kind of just take like the height of the screen we can divide it by two we can add a small value to it and then we'll say all right well that's where we want to place the turtles at that negative coordinate because right here in the middle is 0 0 right so as we go down this is negative so if we place that -200 they'd be like right at the bottom of the screen so we can move it up like 10 pixels and then that would bring us to this kind of red line that we have right here now the question becomes though what are the X values of our turtles so obviously we want our Turtles to be kind of spaced out if we have two turtles we probably want them somewhere like here and here right want them equal distance from each other and then equal distance from the edge of the screen now I know this isn't exactly equal distance but hopefully you're kind of getting the idea now if we have three Turtles we want one guy in the middle one guy here and one guy here this way they're equidistance from the edge of the screen and from each other so how do we figure out the x positions well what we actually need to do is we need to figure out first of all this spacing between our Turtles then what we can do is we can start our first turtle at whatever the spacing amount is we can then add whatever the next spacing is to what our next Turtle then our next spacing and so on and so forth so how do we figure out the spacing between the turtles well we actually take this number right here sorry this number right here which is the width of our screen and we divide it by the number of turtles that we have plus one so I want you to see this example if we take 400 and we have four turtles a lot of people would say well the spacing between each Turtle should be 100 pixels now the reason why that would actually be incorrect is because that would assume the first Turtle starts at the far left hand side of the screen so if I put my first Turtle right here and then I go 100 pixels over my next turtle is at position 100 right if we're talking about the X then my next guy comes over here and he's at 200 and then my next guy comes here and he's at 300 it's really hard to do a three clearly this is my attempt at a three okay so 100 200 300 and then this first guy's obviously at zero so we don't want that we want to kind of shift this whole line over so there's equal distance between all of the turtles and the edge of the screen so what we really need to do is we need to divide this number by five and then we need to start our turtle at the first spacing position so if we take 400 and we divide this by five oh God this is testing my math skills 400 divid 5 should give us a value of 80 yeah I think 80 is correct 8 * 5 yeah 40 400 yeah okay 80 is correct so now if we do this at 80 let me kind of erase all of this here we'll say that our first Turtle gets placed at position 80 so the first guy goes right here uh should I even attempt to do an eight okay we have8 zero then our next guy is going to go at 160 and then we'll move over again and then our next guy is going to go at 240 our next guy will go at 320 and then this will be perfect we'll have our four turtles they'll be equal distance from the edge of the screen and equal distance from each other now I know this seems like they're not equal distance because I've kind of dro on this not to scale but that's the idea behind this so hopefully this long explanation gave you the idea of what we're doing we're going to divide the value that we have here by the number of turtles plus one then we're going to place the first turtle at spacing um position so whatever the spacing is so starting at 80 the rest of them will go up by the increment of spacing every time so we'll leave that kind of open in the background in case we need to refer to it again but this means we are going to set the position and we need to figure out the turtle spacing so I'm going to say spacing X is equal to and then the L of colors this is the number of turtles that we have right plus one we're going to put these in parentheses and we're going to start by dividing the width by two so we're going to say width divided by two sorry not width divided by two width divided by the Len of colors plus one so whatever our width is we divide it by the number of turtles plus one which is really just the number of colors that were given to us and there we go so now where do we want to start placing our Turtles well what I was showing you before as I was saying with placing at 0 80 so on and so forth the only issue with that is that when we're at the left so we're to the left of the middle of the screen we're at a negative coordinate right so really when we're dra drawing the kind of coordinate axes here this is 0 0 so as we're over here we're in the negatives so that's fine all that means is we need to add the negative width over two uh as our starting position to all of these right here so the first position for our Turtle will actually be at negative width over two plus this value right here the reason that will work is because we will subtract this by -200 and then -200 + 80 that will be equal to uh what is this 120 120 then we will go and be equal to -40 then we will be equal to 40 then we will be equal to what's 80 + 40 120 and that will work and and that will still give us the equal distance and it will just kind of translate everything over to the left which is what we want it to do so so hopefully that's making sense we just need to account for the negative coordinate system so we're going to set position at negative width over two and then we're going to add to this I + 1 Let's guess why we need to do that in a second multiplied by and then the spacing X so this will be our X position and our y Position will be equal to negative height / 2 plus 20 pixels now this is kind of an arbitrary value I'm deciding I'm saying we want to be 20 pixels from the bottom of the screen so we take the negative height divided by two and add 20 the reason we have the I + 1 is because we start indexing at zero so the first cutor is zero really want to make that one because remember we want to place the first turtle at the first spacing position so negative width over two plus whatever the spacing X is that's where the first Turtle should go then the second Turtle well that will be a one so that will give us two so then we'll be at the second spacing position then the third then the fourth so on and so forth so this should place our turtles in the correct position let's see if it does so so let's run our code here and let's say we want to have eight turtles so we have eight Turtles notice that now we're going to move the turtles they are perfectly aligned on the screen and they have equal spacing between each other and between the edges so that's awesome now all we need to do is just return our Turtles like that and now that we've created the turtles we've placed the turtles we've picked our colors and the number of turtles that we have we can start finally racing them on the screen all right so now what I'm going to do is create a new function I'm going to call this function race and this function race is going to take in our colors now I'm going to change kind of the flow of our program a little bit let me zoom out here so you guys can kind of read more of what's going on so right now what we're doing is we're getting the number of racers we're initializing our Turtles we're picking the colors and then we're creating the turtles that's great but I don't want to create my turtles until I'm ready to erase them so I'm going to take this create Turtles kind of function call here and I'm going to put that inside of this race function now the idea is that we're going to pass the colors to race and then race will create our Turtles for us so we'll say Turtles is equal to and then create turtles because this function Returns the turtles so then inside of here we will create all the turtles using our colors and the reason this is important is because I want to know what color every turtle is and by having access to colors and turtles I can do that so now rather than calling create Turtles down here we're just going to call Race so we're going to say race and then cols and then this will create our Turtles for us and then in here we can race them so after I create my Turtles I want to start racing them I want to start moving them so I'm going to say while true and then I'm going to move all of my turtles one by one now the idea behind this is that we don't know how long it's going to take us for our Turtles to get to the top of the screen so what I need to do is have a while loop because I need to keep moving them until eventually one gets to the top of the screen so inside of here I'm going to say for racer in Turtles and then what I'm going to do is move this racer so I'm going to say racer Dot and then move and sorry the shouldn't say move this actually going to be racer. forward because it's now facing the correct direction it's facing up so when I move it forward that's the direction it's going to go in so racer. forward and then I want to move it forward a random amount so I'm going to say move is equal to or maybe distance is a better variable name distance is equal to random Dot and then Rand range and inside of here we're going to put the minimum and maximum amount we want the turtle to possibly move at every iteration so I'm going to say 1 comma 20 and what this means is every time I decide to move my turtle I'm going to move it by either 1 or 20 pixels or sorry between 1 to 20 pixels so it will randomly generate a number that is between 1 and 20 and move the turtle uh that amount that's what Rand range does so you can make these values whatever you want the larger you make this minimum value the faster your turtles are going to move and obviously the larger you make this one the higher probability your turtles are going to move faster but really this minimum value will dictate kind of the slowest speed of the slowest Turtle right so just keep that in mind I like to keep it at one so that the race kind of looks like they're like kind of inching forward rather than having big jumps every single time anyways we're going to say racer. forward we're going to move it forward the distance now once we've moved our racer forward what we want to do is check if this racer is kind of past the finish line so the reason We're looping through all the Turtles first of all is because we need to move every single one of them we have a list of turtles Right we've created all of these Turtles here stored them in a list now we need to move every single one of them so we Loop through all of them and then we move them now for every racer we check if it's past the finish line so I'm going to say x comma Y is equal to racer. pause what this does is give me the position of this Turtle so I know the X and the Y I don't care about the X I just care about the Y I'm going to say if Y is is greater than or equal to and then height and this is going to be divided by two and we'll subtract 10 here then what I want to do is I want to say that this Turtle crossed the finish line that it was the winner so to do that I'm just going to return this turtle's color so if this Turtle pass the Finish Line then it is the winner what this function is going to do is it's just going to return whatever the winning turtle is it's going to return the color of the winning Turtle so we'll say return and then here we will return and this is going to say colors at index I now this may be a bit confusing but the idea here and oops index I I can't even use that um okay I'm going to show you a different way to do this I thought I had coded this in a different way I'm going to say colors at and then this is going to say turtles. index Turtle so this may be a bit confusing if you guys haven't worked with list before but this is the rationale we want to find the winner or sorry the winning Turtle color want to know the color of the winning Turtle so to do that we need to access its color now I don't think there's a way to get the color of a turtle from the actual Turtle object I may be wrong on that but all we have access to here is just the turtle right we have the turtle that we're moving that's all we have so this kind of turtle. turtle that's all we have so the question then becomes okay how do I find the color of it well I have the colors of all of my turtles here so what I can do is I can find which turtle or the index of the turtle that was the winner and then I can use that same index to figure out the C of it in this colors list so think of it this way if I have a list of colors I have like blue and red and then I have my two turtles right so let's just say I have turtle turtle one and I have Turtle 2 well Turtle 2 is at index uh one right so we have index zero and index one so Turtle 2 is at index one so if I can find the index of this Turtle all I have to do is reference that same index in my color list and that tells me the color of it right same thing for turtle one well Turtle one's at index zero its color must be index zero in the colors list this expands with any length of turtles so what turtles. index does is notice this is the name of the list I'm then passing the turtle that I'm looking for the index of it tells me the index of this Turtle so and sorry this should be changed actually to be racer that's my bad I was probably confusing you guys there but we have access to the turtle so we say turtles. index racer gives us the index of this Turtle object in the turtle turtle's list we then use that same index on the color's list to reference the color of that turtle and we return it so not really much more I can explain there that's probably the best that I can do for that we're going to return the actual color now that we have the color down here we'll say winner equals race and then we can just print out winner the idea being that this function is only finished once we return this color so just in case you're aware or just in case you're unaware sorry in a while loop whenever you return something or just in a function in general as soon as a return statement happens the function immediately stops so even though this is inside of a the walloop will stop running as soon as one of the Turtles has one so let's just run this code let's just see if this works then I can explain to you some more kind of details about this so let's go here python Turtle race let's go with five turtles so we're going to create our five Turtles and then they're going to start racing so they kind of start racing up the screen notice that they're drawing every single time and then boom it says pink the reason it says pink is because if you saw pink was the first Turtle to cross the finish line now it's worth noting here that there is a little bit of a bias in the uh the first Turtle so the very first Turtle has a very very small probability of finishing uh earlier than all the other Turtles like it has a better chance of doing that in a sense because it's the first turtle that we move we have to move the turtle sequentially like we can't move all of them at the exact same time so we move the first Turtle then the second Turtle then the Third Turtle than the fourth Turtle we check if any of them are past the Finish Line whatever one crosses first we say that's the winner so it's just a higher probability that the very first Turtle we move will finish first so the last Turtle kind of has you know the least chance of winning but based on this Randomness here uh it ends up kind of counteracting that in some type of sense so hopefully you get what I mean I'm not going to worry about that for this problem right here if you guys were concerned about the fact that one Turtle has like a little bit of bias which it kind of does what you could do is is you could see if one Turtle crossed the finish line and then if a turtle crossed the Finish Line you could still move every other turtle and whatever Turtle moved the furthest so was like the furthest past the Finish Line that's the one that you would say would be the winner there's no way other other than that to really kind of fix this problem uh so anyways that is really all we need to do here like that that is it for this program so the last thing I'm going to do is I am going to print out in kind of a nicer way what the winning turtle is so I'm going to say the wi Winer is the turtle with color colon then comma and I will say winner so that's all we'll do so now we just have a nicer kind of output message saying this was the winning turtle and then I'm going to say time dos sleep and I'm going to sleep for 5 seconds just so that we have a few seconds to actually see which turtle was the winner before we just go ahead and close the program so hopefully that's clear but yeah that's really all we need so let's run this let's go with 10 Turtles this time and let's see what we get let's just enjoy the turtle racing show okay so they're going to race you're going to notice the more Turtles you have kind of the slower they go just because we have to move every single turtle one at a time we can't move like a bunch of turtles you know like the more Turtles we have the more we have to move in so the longer it takes to run that's what I'm trying to say but we saw that the winner is the turtle with color green let's run this one more time with two turtles and you'll see that it goes like way faster because it's just these two guys that need to move purple was the winner and then if we kind of go back into CMD it says the winner is the turtle with color purple awesome so I think that's really all I need to show you here now all of this code will be available to download from the description in case you got lost or something's not working but hopefully I did a good job at explaining a lot of these Concepts hopefully you guys kind of learned how you can lay out a I don't want to say large but medium-sized Python program that has more than just a few lines of code and you get the idea behind these functions right so now now at this point if I want to go change something like say I want to change the width of my screen since I used this width variable everywhere in my program and everything I did was very Dynamic right I had like height over two I had width over two if I change the width up here now everything will just work right like if I change this to 700 and I change the height to 600 doesn't even have to be square let's just run the program again let's go with six Racers and it's still going to be evenly spaced out on the screen right just because the way we did this is everything was Dynam dnamic it used the variables and we set it up in a way where if we made any changes later on it wouldn't completely ruin or mess up our program and what does it say the winner is here the winner is turtle with color blue so just keep that in mind hopefully you appreciate that kind of detail in in writing this code uh and same thing here even with like validating the input right we're going to keep asking the user for a valid input until they give us something that's valid and then race uh we're using another function inside of this function we could have just took take uh tooken taken whatever all of this code and placed it inside of here but if we did that then if we wanted to change the way that we were creating our Turtles well we we could do that but it would just be a little bit harder and if we wanted to say use this function anywhere else same thing just wouldn't work as well so this way it's really easy to see laid out very nicely and this is just a better style of coding than writing everything in one line right because we could have written this entire program in just one line like we didn't have to use any functions it could have just all been in the main line of the program but then it wouldn't be very clear to see what part of the program was doing what so you can see here I have my terminal open it says welcome to this typing test you'll be given a block of text and need to type it as fast as possible press any key to start so I'm going to start and it's going to bring up the text like this now I'm not going very fast right now but the point is that we can just type the text and if I get something wrong so notice I'm getting something wrong here it's highlighting in Red so this is something that you know you probably don't already know how to do and that is pretty simple actually but I'm going to show you how to do in this this video how to get all the text highlighting and kind of nice styling as you see here and then the ability to clear the entire console so you can see here it says you completed the text your wpm was 55 so I'm going to hit enter and it says you want to play again let's play again brings up some text it actually does randomize the text but in this case we just got the same text that we had before anyways there you go that is the demo of the project now we're going to hop into the code I'm here in my text editor I'm going to be using Sublime Text for this video not really that important you can use whatever you want anyways what I've done is opened up a folder and then inside of this folder I have a file called tutorial. now I'm going to recommend you do the same thing make a folder somewhere probably put on your desktop put a file inside of there that is a python file and then you are good to start working now as you guys saw we had some really nice styling for our terminal we had some different colors and we were able to kind of write over the previous text now the way we were able to do that was by using this module called curses now this is built into into python if you're on Mac or Linux but if you're on Windows you actually need to install it so if you're on Windows you need to follow along with this step otherwise skip forward into the video until we actually start writing some code okay so if you guys are on Windows what you need to do is open up your command prompt here and we're going to type the following command to install the windows version of this curses module we're going to say pip install and then this is going to be Windows hyphen curses like this so you should run this command and it should install this for you and if for some reason reason this command does not work for you I will leave two videos on the screen they'll be linked in the description as well and there'll be cards on the screen showing you how to fix this pip command now they're called how to install pame just follow along with the exact same steps except instead of installing pame you're going to install Windows curses now you also can just try here pip install and actually sorry this python hyphen M pip install and then Windows hyphen curses like this and see if this command works for you and if this doesn't work then again and follow along with those two videos anyways this should install the curses module and once you have the curses module installed then we are ready to go okay so I have curses installed and this is what allows me to do the styling of the terminal so the first thing I want to show you how to do is just to use this module and to kind of print stuff out to the terminal because it's going to be different than what we typically do we're not going to be using the print and the input statements we're going to be using some statements from this module okay so the first thing I'm actually going to do here is write a other line and I'm going to say from wrapper or sorry not from wrapper from curses import wrap now what this is going to do is give me something that allows me to initialize this curses module because when I initialize the module what's going to happen is it's going to take over my terminal and it's going to allow me to kind of run some different commands on it so I use this wrapper it initializes curses and then as soon as I'm finished with the program it will kind of restore the terminal back to its previous state so it's pretty important that you do this anyways what I'm going to do here is say Define Main and inside of main I'm going to put a variable here which is going to be called stdr standing for STD screen now STD is your standard output so the standard output is just kind of the terminal it's where you're writing stuff out to and what this module does is kind of take that over and give you a screen over top of it that allows you to write stuff to the screen anyways that's what this is doing so it is the standard output screen okay perfect so now that we're inside of here for now what I'm going to do to show you the most basic thing which is just adding text to the screen the way you do this is you say stdc do add and then string like that so then inside of here in quotation marks you just put the text that you want to print out to the console so just like a print statement I'm going to put the text hello world okay that's it this is just going to Output the text for you then what I'm going to do here is I'm going to call rapper and then pass my main function now this might look a little bit confusing what I'm doing is I'm passing this main function to this this wrapper function so this actually a function I just call it like this using the parenthesis I pass main inside of there and it's going to actually call this function while initializing all of the stuff related to this module so anyways that's the first step all this is going to do is print hello world out to the screen now before I do that though I actually want to clear the entire screen because if I don't clear the entire screen we're going to have a bunch of junk on there so what I want to do is I want to say stdr dot and then clear this just clears the entire screen for me and then as soon as I do anything so I add text I need to refresh the screen so the way I do that is stdc Dot and then refresh like that perfect okay so this will actually print hello world out for me all right so now that we have all of this I actually just want to add one more line here I'm going to say Str Str or sorry std. strr Dot and then get key like this with two parentheses what this is going to do is just wait for the user to type something so that way it doesn't immediately show this and then close the screen because right now if we run this code what's going to happen is it will print hello world it will refresh we'll see it for like a millisecond and then it will end we need to add this get key so that we don't immediately close the program we wait for the user to type something and then we finish it okay so now that we have that we can run this code now to run this code is a little bit trickier than your standard python code you actually need to run it from your terminal or your command prompt that's because this requires a terminal or command prompt to actually show you the correct output so what we're going to have to do here is open up a command prompt or terminal again depending on your operating system we're going to have to get our working directory which is right here on the Le hand side into the folder where this file is I'm going to show you a shortcut on Windows here to do this and on Mac I'll describe kind of how you can do the shortcut obviously I'm not on Mac so I can't quite show it to you okay so I'm going to open up my Windows Explorer here and I just have it on my other screen right now I just need to hide some of my files and what I'm going to do is navigate to The Path where my file is so I assume you know where your file is I mean you should know where you placed it and anyways you can see here that my tutorial file is directly inside desktop and then beginner project so what I'm going to do is click on this menu bar here so notice where it's showing the path I'm just going to delete all of this and type CMD now when I do that it's going to open up a command prompt and notice the working directory which is on the left here is directly inside of beginner project so all I'm going to do now to run the code is type Python and then the name of my file which is tutorial. P now I'm going to hit enter and when I do that notice it shows me hello world and when I hit enter again it brings me back to my terminal okay that's how you run the code now if you're on Mac you can do a very similar thing you can open up your finder you can navigate to where your python file is and then you can rightclick and there should be something that says open Terminal now if you can't find open Terminal what you're going to have to do is use the following commands CD like this so CD stands for change directory and to go to The Parent Directory you type CD do dot so notice that brings me to desktop that's the Parent Directory of beginner project then if I wanted to get into beginner project I would type CD and then beginner project like that it would bring me into that directory so from wherever you are you need to change your directories into the correct directory where your python file is and then type python space and then the name of the Python file you want to run now for some reason that doesn't work type Python 3 and then the name of the file so for me it's tutorial. piy but for you guys it will be probably something else hopefully that clears it up it's hard to explain that more because I'm not actually on Mac but you need to open up a terminal and get this directory here on the left hand side to be the directory where your python file is or what you can do is you can look for the exact path of your file and type Python and then put the exact path so it would be on Windows something like C colon slash and then the path to it or on Mac maybe Python 3 and then the path to the file anyways that's pretty much all that I can explain for right now but that is how you run this code okay so now that we know how to run this let's talk about how we can add some colors here and kind of style it a little bit all right so if we want to add color to our text what we need to do here is create something known as a color pair now a color pair is just a foreground and a background color so the foreground is the text the background is obviously what's behind it so what I'm going to do is I'm going to create a pairing of a foreground color and a background color and then use that pairing to print out my text so I'm going to say curses Dot and then a knit underscore pair at the top of my function here and it's important you do it in the function if you try to do it outside it's not going to work you can only do this once you've initialized curses and that's going to happen when we call this wrapper function and then it calls the main function anyways I'm going to say curses. AIT pair I'm going to put the ID of my pair which is going to be one and then I'm going to say curses Dot and then this is going to be colorcore and then whatever the color of the text is that I want so in this case I'll go with green for my foreground color and then for my background color which is is the second color you pass going to say curses Dot and then we'll go with color underscore and let's just go with white so that we can see kind of you know a lot of color here okay so what I've done is I've said that I want to have the pairing with the foreground color green and the background color white be represented by the id1 so I need to put an integer here and this integer kind of represents this pair so if I wanted to make another pair then what I could do is the same thing and I would just change the integer here to be two if I had it at one then it would override what this pair was so I wanted to change it to two and then I could make this something like color dot and then can we go with yellow uh let's go all capitals yellow and see if that's a valid color okay so now we have a pair with one and two as the ID so to use this what I'm going to do is go inside of my ADD St here and I'm now going to reference this pair now the way I do that is I say curses. colore pair like this and then inside of the brackets I just put the ID of the pair I want to reference so if I want it green and white then I put one if I wanted it yellow and white then I would put two and if I just wanted the default color I just remove this I don't need to include it anyways let's give this a test here and see if this is going to work so I'm going to go to my terminal and go Python tutorial. py and notice we get green text with a white background then if I hit any key it's going to escape and bring me back to the terminal perfect let's try this now with the color pair 2 and run this and notice we get yellow text on a white background that looks pretty ugly but that is fine so for now the pairs that I want to initialize are actually just going to be red uh let's go with blue no do we want blue no let's just go with red green and white and then we can use those pairs throughout the program so I'm going to say curses. niit pair one green is perfect but for the background I want the background to be black then I want one that is going to be red so I'll say color red and color black and then I want my last color just to be the standard white text so I'll go three and then this will will be color white like that okay perfect and for now we don't need to add any color to that okay so now we have our three colors we have one which is green two which is red and three which is white so now that we've looked at the colors the next thing I want to show you is how we can locate text differently on our terminal or kind of place it in a different place based on where we want to put it so in this STD uh sc. add string method that's a mouthful what we can actually do is specify the position so kind of the row and column that we want to start this text app so I'll show you what I mean but for now if we go with something like 1 Z what this is actually saying is I want to go one line down and start at the zeroth character so start all the way furthest to the left but one line down so you go kind of your row and then your column that's how this coordinate system works now you'll see very quickly how this works it's pretty straightforward but if I run this notice that now we're just on the second line down in the terminal so it's very easy to kind of place text in different places now if I go and do this like five you're going to see that now we're going to be five characters over to the right so if I run this now we're one row down five characters to the right so we start writing from that place okay hopefully that is clear now let's just see what happens if I actually write something else so let's write this at like one and then zero and see what happens when I kind of have two colliding pieces of text so let's do this let's hit enter let's run the code and notice that the hello world I wrote second kind of overrides what was already on the screen so that can happen and that will happen based on how you're writing stuff out and that's exactly what we're going to do to kind of have our green text go over top of the white text when we're trying to type out the target text uh when we're doing kind of our speed test right so I just want to show you that you can kind of pick the location on where you want this text to go you just pass before the text uh the coordinates so you go either the row and then the column that you want to place this in and if you just want to be at the top left you can just leave it you don't need to add anything or you can explicitly say 0 0 like that okay so now we have pretty much gone through everything in the curses module the last thing I'll show you is that we can actually get the key that people type so notice here that I said stdr doget key so what I can do is store this in a variable and just print this out and now this will actually tell me the key that the user typed in and you'll see why this is important in a second but we're going to need to register the user's keystrokes so that we can see what they're typing and keep track of their word per minute right so that's what key will do for us we'll get the key that the user types so let's go uh to our terminal looks like I closed it so I'm going to have to open it again okay so I've got the command prompt open now and I'm just going to run this code so python tutorial. piy I'll hit the key e and then notice it prints out e because that's the key that I hit okay now we've gone through the curses module now I want to start kind of building this speed test or this game or whatever you want to call it so the first thing I want to do is kind of have a start screen here that says hey would you like to play the game and if they say yes or they hit any key then we will you know like continue with the game and we'll get into the game so I'm going to write a function here I'm going to say Define startor screen and this is going to take the stdr now the reason we need to take this is because we need to have access to this object to be able to write to the screen because notice we're using the add string method we're using clear we're using refresh so we just we need access to this to be able to actually write something onto the screen using the curses module anyway what I'm going to do is I'm going to steal these lines right here so clear add string and refresh and I'm just going to put them inside of start screen and what I'm going to say is press any key to continue and I'll give kind of a description of the game so I'll say welcome to the speed typer test or whatever uh speed typer test speed typing test maybe uh and then we can do a new line so let's get rid of this here and let me show you how we can print something on a new line so we can use the coordinate system we can do something like 1 comma 0 or what we can do is we can print this character which is a back sln now when you print a back sln what this does is it brings the cursor down to the next line and you're going to start writing wherever the cursor is so after I print this out my cursor is going to be at the end of this line and if I were to print something else so I were to do this line here it would go right after it kind of be squished together but if I wanted to go down to the next line I can put in this Escape character called back sln this is the new line character and it makes me go down to the next line before I start typ so now I'll say press any key to begin okay welcome to speed uh typing test press any key to begin boom and then what I will do is refresh the screen and I will just say key is equal to this and I actually don't even need to store the key I just want to wait for the user to type something so that's what I'll put right here okay that's awesome so now what I can do is just call this start screen function from inside of this function right here so I'll call start screen and I'll pass the STDs strr like that and now what will happen is when I run the main function we'll initialize our colors we'll call the start screen we'll do this and then we'll continue so let's test this out before we go any further let's go Python tutorial up Pi welcome to speed typing test press any key to begin boom and then we begin okay so now that we've done that we need something to kind of store what our Target text is we want to print that Target text out to the screen and then ask the user to start typing it in so I'm going to make another function here and notice I'm kind of splitting all of my codee up into different pieces of logic that's a good practice you should try to get in the habit of but that's what I'm trying to show you here anyways I'm going to say Define wpm test standing for words per minute test we are going to take the STD sccr like that and inside of here we're going to actually print out kind of what our Target text is and then get the user to start typing it in so I'm going to say Target unor text is equal to and for now we'll go with hello world this is some test text TT for this app exclamation point and this is what we want the user to type in so we want to print this out and then we want to print whatever the user has typed kind of over top of it which you'll see in a second so now I'm going to say current text is equal to and I'm going to make a list you'll see why we need this in a second and for now all I'm going to do is clear the screen refresh it and then uh actually print what this text is so we'll start with that and then we'll kind of keep track of what the users actually typed so I'm going to steal again these lines because we just going to keep read using them and I'm going to say uh std. add string and rather than welcome to speed typing test we'll just put the variable Target text in here because this is what we actually want to display so we're going to get the target text uh which is this we're going to have our current text which will be what the user has typed we're going to clear the screen add this to the screen and then refresh and then again we'll just get key okay so now after we get past the start screen what we want to do is call the wpm test function like this and pass this okay so let's give this a run and see how this is working python tutorial. piy let's hit enter no it says hello world this is some test text for this app and when I hit enter or any key for that matter then it exits great so now that we've done that what I want to do is actually register the user key presses and then I want to take whatever they're typing and kind of overlay it on top of this so as you saw in the demo if they type the character correctly want it to show up green if they type it incorrectly I want it to be red okay pretty straightforward so what I'm going to do here is I'm going to start a while loop so I'm going to say while true and I'm going to continually kind of ask the user to type something in and every time they type something I'm just going to Overlay it in a different color on top of the target text so we're going to have to change this drastically from what I do right now but this is just an example so you can see how this is going to work so what I'm going to do is say key is equal to and then STD SC Dot and then get key which means I can remove this one right here because we're immediately going to jump into the wall Loop and then we'll get the key then I'm going to add this key to the current text and I'm going to draw the current text onto the screen so I'm going to say uh let's go current text like this do append and I'm going to append the key so we're going to have a list of all of the keys that the user has pressed then I'm going to Loop through every single one of these Keys using a for Loop and I'm going to kind of place that character onto the screen so I'm going to say four and we're going to go with Char standing for character in and this is going to be current text what I'm going to do is say stdr dot and then this is going to be add string we're going to add whatever this character is comma and then I'm going to put the color that I want this to be so in this case I want the color to be uh let's go with green so that's going to be pair one so what do I need to do I need to say curses Dot and then this is going to be color underscore pair one okay so let's just go through this quickly to make sure everything is clear so what we're doing is we have the target text we have the current text we are clearing the screen we are adding the target text to the screen we're then refreshing the screen we're then going to ask the user to enter a key so when I say get key this is going to wait for them to type something as soon as they type that we're going to append that to the current text then we're going to Loop through every single uh character that they've typed cuz they're going to be storing that in a list so for chart in current text we are then going to display that character on the screen so we're just going to add it and it will be in a different color okay now one thing that I want to do here is I want to constantly do this so you'll see why I want to do this in a second but I'm going to go here and I'm going to add this string the target text and then after I add the other string I'm going to refresh so I'm going to clear the screen every single time this wallet runs I going to add the target text to the screen I'm then going to add the other text onto the screen so whatever the user has typed in a different color and then I'm going to refresh the screen so that you see it so this way I'm not going to continually keep adding the same text to the screen I'm going to clear everything and then add whatever I currently have if the user adds another key I'll add that as well you'll see why I need this but I'll show you if I don't clear uh what's going to happen in one second anyways let's run this and let's just see what's happening so it says press in a key to begin okay so hello world this is some t text for this app and now let's just type something so let's go H and notice it's showing up on a new line all of the characters that I'm typing so that's exactly what I expected now if I didn't clear the screen what would happen is we would uh write all of this like multiple times onto the screen so let me show you this I'm just going to get out of this um actually we didn't even make a way to exit this so I'm going to hit control C okay that doesn't work uh we're going to have to just close the terminal because I didn't make a way to exit yet well we'll have to do that in a sec anyways if I don't clear the screen here and we rerun this so let me go to my terminal so CMD CD desktop CD beginner project and python tutorial. py now watch what happens when I start typing okay so first of all you can see that it didn't clear but if I type this it's going to repeat all the text a ton of times right because we're not clearing what we previously had we just keep adding what we had to the screen so that's kind of what I was getting at that's why we need to clear so anyways let's make sure we include this clear and now what I want to do is include some way for the user to actually exit the program so I'm just going to check if the key that they hit was the Escape key and if they hit Escape I'm going to allow them to exit because obviously we want some way to get out of this program so before I add this to the current text I'm just going to check if the ordinal value of this key and I'll explain what that is in a second is equal to and then 27 now if it is I'm just going to break what break is going to do is just get me outside of this wall so it will break this infinite Loop now the ordinal value of a key is its numeric representation on your keyboard so every single key on your keyboard has some number that represents it and this number is known as the asky representation or the Unicode representation you don't have to really know what that means asky stands for American Standard um something something something I think it's like American Standard code information whatever someone smarter than me in the comments will tell you what it stands for I forget or maybe I'll throw it up on the screen point is every single character has some number that represents it so I know that the character lowercase a is represented by 97 uppercase a is represented by 65 and it just so happens that escape is represented by 27 so we're going to check the ordinal value when you take the ordinal value of an individual character which is what the key will be it will give you what it is so if it's 27 then we'll break that means they hit the Escape key okay hopefully that makes sense we can test that out though so let's open up our Command Prompt so so let's CD to desktop CD to the beginner project and then go Python and then tutorial. piy and now if I hit Escape notice I'm going to exit and I am all good perfect that is exactly what I wanted now one thing I will do here is I'm going to show all of this before I ask the user for a key the reason for this is right now I'm having to hit the key kind of two times before it shows anything so I want to show this first and then ask the user to kind of type in a key and when they type in that key then we will add it to their current text now one problem that we're going to run into here is that there's a bunch of special keys that the user could hit for example the backspace if the user hits the backspace I don't want to display the backspace character I actually want to remove one of the characters that they typed now since we're kind of doing this in curses we have to manually handle all of this so when I hit backspace is not just going to move me back it's actually going to show kind of a really strange character on the screen so let me show you what I mean but if I run this code so python tutorial. piy let's hit enter and let's hit the backspace you notice that it's bringing my cursor backwards but if I start typing stuff here it's not actually going to delete that stuff right it's just bringing the cursor back it's not actually deleting anything so when I hit backspace I want to delete the text that I was typing so let's see how we can do that so what I'm going to do now is after I check if the ordinal value of my key is 27 I'm going to say if the key is in and then I'm going to check three things now the first thing I'm going to check is key backspace the next thing I'm going to check I have to actually look at here it's going to be back SLB and then the last thing is going to be SLX so back accessory 7 and then F now I understand this looks like complete gibberish but the thing is the backspace key on different operating systems will be represented by a bunch of different characters so it could be represented by keyb space space it could be represented by back SLB or it could be represented by back/ x7f don't ask me why that's the representation but that's what it could be so just to make sure this is going to work for all of you no matter what operating system you're on just do this now this is going to check if this key is in this so essentially if the key is equal to any one of these three things if it is then what we're going to do is we're actually going to pop off the last element from current text you'll see what I mean here but I'm going to say if the Len current text is greater than zero than current text. poop now this is one of the reasons why we use the list here to represent all the characters that we're typing because we can very easily and quickly remove the last character from it so what do popop will do is it will remove the last character from a list or the last element from a list so if I have one two and I call pop on this list it just gets rid of two so now I only have one which is exactly what we want because remember current text is keeping track of all of the keys that we have pressed so if we hit the backspace we want to get rid of the last key that we inputed that's what this will now do now we just need to put an lse statement here because if we hit the backspace we don't want to add that backspace key to our current text we just want to remove the current character so we'll add the else to make sure that if this is the case we're not still adding this key to the current text okay hopefully that makes sense let's run this code and let's hit enter and let's start typing so I'm going to say hello world and then I'm going to hit backspace and notice when I hit backspace I'm actually deleting the characters now which is precisely what I wanted so now that we've done this let's see how we can get this text to go over top of the text that we currently have because obviously that's kind of what we want we don't want this text to be um what do you call it coming after we want it to kind of go over top of it and then we want to change the color on if it is the correct character or not okay so let me escape this by hitting escape and let's see how we can go about doing that so to do this I'm just going to write a new function here because I think it makes sense to kind of separate displaying all of our uh what do you call it text in a separate function so I'm going to say Define display _ text like this we're going to take in our STD Source like this or sorry screen not Source we're going to take in our Target text we're going to take in our current text and then for now we'll take in wpm as well but I'm going to make this a default value of zero now in case you're unfamiliar with this these are parameters which means we have to pass values to this function when we call it and if you do something like equals z this means this is a optional parameter so if I don't pass this parameter it will just have a default value of zero now the reason I'm doing this is because we're going to have to calculate the words per minute in a second and we want to display that as well we won't do that in this step this second but we're going to do that later okay so now that we have that what I want to do is display the target text and over top I want to display the current text so I'm going to take all of this stuff that I did here so let's go with this right here the ad string and the character and I'm going to paste this like that so let's now go over here so let's say we're going to display the target text then we're going to Loop through all the characters in our current text but I want to place them somewhere different I want to place them on top of this text so I'm going to say this for I comma Char in a numerate current text now if you're unfamiliar with a numerate what this is going to do is it's going to give us the element from our current text as well as the index in the list so remember current text is a list let's say we have the elements 1 2 3 4 like that what's going to happen when I enumerate over this is I is going to start out being equal to zero zero is going to reference this first Index right here and then Char is going to be equal to one now of course these would be characters but hopefully you get the idea so the next element would be two so Char would be two and I would be one this gives me the index as well as the element just kind of a cleaner way than just going by the index and then manually getting the element hopefully that makes sense but the thing is whatever character that I am on so if I'm on character Zero or character one or character two according to their indexes in the list I can use that to determine where I should place this character so I'm going to say 0 comma I like this so the point is I is going to keep getting incremented by one this is representing what character that I'm going to place this on and so I want to place it on the very first character which is zero and then on one then on two then on three then on four so this will be overlaid on top of my target text hopefully that makes a little bit of sense but since I is going up up by one in every single iteration this means every character that I'm drawing onto the screen will kind of Be incremented by one and it will go directly over top of my target text so let me just show you and hopefully this will clear it up what I need to do though is I do need to uh call this function so right between my clear and my by refresh I'm going to say display text and then I'm going to pass this all of the parameters so stdr I'm going to pass by Target text and I'm going to pass my current text as well okay and then instead of here sorry I'm referencing Target text uh when instead I need to be referencing just current okay hopefully that is all good now let's go ahead and run our code here so python tutorial. piy let's hit enter and now notice when I type hello that it's going over over top of my text right and if I hit space of course it's going to remove those characters because well that's what it's doing but you get the idea okay and then I can go like this so now what we need to do is we need to change the color of this text based on if it's the correct character or not okay but you can see that is going directly over the top of this text and even though it's kind of replacing the text it looks like it's just changing the color okay that's what we want so I'm going to hit escape and now we're going to modify the color based on if this is the correct character now we have what the correct characters are in our Target text and then we have whatever our current text is so what we can actually do is we can compare every single character in our current text to the corresponding character in the Target text and see if we're getting the correct one so I'm just going to say the corrector Char like this is equal to the Target at index I so if my target text is something like hello and then I have my characters as like H comma and then L like this if I'm accessing the zero with index so I'm looking at the first character I can look at the zero with index in this string and I can check if the character I have here matches with that character if they do then I can show this in green if they don't then I can show this in Red so I'm going to say that my color is equal to and then this is going to be curses. col pair at one like that and then I'll say if the Char is uh not equal to the correct Char then theor color is going to be equal to curses do col pair and then what do we use for red I got to see this we use two so let's go here and do two and then I'll put the color variable so let me slow down to make sure I'm not going too quickly here all we're doing is defining a color variable this is equal to curses docolor pair 1 so I'm just storing it in a variable it's the same thing as if I were to directly put it inside of here and then I'm saying if the character does not equal the correct character then we'll change the color from the default green I have right here to be read and then whatever the color variable is that's what we're going to show for this character when we draw it on the screen and of course we're just comparing the correct character to the current character um and we're getting the correct character by accessing the corresponding index in this string so let me get rid of these here and now let us try this so let's go back here let's run the code and let's hit enter and let's go hello and notice if I type something in correctly now it is showing up in red but if I do it correctly then we are getting it in the correct color awesome okay so we are well on our way to completing this application we have a lot of what we needed done uh let me just have a look at my cheat sheet here and see what we need to do next all right so the next thing that we need to do is actually handle what's going to happen when we complete the text we also need to handle showing the words per minute because that's kind of the whole point of this typing speed test so I'm going to run the code one more time and show you that if I type more characters than in this text we're going to get an notice that we get a crash here and it says index out of range now the reason why we're getting this problem here is because we have more characters in our current text than we do in our Target text which means when we try to access Target at index I we get a list index out of range because we're trying to access an element in the Target that doesn't exist again that's because we have more characters in our list in our current text than we do in the Target so when I'm on like the 20th element of my uh current text here here and say my target text is only 15 elements long then I'm going to get a problem right I mean that's kind of a bad example but you get the idea that's what's going wrong so we need to make sure that once we get to the point where we've typed in all of the text or we've typed in the same number of characters as the target text we stop and we don't let them type anymore so what I'm going to do is after I look at the key here uh and after I check if it's a backspace I'm going to put in L if I'm going to say l if the Len of our current text this will tell us how many elements are in the list is uh less than the Len of our Target text so this will make sure that we cannot add any more stuff to our current text unless there is room to add it so unless the current text is less than the length of the target text we are not going to allow you to add another key even if they're the same we're still not going to allow you to add anything else to this because if you did then that would cause the index out of bounds exception so now let's try this and see if we're still getting that problem or not so let me run the code going to begin and let's just go hello world this is some test text for this app I don't really care if I spell it correctly and notice here I'm hitting a bunch of keys but nothing's happening because um we are already at the length of this text awesome okay so let's escape from that all right so now that we've done that I want to start showing the words per minute so we actually need to calculate what the person's word per minute is and then we need to display that now first let's just display it and then we can figure out how to calculate so notice I'm taking in wpm here so what I'm going to do is make a variable in my wpm test function and say wpm is equal to zero so that's what it will be equal to to start then I will pass wpm like that and inside of here we can just display it so I'm going to add to the string I'm going to say std. str. addore string such a mouthful here I'm going to say in an F string explain this in a second wpm and then inside of curly braces wpm and I'm going to put its location at 1 comma 0 so that we go one line below where our Target text is so what this is doing this F string is it allows us to actually embed python Expressions directly inside of a string without having to add two strings together so usually you'd have to concatenate the strings but this is a little bit nicer you can use this in any version of python this is 3.6 and above so you do a lowercase or uppercase F followed by just any string double or single quotation marks doesn't matter matter then you can write any regular string stuff that you would and if you put curly braces like this you can actually put a variable directly inside python will evaluate this as a string and then you will display that so I'm going to say uh wpm equals and then just wpm and that's all we need for right now so if we run the code so let's run this and I hit enter notice now we have wpm which is on the line below so now we just need to calculate the wpm and once we do that we will be all good okay so let's figure out how to calculate that so to calculate our words per minute we need to know how much time has elapsed so far in the program we can't calculate our words per minute if we don't know how long we've been typing for so I'm going to go up to the top of my program here I'm going to import a module called time now time is going to allow me to actually time how long I've been typing for so I'm going to go inside of my wpm test function here and I'm going to start by putting a start time variable which is equal to time.time now what this is going to store is a very large number that represents the number of seconds past what's known as an Epoch now you don't actually have to really understand this at all the point is that this is going to tell us what kind of the current time is when we started doing this so right before we hit the wall Loop we'll record what our starting time was and then inside of the W Loop every single iteration will calculate the wpm based on the start time so you'll see what I mean here but again just kind of keep keep in mind that what this is doing is keeping track of the start time it's a very very very large number that's going to be the number of seconds past a certain date I think it's some time in like 1970 or something doesn't really matter too much okay so we have the start time now what I'm going to say is time elapsed is equal to and then I'm going to get the current time minus the start time so the reason why this works is because time.time as I said is some like really large number that is the number of seconds past a certain date so if I call time.time again this is now going to give me the new time now this time is going to be larger than whatever ever the start time was so I take whatever the current time is subtract it from the start time and then that tells me how many seconds have elapsed now what I do need to do here though is use this Min function or sorry use this Max function and say the max of this n one you'll see why we need to do this but essentially this is going to uh result in us not getting a zero division error which we could get because what's going to happen is we're going to calculate the start time we're then going to go into the wall loop we're going to immediately calculate the time elapsed and the very first time we do this the time elapse is going to to be 0 seconds because the time between when we calculated this and this is going to be like nothing it's going to be the exact same time so this will give us zero and when we have zero when we perform the next operation that could give us a division by zero eror anyways now what we're going to do is calculate the wpm so the equation for wpm is a little bit complicated I'm just going to write it out then I'll kind of explain how it works so we're going to get the Len of the current text underscore text like this we're going to divide this by the time elapsed divided by 60 now the idea here is that if we have say 30 characters types so we have 30 characters and we typed them in 30 seconds then that means that our words per minute sorry our characters per minute would be 60 right if we typed 30 characters in 30 seconds and we're trying to figure out how many characters we're going to type in the minute then we need to multiply our 30 characters by two the reason we need to multiply by two is because 30 is half of 60 now let's do the same thing except with a different time so let's say we type 30 characters in 15 seconds well if we did that then our words per minute is going to be 120 the reason why we know that is because we can take our time lapse so 15 we can divide that by 60 and that's going to give us 0.25 so we know we're kind of at a quarter of an hour so now if we take 30 so let's take 30 and we divide this by 0.25 what this is going to give us is 120 now you can do this with multiplication as well I can say 30 multiplied by and then rather than 0.25 I would multiply it by four and then the way I would get that is I would reverse this operation and I would do 60 over 15 the reason it's 60 is because we have 60 seconds in a minute so that's kind of the rationale here but this is only giving us our characters per minute so this right here is characters per minute we're going to get the line of our current text which is how many characters we've typed we're going to divide that by how much time has elapsed over 60 and that's the characters per minute now it turns out that the characters per minute divided by five is the words per minute so we're assuming the average word has five characters so what I'm going to do is take all this and now divide this by five and now this is the words per minute so the characters per minute divided by five gives us words per minute now one thing I'm going to do here continues to get complicated is I'm just going to round all of this and the reason I'm going to round it is so we don't get some crazy decimal numbers we just get the kind of flat words per minute right I'm sure that makes sense but anyways that is how you do wpm now again the reason why we have this Max of one and then whatever the elapse time is is so that if this is zero this will just give us one right if it's anything less than one then it gives us one so that way when I try to do my division so I try to divide the Len of current text by the time elapse over 60 this isn't zero because if that was Zero then I would get the zero division error okay so now we have the wpm and this will be calculated every single time we hit a key now I'll show you here how this works so let's run the code and let's see what our wpm is going to be okay so notice as soon as I start typing then the wpm will be calculated however right now I'm not typing and the wpm is staying the same the thing is it really should be decreasing right but the reason it's not decreasing is because let me escape out of here this line in our code key equals std. getet key is actually what's known as blocking now blocking essentially means that we're going to wait here we're not going to do anything until the user types a key we're going to wait for them to enter a key that's what this line is doing it's very similar to the input function uh in uh python right now the thing is I don't necessarily want that to happen if the user doesn't type anything I still want to show the wpm I still want it to decrease and I still want to show the text on the screen so what I need to do is actually call this one method here that makes this call no longer block now what I'm going to do is say stdr dot and then I think this is no delay and I pass true inside of here now what this essentially says is do not delay waiting for a user to hit a key the problem is though now if the user doesn't enter a key this line throws an exception now an exception is an error in Python we've seen them so the way that we need to handle this is we need to say try like this we need to say accept like this and then we need to say continue so what this is going to do now is make sure that this line won't crash on us if the user doesn't type something in and then if it does crash on us we go into this accept statement and inside the accept we say continue now what continue does is just bring us back to the top of the while loop it's just going to skip all of this right here because if this line cause an exception then this key variable it doesn't have a value right just it doesn't work we don't have a key because you didn't type in any key so there's no way for me to check what key you typed in if you didn't actually type in a key or you didn't hit a key so I need to skip the rest of this this if we didn't hit a key hopefully that makes a bit of sense uh let's go through an example and I will show you how this works okay so let me go python tutorial. Pi let's hit enter and let's start typing and again we're seeing that it's actually not updating the wpm so let me have a look here and see what's going on all right so it turns out I just need to save the code and rerun and now notice when I do this everything is working right the wpm is going down now let's just change our code a bit just so I can show you kind of what was going to happen if we didn't implement this try and accept so let's get rid of the try and accept and let's now just have key equals to this remember we have this stdr do no delay which means we're not going to wait we're just going to continue right so now watch what happens when I run the code I'm going to hit enter and immediately my program's going to crash we get this no input error because this line here right get key didn't actually get a key so that's why I did the try and accept I just wanted to show you that so that that explanation hopefully made a bit more sense okay so now we're getting the w PM now we're able to type in the text we're pretty much finished except what we need to do is we need to figure out what's going to happen when you actually type in all of the text right because at this point in time when we type in all of the text nothing actually happens so we need to make sure that the user when they get to the end of the text they've typed in all of the characters correctly and if they have then what we'll do is tell them hey you know you won whatever and then we'll prompt them to play again so what I'm going to do is right after this I'm just going to check if the user's current text is equal to whatever the target text is the only thing is the current text is a list and the target text is a string so what I need to do is convert this list to a string to check if it is the target text now there's a really easy way to do this in Python when you have a list and you want to kind of combine it all together into a string you can use something called jooin now what dojoy doeses is it takes a list as an argument so I'm going to pass to this my uh current text current _ text like this and you call it on a string now what it's going to do is it's going to combine every single character from this list with this string right here as what's known as the delimiter or the separator so if I were to make this a space then what would happen when I run. jooin is I would get say I typed hello world there I would get h e space l space l space o it would space them all out if I made this a hyphen then it would kind of combine them together with hyphens in between but if I just make this an empty string which is what I'm going to do then what it does is it just combines all the characters together because well it's combining them with an empty string so they're just getting all squished together hopefully that makes sense but that's what dojyan does it just takes all the characters and combines them together with this as the separator very useful method when you want to convert a list to a string so I'm going to say if joyin current text is equal to the Target text then we are done so what I'm going to do is I'm going to say std. no delay false the reason I'm going to do this is because I want to show something on the screen and then wait for the user to hit a key before I continue so if I want to wait for them to hit a key I need to get rid of this no delay thing because if it's still no delaying then I'm going to get an error if I'm trying to wait for them to get a key okay then I'm just going to break so I'm going to say no delay false I'm going to break and what that's going to do is bring me outside of this W Loop so now that I'm outside of this while loop what happens is this function is going to be done so it's going to bring me back to where this function was called and then out here I can actually show something on the screen and prompt them if they want to play again so I'm going to say stdc dot and let's go with add string like this we're going to add this on the second row down so really the third row CU I'm putting two and I'm just going to say you completed the text exclamation point and then press any key to continue dot dot dot and then I will say this dot uh and then get key so we'll wait for the user to type in a key okay so let's run this now and let's see what's working or if it's working so python tutorial. py okay hello world so let's go hello world this is some test if I could type properly for this app exclamation point and it says you complete the text press any key to continue great and then of course our wpm is 47 cuz that's what we ended up so we hit continue and then it's just going to a the program now what I want to happen is I want it to actually uh bring us or prompt us to play again so rather than just doing this and then ending I'm actually going to put this in a while loop so that I can play as many times as I want so you'll see what I mean but let's go while true let's put all of this inside of here and then let's get the users key and if they hit anything other than Escape we're just going to have them play again so we're going to say key is equal to this and we'll say if the ordinal value of the key is equal to 27 so if they hit the Escape key we will break so they will exit otherwise we'll just continue so we'll just continue with the wall Loop we'll call the wpm test function again which is just going to rerun all of this it will reset all of our variables for us and we will be good to go that's kind of the beauty of doing everything in functions now I don't need to kind of have any weird logic to run this again I just rerun the function right I just call the function another time and we are good to go so let's run this now and and see if it is working okay so let's hit enter and then we'll go hello world this is some test clearly I can't type Under Pressure here when I'm on the recording app exclamation point okay 59 that's not horrible you complet the text press any key to continue we hit enter and what happened it actually crashed the program uh maybe it's cuz I didn't save this ah that would be why I didn't save my code so let's rerun this again and try enter okay hello world this is some test text for this I was doing so well app exclamation point okay we hit enter and then it brings us right back in perfect that is exactly what I want let me hit escape and then I can quit Okay so that is pretty much all we need for the functioning application the last thing I want to show you is how we can randomize the text that's on the screen because it's going to get pretty boring if we just always have the exact same text right and that's probably not the best so what I've done here is I've created a file called text.txt now you can do this as well I trust you guys can create a text file on your own you can probably rightclick on your desktop or whatever and make a new file and what I've done is I've put some uh different text here on different lines so notice every single line has kind of a different piece of text that I want the user to be able to type and I can add as many of these as I would like so what I'm going to do is read in this text file store all of these pieces of text and then randomly select one of them for the user to be typing when they're going with this program so I'll show you how we can do that we're going to write a function here I'm going to say load text okay and all this is going to do is it's going to open up this file it's going to get all the lines and it's going to randomly choose one now since we're doing something random we need to import the random module so I'm going to say import random like that and we are now going to load the file so to load a file is pretty easy you can say with open then you're going to put the name of the file I'm going to go text do txt and I'm going to put the mode I want to open it in for now it's just going to be R if you wanted to create a new file you would do W so that actually is Right mode so you would open a new file in write mode and you could write to the file I'm not going to show you how to do that but I just wanted to mention that but we're going to open in read mode I'm going to say as F and then what I'm going to do is I'm going to read all the lines so I'm going to say lines equal to f. read lines now what this does this with is essentially ensure that this file will be closed after we open it this is known as a context manager it's pretty Advanced I don't want to explain it too much but we say with and then we have this open function this is just how you open a file and we say as F which means we're going to take this kind of file object here this file variable we're going to store it in F and then we can access the file by using F inside of this width so just like the if statement we have our indentation right so I'm going to say lines is equal to f. read lines this is going to give me a list containing all of the lines of this open file and then I want to randomly select one of those lines and return it so I'm going to say return random. choice on lines and then strip now what random. choice does is just randomly choose one element from a list so if I have a list with 100 different things inside of it just randomly picks one and just gives it to me so which is going to give me one of these kind of strings of text one of these lines now the thing is all of these lines of text have an invisible character at the end which is back sln now we looked at this this is the new new line character the reason why they have this is to tell my Editor to display the file in this way if I they didn't have the back sln I would have no way to know kind of where my line breaks are in the uh the text file so what I need to do is I need to remove this back sln which is what strip does from all of these lines because I don't want the user to have to type in back sln I just want to remove it right so I'm going to say strip strip will just get rid of any leading or trailing Whit space characters and a whit space character is the back SL characters that's why I have strip okay so now we have load text this will just give us some Target text so rather than manually coding in my target text now I'm just going to say load text and this will return to me one of the lines from this file now it's very important that this file is in the same directory as where your python file is if you put this not in the same directory it's not going to work it just needs to be in the same directory so you can see my tutorial in text.txt are right beside you now if you don't want to do this that's totally fine you can just manually hard code in the text but I figured I'd show this to you because it is kind of useful okay so that is pretty much going to wrap it all up let's do a few tests here and make sure I haven't messed anything up too badly and then we'll wrap up the video so let's hit any key to begin and let's go subscribe so this looks like it's working to Tech with Tim on YouTube clearly not for typing lessons okay perfect 43 solid I'm sure many of you can type a lot faster than that but let's go on to the next one and then notice it gives me a different string of text we can escape let me just run it again and okay it's giving me another test I'm just going to keep running this to make sure it's going through all of them and awesome okay so it does give me all of the different options that I have of course you can add more to this text file if you like so with that said that is going to wrap up the video there you go we have our wpm tester and I've showed you how we can add all kinds of styles and nice stuff to our terminal I thought this was a really fun beginner project I do kind of admit it's a little bit bit harder than maybe what I would consider beginner but I still think you guys were probably able to follow along at least I hope you were let me know in the comments down below and this showed you a ton of cool stuff that now you can add to your own projects in this video I'll be walking you through a mini python project where we will create an alarm clock SL timer now this will be fairly straightforward but I will show you how to play sound through Python and how you can do a fancy thing with the terminal which involves clearing what you've already printed and then printing something over top of it so you kind of get a live countdown timer you know 10 9 8 7 Etc and it looks a little bit better than printing out like a ton of lines of code probably something that's interesting and that you guys have not seen before regardless that's what we're going to build all right so just to give you a super quick brief here on what we're going to be doing essentially we're going to ask the user to input some kind of time you know 5 minutes 6 minutes 30 seconds whatever it is we're then going to give them a live kind of countdown timer and then as soon as that timer or alarm goes off we're going to play a sound now that means the first thing we need here is some kind of sound effect so that we can actually play that when the alarm goes off so to get a sound effect you can just download one on your own you can pick one that's on your computer and just drag it into the same directory as where your python script is so in my case I have a folder open on my desktop and inside the folder I have my alarm clock. py file and then alarm. MP3 which is a sound effect I downloaded from this link which I will leave in the description so whatever sound effect you want just make sure it's in the same directory as the file uh that you're writing your python code in okay next we need to install a module which is going to allow us to play this sound effect so I'm going to open up my terminal here or command prompt whatever you want to refer to it as and I'm going to type the command pip install play sound so this is the name of the library module that we're going to be using to play the sound okay pip install play sound I already have it installed if for some reason that doesn't work for you you can try pip 3 install play sound if that doesn't work try python hyphen M pip install play sound and if that doesn't work try Python 3 hyphen M pip install if none of those work I will leave two videos on the screen that show you how to fix this pip command okay at this point I'm going to assume you have play sound installed and what we can do now is import this module so we're actually going to go to the top of our program and we're going to say from place sound import play sound now this here is a function that we can use uh to play a sound so we can simply say play sound we put the name of our sound which in this case is alarm. MP3 notice it matches the file name here and since it's in the same directory all I need to know is the name of the file and then if I run my code it will start playing this sound this one is pretty aggressive it's also fairly loud hopefully it's not going to annoy you guys too bad but that is how you play sound very very easy okay next I'm going to import a module here called time we're going to use time uh to kind of regulate the time so we have you know 1 second for each iteration as we're doing this countdown clock perfect we're then going to make a function so we're going to say Define alarm this is going to take in a number of seconds and this is how long until we will play that kind of alarm sound effect okay the first thing we're going to do inside of our function here is we're going to say time elapsed is equal to zero we're going to need a variable to keep track of well how much time has elapsed and then we're going to have a wall Loop and we're going to say well the time elapsed is less than our seconds we're going to do whatever is inside of here perfect so the first thing we're going to do is say time do sleep one now this means wait for 1 second very straightforward just pause the code right here wait for a second and then continue obviously we need need to do that because if we don't have this kind of regulation of time then the alarm is just going to go as fast as it possibly can as fast as your computer can run it and well we're not actually going to be waiting 20 seconds 30 seconds Etc okay next we're going to say _ elapsed plus equals 1 okay and now we want to figure out uh how many minutes are remaining and how many seconds are remaining and then print that out to the screen so you can do this in whatever kind of format or order that you want but in my case I'm just going to take the number of seconds I'm going to figure out how many minutes are in that and how many seconds are in that and then print that out if you wanted to do hours you know weeks days months Etc feel free to go ham and do that in my case I'm just going to do minutes and seconds so first I'm going to say time left is equal to the seconds minus the time elapsed because seconds is how many seconds we want to run this for time elaps as well how much time has elapsed so we subtract those and that is how much time is remaining then we're going to figure out the number of not hours the number of minutes so we're going to say minutes left is equal to the time left integer divided by 60 integer division is two forward slashes and that's going to give you the integer component of division so for example if we had 125 seconds like this and we inst divide this by 60 then we're going to get two because 60 evenly divides 125 two times all right very good next we're going to say seconds underscore left is equal to the time left and then this is going to be modulus 60 now the way the mod operator Works which is the percent sign here is it gives you the remainder after division so again same example we have 100 25 seconds if we do the mod operator here by 60 that is going to give us five because 60 goes into one 125 two times sorry so that uses 120 seconds and then we have a remainder of five okay so that gives us the minutes and seconds left now we can print those out so we're going to say print we're going to use an F string available in Python 3.6 and above so you do F either lowercase or uppercase doesn't matter you do a string and then inside of the string you can use curly braces and inside of the curly braces you can just put a variable so I can do minutes colon and then seconds and now it's going to print however many minutes colon however many seconds are left great lastly we can go here and we can call the alarm function and let's just test this out with say 10 seconds to see if everything's working before we go a little bit uh further and kind of make things look prettier all right so let's run this here run the code and notice that we will get an issue name minutes is not defined okay that's because I need to put minutes left and seconds left so let's quickly fix that bug and then rerun okay 9 8 7 6 5 Etc it's just going to count all the way down however notice that this looks a little bit weird right we don't want to have like 00 0 0 1 instead we'd want to have something like 0 0 01 that's what we're used to seeing right or you know 20 minutes and 5 Seconds we want it to be formatted like this so how do we fix that well there's actually a fancy thing we can do in Python to automatically format our numbers we can go to our variable here which is a number we can put a colon directly after it and then we can put 02d and this stands for make this two digits and Pad it with a zero so if it's already two digits fine we leave it the same but if it's only one digit we add a leading zero that's what this is going to do so I'm going to copy that and I'm going to put that on second left as well and now just to quickly show you if I run the code here notice that we now get our formatting with our leading zeros Perfect all right so now that we've handled our formatting the next thing we need to do is kind of clear the terminal and make it so everything is on the same line and it looks like it's constantly updating kind of the same countdown timer so to do this we're going to use two sequences of characters which are known as a ANSI characters or like commands or Escape sequences whatever you want to refer to them as essentially these are invisible characters that when printed to the terminal will manipulate the terminal in our case it's going to clear something or delete something but it could change the color of something it could make something bold underline italicize there's all kinds of styles and interesting sequences and character CS you can print that manipulate the terminal so I'm just going to show you two of them here related to clearing but if you want to look at more of them feel free to look them up you're looking at a ANSI I guess it's characters or Escape sequences so we need two of them the first one we're going to have is clear and this just going to clear the entire terminal screen so that it's empty we don't see anything else now to do this we're going to do back sl033 then this is going to be a square bracket then two and the capital letter j the next sequence we want want is going to be clear and return and this works a little bit differently but this is going to return the character to or sorry return the cursor to the home position so that when we print again it's going to print over whatever was currently there whatever was there before so now this sequence is 033 square bracket and then H okay so what we're going to do is start by just clearing the entire terminal right once we clear the entire terminal then we're going to print out this and then the next time we print it we're going to clear return to the home position and kind of print over it I know it seems a bit strange but let's start by just looking at one of them so I'm going to go here and I'm going to say print clear and we'll just do clear okay the first one so now notice when I run my code that it clears the terminal and then it starts printing stuff out so that's fine but it's printing everything on a new line which we don't want so what I can do is stop this and now if I use my other sequence I'm going to go here in my F string and I'm going to print clear and return before I print all of this and now watch what happens okay 9 8 7 and look it's on the same line and it's just updating the value okay so we cleared the entire terminal then we cleared and returned to that home position and kind of printed over what we had before so hopefully that is making a little bit of sense I know it's kind of weird how these uh Escape characters function but now we have like a decent timer being updated on the screen so now the last thing we need to do is once our alarm is finished or the timer is up we need to play the sound so we're going to say play sound and then this is going to be alarm. MP3 and we need to ask the user how many minutes and how many seconds they want to set the alarm for so let's go ahead and do that we're going to say minutes is equal to input how many minutes to weight or whatever you want to say here okay now I'm just going to convert this directly into an integer I'm going to assume that they give me a valid int if they don't that's going to crash the program but again we're just going to assume that's fine then we're going to say seconds is equal to int input how many seconds to wait like this and now what we can do is we can say total underscore seconds is equal to minutes MTI 60 plus the number of seconds that they said and then we can pass here total uncore seconds and if we want to make this a little bit nicer we can have some text here that says alarm will sound in and then the minutes and the seconds remaining okay so we're clearing and then we're going to print the alarm will sound in and then it will update whatever this value is and keep going downwards okay so that is pretty much our entire program let's try this out here guess we're going to run how many minutes to wait let's wait 0 minutes and how many seconds let's wait 12 seconds okay alarm will sound 11 10 9 eight goes on and then hopefully we should hear the sound okay so let's give this a second two one and for some reason I'm not hearing the sound okay ah the reason I'm not hearing the sound is cuz my speakers are off but I think you guys probably heard it in the recording because of the way that I have things set up and there you go everything functions it plays the sound and we are [Music] good all right so let's dive into the project just as a quick brief here what we're going to do is create a password manager that allows us to generate passwords with a minimum length so maybe you pass a minimum length of seven that means any password you get will have well a minimum length of seven continuing we're also going to allow the user to set if they want the password to contain special characters and if they want it to contain numbers this way it's slightly Dynamic and we can create some different types of path password sorry so with that said let's get into the project so I'm here in Visual Studio code I assume that you have a python environment setup you can do this in really any version of python and we're going to start at the top of our program here by importing two modules that we're going to use so we're going to import random and we're going to import string now we're going to use string to just grab all of the lowercase and upper case letters that exist and then all of the special characters as well as all of the numbers or digits kind of a cool thing that you may not have seen before now there's two different things that we need to do here the first thing we need to do is ask the user what the minimum length is if they want numbers if they want special characters Etc and then we need to write a function which is actually going to generate the password we can do this in any order that we want for now I'm going to start by writing the function so I'm going to say Def and then I'm going to say generate uncore password and for the parameters of this function I'm going to pass the following which is the minimum length then I'm going to pass numbers is equal to true and then special underscore characters is equal to true and for now I'm just going to write pass here while I explain this so these are the parameters the things that you need to pass the function when you call it again we start with the minimum length which will be a number and then we have two optional parameters here where we can specify if we want the password to include numbers or if we want it to include special characters the way you would call this function is like so so I would say generate password and if I passed just 10 then that would create a password for me that has minimum length of 10 and includes numbers and special characters if we passed say like 10 and then false that would mean we'd have a password minimum like 10 would not include numbers but would include special characters so you can see that if I only pass one of the different arguments then I'm kind of substituting that here for this parameter obviously I could pass both of them as well if I wanted to do that so I could say false and false but by default if you don't pass them we're going to have that equal to True okay all right so now that we're here I just want to grab all of the potential characters so like numbers special characters letters Etc that we could be using so I'm going to say letters is equal to string. asky underscore characters uh is it asky characters or asky letters I think it's asky letters then I'm going to say digits is equal to string Dot and then I think it's digits uh yes that's correct and then I'm going to say special uncore chars is equal to and then this is going to be actually let's make this special is equal to string. punctuation I think I spelled that correctly okay now I'm just going to quickly print these out just so you can see what they look like and then we will continue so I'm going to say channelate password and we'll just pass 10 for now just so that we can see what these are okay so when I call the function you can see that what we get printed here is all of the lowercase and uppercase English letters then we get all of the digits and then we get all of these special characters which are really just all the punctuation on our keyboard perfect so I just want all of those so that I can kind of create the set of characters that I'm going to select from when I generate this password so now we need to combine all of these into one kind of list or one large string that we're going to randomly choose from however that string that we're going to randomly choose from should only contain uh what we have specified here so for example if we're including numbers and we're including special characters then we want to be picking from all three of these variables so either a letter number or special character every single time we kind of generate a new character for the password if we're not using numbers and obviously it's just letters and special and then if we are using numbers but not special characters then it's just letters and our special characters so how do we do this well we're going to say say the following we're going to say should I do the selections no let's call this characters is equal to letters because we're always going to have letters no matter what then I'm going to say if numbers like this then characters plus equals and then digits so if this variable is true for including numbers I'm going to take all of my digits which by the way are inside of a string and I'm going to add those to the letter string so now they're combined and then I'm going to say if special characters like this then characters plus equal special like that so now if we have our special characters we add that to our characters which will allow us to select from those when we are generating the password perfect so now what we're going to do is start a loop and during every iteration of that loop we're going to generate a new character to add to our random password and we're going to continue that Loop until we meet the criteria so until we have for example a number a special character and we are at the minimum length so we need to set up a few variables here the first variable I'm going to create is PWD which stands for password and this is what will store the password the next variable is going to be called meet criteria and actually this will be meets criteria and I'm going to make this equal to false now we're going to set this variable to True once the password meets the criteria and meeting the criteria will mean that it includes a number and a special character or it just includes a number or just includes a special character Etc and that's going to be based on what the input is to this function so we want to make sure that we have at least one special character and at least one number if you made these equal to True next we're going to have a variable that tells us if we do have a number in our password so we're going to say has number for right now that's going to be equal to false and then we're going to have has special and that's going to be equal to false as well okay so now that we have these variables we're going to create a while loop and we're going to say w not meet underscore criteria uh like that and actually not and or PWD the Len of PWD is less than the Min length Okay so this is the condition for our for Loop or for our while loop sorry so we're saying while we are not meeting the criteria so while we don't have a special character or don't have a number or whatever that criteria is or the length of our password is not yet equal to or greater than the minimum length we're going to continue doing this where we're going to continue adding characters to our password hopefully that makes a little bit of sense now I'm going to generate a random character that I want to add to my password add it and then if it's a number I'm going to set has number equal to true if it's a special character I'm going to set has special equal to true and then at the bottom of the W Loop I'm going to adjust this meets criteria variable to tell me if the password currently meets the criteria based on these two parameters so we're going to say uh new _ Char is equal to random. Choice and then this is going to be from the characters uh kind of string here so we've built this character string which has all of our available characters we can pick from so we're going to randomly pick one using random. choice just picks a random element out of the string for us that's why we imported random and we're going to add that to our password so PWD plus equals and then the newcore Char we're now going to say if the new character uh is in our digits so is in digits like that then hasore number is equal to true and we're going to say l if the new Char is in our special characters then has special is equal to true so again this is telling us if this character exists inside of the digits which we have up here and it's telling us if it exists inside of our special characters which we have right here if it does then we're going to adjust these variables so we know now if we have a special character and if we have a number there's a few other ways to go about doing this but the way I'm coding this is one of the more efficient ways rather than rechecking the entire password every single time to see if it has a special character or see if it has a number okay so next what we need to do now is update this meets criteria variable so it's a little bit strange how I'm going to do this but I want to show you uh kind of a more complicated way just as a bit of a learning experience here so I'm going to say meets criteria is equal to true now you're going to see this as a common pattern when you're programming that you actually start a variable equal to true and then you try to prove that the variable is false and then if that's the case you set it to false so I'm going to say meets criteria is equal to true then I'm going to check a few things and set it to false if it needs to be false okay that's how it's going to work and if I didn't set it to false that means well I've met the criteria so I'm going to say if numbers like this and remember numbers is telling me that I should include numbers in the um in the password so I'm going to say if numbers then meet criteria is equal to and in this case we can just say numbers or not numbers sorry hasore uh number then we're going to say if special and did I just call it special no special characters then meets criteria is equal to meets criteria and and in this case uh special has underscore special okay now the way this works is that I'm starting by saying if we should include a number then we're going to set the meets criteria variable equal to if we have a number or not so if we do have a number this is going to be equal to true if we don't it's going to be equal to false then after that no matter what so whether this is true or false I'm going to do this other if statement where I say if we have special characters or if we should include special characters then meets criteria is going to be equal to meets criteria and has special now the reason I'm using this and here is because if has number was equal to false or if at this point meets criteria is equal to false then it doesn't meet the criteria right if we don't have a number but we're supposed to include a number we don't meet the criteria so it doesn't matter what has special is this should return false so that's why I'm putting meets criteria here then I'm checking that with has special so if we did have a number for example if this if statement was true then this is equal to true and if we have a special character then that's equal to true so meets criteria is equal to true if we didn't have a number but we do have a special character then this is equal to false hopefully you can kind of understand where I'm going here and how this works there's a bunch of other ways I could probably have written this a little more clear but I just wanted to show you an approach of kind of doing it in this format and using a what would you call it a chain conditional or a compound conditional here with the and keyword if you're not familiar with the and keyword this expression returns true only if both the leftand side and the right hand side are true so try if you don't understand to pause the video and kind of figure out what I'm doing here and how that works uh but this will now kind of finish our generate password function so from here I'm now going to return my password and at this point it's guaranteed that my password is going to have uh at least one number and at least one special character and be the minimum length assuming that this was true and this was true all right so let me zoom out here we'll run through the code quickly and then we can do our inputs so the user is going to tell us the minimum length if it should have a special character Etc and we'll kind of test the program out so we get our letters digits and special characters fairly straightforward we then create a string that contains all of the different characters we could be selecting from so we've already explained how that works then we say our password is empty we currently do not meet the criteria we do not have a number and we do not have a special character now we say while not meets criteria or or the length of our password is less than the minimum length so if either of these two are true then we're going to continue then we generate a new character by randomly selecting from the characters we can pick from we add that to our password and then we determine if that new character was a number if it was we're going to say has number is equal to true and if it was a special character we're going to say has special is equal to true then we're going to set meets criteria equal to true and if we have a number or if we should include a number sorry I keep mixing this up but if we should include a number but we don't have a number we're going to set meets criteria equal to false if we should include a number and we do have a number then meets criteria will stay true okay then we go here and we say if special characters then meets criteria is equal to meets criteria and has special which is what I just explained which will make sure that this is going to be equal to false if we don't have one of the two things that we need then when these conditions are false so when we are meeting the criteria and when the length of the password is at least the minimum length then we will return the password okay so let's just try calling generate password uh using some manual inputs then we can grab our user inputs so I'm going to say PWD is equal to generate password and then I'm going to print PWD here and for now we're just going to generate it with 10 minimum characters and containing numbers and special characters okay notice that this is the password that we got we can run it again we'll get another password and we can keep running this as many times as we'd like so now the last step is to ask the user to give us the information that we pass to this function so we're going to say the Minore length is equal to input let me zoom in a little bit here so we can read this better and I'm going to say enter the minimum length Okay then we're going to convert this to an integer because we need this as a number value we're just going to assume they give us a valid integer if they don't it's going to crash the program but we don't need to handle that right now we're just going to assume they give us valid input then we are going to say uh has number is equal to and then input do you want to have a number or do you want to have numbers question mark and then we'll say that we're going to accept either y or no all right and then we're going to have has special we're going to say do you want to have special characters now for both of these inputs I'm going to convert them to lower cases so do lower is just going to take whatever the user types in and convert it into lowercase so we're going to do that here and then I'm going to check if this is equivalent to Y so if the lowercase thing that they typed in is equal to the lowercase letter Y then that means yes we should have a number and then same thing here check if this equal to lowercase y so they if they type anything other than y either uppercase or lowercase then we are not going to include the number or not going to include the special character okay so this is going to return a Boolean for us giving us either true or false next I'm going to go down here to PWD and I'm going to pass all my parameters so I'm going to say Min length has number and has special and then I can print the generated password is and then whatever the password is all right so quickly run through this we ask them first what is the minimum length they want we convert that into an integer because we need a number value and by default whatever is entered in the input statement is going to be a string so we got to convert that to an INT then we ask them if they want to include a number we cast that or convert that to lowercase and then we check if it's equal to Y the double equal sign in Python checks for equivalents so we're checking if they're exactly the same if it is then this is true and we will include a number then we do the same thing for special characters we take all of our three values here that we've asked the user for pass that to our function and then print out with the generated pass password is so let's run this okay Enter the minimum length Let's Go with 25 do we want to include numbers yes do we want to include special characters let's go with no and there you go we get our password we can run this again minimum length let's go with 20 numbers no special characters yes and we actually got a small error here it says local variable meets criteria reference before assignment let me have a look at why we're getting this we'll fix that error and then we'll be done all right so the issue is that I accidentally spelled this wrong so criteria has to have the i a and I only had a so it was saying I referenced it before assignment because I spelled the variable wrong so let's just run this again and test this one more time so 20 uh yes and no and there you go we're all good we generated our password all right so let's go ahead and Dive Right In now I'm going to start with the Pathfinder or the maze Navigator whatever you want to call this and we're going to use a package here called curses which allows us to control the terminal and CED in the way that you saw and actually override what's currently in the terminal so that we don't have to keep printing a bunch of separate lines and kind of having a really messy standard output now if you're on Mac or Linux curses should be installed by default for you but if you on Windows you're going to need to install this so go to your terminal I'm just in VSS code and I've opened up a terminal here and you're going to type the following command pip install and then Windows hyphen curses like this now again you only need this if you're on windows so hit enter try that command that should install it for you and if for some reason that doesn't work I'm going to give you two or three alternative commands you can try pip three install Windows curses if that doesn't work you can try python hyphen M pip install Windows curses and if that doesn't work you can try Python 3 now if none of those work I leave two videos on the screen that should show you how to fix this pip command one for mac and one for Windows although I guess you only really need it for Windows because uh you don't need to install anything if you're on Mac or Linux all right now what I've done is made a python file here called Pathfinder P I've opened it in vs code you can work in any editor that you want but I'm going to use vs code I've also pasted in a maze you can find this maze from the link in the description on the GitHub repository or you can just make your own maze I'm trading all of the pound sign here or number sign here as uh my obstacles in the Maze all of the empty strings are going to be things we can navigate and then the O is going to be our start and the x is going to be the end now I do want to mention here that if you are trying to get better at python you also can check out a product I have called programming expert.i this a programming course teaches fundamental programming object-oriented programming Advanced programming software engineering tools all kinds of stuff just wanted to mention that if you guys are interested you can use discount code Tim I'll leave that in the description for now though we do want to build out this project so we have our maze here and the first thing I'm going to do is I'm going to import that curses module and quickly walk you through how this works so you can see how we can print colored output I do also have an entire tutorial series on the curses module on my channel uh in case case you are interested I'm also going to say from curses like that import and I'm going to import something called wrapper and then while we're up here we're going to import a Q This is built into python you don't need to install it and we're going to import time just so we can Implement a bit of delay here in this program when we start actually trying to visualize things for now though I want to show you how the curses module works so what we need to do here is Define a main function and this main function needs to have as one argument stdr now this stands for standard output screen and this is what we're going to use to actually output all the stuff for our program so rather than using the standard print statements here we're going to add stuff to this screen this screen is going to override and kind of take over our terminal and then as soon as the program ends everything on that screen will be cleared and will be brought back to the original terminal you'll see what I mean in a second but for now we're going to type the following STD screen. CLE so we're going to clear the entire screen then we are going to not write we're going to add string and when we add add a string to the screen here we have to pass the position that we want to enter this string at or that we want to add it to so for now I'm going to go 0 0 that represents the top leftand corner of the screen so I believe we're going row and then column that we want to enter this in I'll experiment in a second then whatever the text is that we want to show on the screen so in this case I can do hello world exclamation point then we're going to do STD screen Dot and then this is going to be refresh and what that does is refresh the screen and so we actually see what we wrote and then lastly I'm going to say STD screen Dot and this is going to be get CH what this stands for is get character and this is similar to an input statement that we would have in Python it just makes it so that we're going to wait here until the user hits something before we exit the program if we don't have that it would do this and then just instantly exit and we wouldn't see anything because we weren't waiting long enough to actually view the output all right now that we have that main function we're going to call wrapper which we imported up here and we're going to pass to it the name of this main function we're going to make sure we don't call the function so I'm not calling like that I'm just passing the name of the function and what this does is it initializes the curses module for us and then it calls the function passes this STD screen object and then we can use that in here to control our output all right hopefully that's clear so far let me save and let's run the code uh and let's see what we get and notice that it kind of brings me to this blank window and it says hello world and then if I hit any any key on my keyboard brings me back to the original terminal one more time if I run this notice it shows me hello world hit a key and then I'm out uh that is the curses module very basic introduction however I want to show you what happens when we change these coordinates and how we can add colors so let's say now we maybe draw this at five so 5 Z is our position let's run the code and notice we go five rows down and we're at the zero with column so that's how you can control where you're drawing this you put the row and the column you want to start drawing so if I go maybe 55 and then let's save and rerun uh oop oops save and rerun uh notice we get Hello World kind of more in the center of the screen so very powerful what you can do here and then if we want to add a color this is a little bit more complicated uh we first need to initialize a color so I just got to look at my cheat sheet over here to remember how to do this so we're going to say curses. anitore pair and whenever we create a color pairing here in curses we give it an ID so I'm just going to give an ID of one and then I put the foreground and the background color that I'd like to have so I can say curses Dot and then color underscore and then whatever colors you can see there's a bunch of options here green magenta red whatever so let's go with blue for now and then the foreground color or sorry the background color my bad is going to be curses undor color and then black so you put your foreground color and your background color pretty much all the colors you can think of are you know you can access them with colorcore their name and then now that we have the initialization pair if I actually want to use this color what I have to do is the following I'm going to say bluecore andore black is equal to and this is going to be curses Dot and I believe this is color pair again let me just have a quick look at my cheat sheet here to remember this yes it's color pair and we're going to put the ID of the color pair we want to use so since I reference this with id1 or created with id1 now I reference id1 and that's going to give me a color of blue and black and the way I apply that now to my text is I just pass another argument to add string with this so blue and black and now when I start displaying this it should be blue and black so let's do this let's run the code and notice I get Hello World in blue text and the black is just the default background so it doesn't change the background color but if I wanted it to be like a white background I would say color white and then if I draw this now so let's rerun this uh notice I get kind of a white background for that text great but let's go back to color block okay so that's the first color pair while we're here let's initialize another color pair cuz I want blue and black I also want red and black so let's change this to red and let's make that to uh and then we'll use these later on I don't actually want to write hello world onto the screen so let's actually just comment all of that out for now uh and let's work on the bread first search algorithm and then we can actually start displaying stuff on the screen so the first thing I want to handle is printing this maze out so obviously I want to view the maze on the screen so to do that well how am I going to do that I'm going to write a function here I'm just going to call this print Maze and to be able to print the maze I need the maze that I'm going to print I need the standard screen or the standard output screen that I'm going to print the maze to and then I'm going to take a variable here or an argument called path now path is going to be the path I want to draw on the maze obviously we don't know what the shortest path is yet but I can pass a path here of coordinates and then whatever values are in that path I'll draw them a different color in the Maze so you'll see what I mean in a minute so that's print maze uh now inside of here I'm going to grab my two colors that I want to use so I'm just going to say blue is equal to and then this will be curses do colorcore pair this will be one let's say red is equal to curses. color pair 2 just so I can use both the blue and the red we'll draw the default maze as blue and then the path as red okay continuing I'm going to Loop through everything in my maze because this a two-dimensional array so I have kind of all my rows and then the columns would be the individual values in each row so I'm going to say four and this is going to be I comma row in a numerate maze now if you're unfamiliar with a numerate this is going to give me the index as well as the value so I'm going to get every one of these rows as a row or every one of these nested arrays as a row and then I will be what row I'm currently on okay continuing I'm going to say 4 J comma value in enumerate and then I'm going to enumerate over the row the reason I can do this is because I have a list or an array whatever you want to call it but list in Python so row is my list then I'm going to numerate over the list that I have I'm going to grab whatever column I'm currently on which is what J is going to represent and then the value is going to be whatever symbol here is in the column okay so that's what I have then what I want to do is I want to simply draw this onto the screen so I'm going to do the following I'm going to say STD screen Dot and we're going to add string and now we need to determine where we want to add this string well where I want to add it onto the screen is going to be whatever position I'm currently on which is going to be represented by I and J so I is going to tell me the row I'm on J's going to tell me the column so what I can do is simply add whatever I'm drawing here at whatever row and column I'm currently at so I'm going to say i j as the position and then I'm going to say value and value is just going to be either an empty string a number sign an O an X whatever it is that I'm currently looking at hopefully that makes sense but that's what we want for print Maze and then I'll handle the path in one second for now though let's actually try printing the maze so I'm going to uncomment the clear I'm going to uncomment the refresh and the get CH and now rather than adding my own string I'm going to call Print maze I'm going to pass to it the maze variable which is just a public variable or a global variable that's fine I'm going to pass my STD screen and then this is a default argument of empty list so I don't need to pass that okay so let's run this now uh let me just make the terminal a bit bigger first let's run this and notice my maze is printing out now this looks a little bit squish together uh like it's too close to me so to spread this out a little bit what I'm going to do is simply multiply the row and the column that I want to draw this at by two uh and actually we can leave the row as just regular I we can just spread the columns out a little bit more so now we should get kind of two spaces between each of our elements and also let's add a color here so let's add blue and now it should be drawn in blue so let's run this and I guess I need run again okay and there we go that looks a lot better the maze is spaced out uh and we can kind of see it all nice great so let me exit that all right so now that we are printing the maze out and I guess that's pretty much all we're doing I need to talk a bit about how this algorithm works so let me head over to the Whiteboard I will explain that to you and then we'll start coding it out so in front of me I have a very simple maze I'm also going to refer to this as a graph uh and this is what I'll use to demonstrate the breath first search algorithm so the goal here is to find the shortest path from some starting node to some ending node and I'm going to reference these nodes by their position in the graph so we see these are different rows these are different columns and I'm going to have my positions in row column format which means I would refer to this here as one Zer so Row one column zero just keep that in mind as I write the positions because uh you might be confused if you're reading it the other way and like here this would be 03 all right so how does the breath first search algorithm work well the concept behind the breath first search algorithm is that we're going to continually expand outwards from a point in until we find the ending point that we're looking for or the ending node I'm just referring to every single one of these squares as a node okay in kind of graph Theory that's what you would call them so we're going to start here at this start point and we're essentially going to slowly expand outward by looking at all of the neighbors of this point so we're going to look at this neighbor and this neighbor and if there was a downwards neighbor or a left neighbor we'd look at those as well uh but there isn't any left or down neighbor so obviously we're starting here so we expand here and then from both of these points we're going to look at all of their neighbors so maybe we start with this one we would look at this neighbor then we would look at this one then we continue the process and we do this one iteration at a time which means that once I finish considering this neighbor here I go and I do this one then of course we're going to move up to here we're going to move up to here and since we're doing this one step at a time as soon as we hit the ending node we will actually be guaranteed to have found the shortest path because we're only expanding our path from the starting node by one new node at every single iteration now that's a super highlevel recap of how this works of course I'm going to walk you through the code and more complicated demo uh but that's kind of the concept here one step at a time we're slowly expanding outwards from this node and expanding our current path by one until eventually we reach this end node and as soon as we find the end node we know that we have found the shortest path because every other path that we have is either going to be the same length uh or longer to find this path okay so let's now look at demo of how we actually do this so first of all we're going to use a data structure called a q now Q I believe is spelled like that I'm also just going to refer to it with the letter q and this is what's known as a first in first out data structure or a last in last out data structure whatever you prefer to call it essentially what that means is that if I enter some item into the queue just kind of like a phone queue or any other lineup that you would be in if I enter this item first then this is going to be the first item to come out and the second second item that I enter into the queue that's going to be the second item to come out now that's important because we're going to process elements in the order in which they're entered into the que so just keep that in mind so for our que we can have a back and a front so we can say that this is the front of the que excuse my messy handwriting and then this is the back just so we're clear on uh kind of what element we're going to process next so what we're going to start by doing is we're going to place our starting node here inside of the cube now the way I do that is I just place the position of the node that I want to start looking from so I'm going to put a position of three and then zero because it's in row three and column zero now every single step in my algorithm what I'm going to do is I'm going to pop an element off of my Q I'm going to take the element that's currently at the front of the queue I'm going to remove it from the queue and I'm going to start processing it now the way I process an element is I essentially just look at all of its neighbors and try to find if we're currently on the end element or not so in this case I take three off the que and I say okay I want to process all of this element's neighbors and kind of expand outwards from this until eventually I get to this note so what I'm going to do is look at the neighbors I'm going to determine I have two of them and I'm going to check if these neighbors are the end node if they are then I'm done the algorithm I found the shortest path but if they're not what I need to do is add them onto the que so now they can be processed and we can continue expanding until eventually we find this and note so let's erase this from the Q here so 3 uh We've now processed that element I'm going to add this into some set here so let me just create a set uh this set will be known as our visited set and okay it's kind of hard to draw this the way that I want to so let's just do this 3 0 and the reason I'm putting it in a set is just so I know okay I've processed this element I don't have to look at it another time anyways processing the element again involves looking at all the neighbors so the two Neighbors here are two 0 and what do we have we have 31 so I'm going to add those positions into the que doesn't matter the order that I add them in so I'm going to add two and what was this zero and then my other one is three and one okay so these are now the two new elements that I need to process to continue expanding my path so what do I do well I'm going to pop now the first element off of the Q and I'm going to process this one and well repeat everything that I was doing so let's cross it off erased in a second this is the current one that we're looking at so now we need to consider all of this node's neighbors now it has a neighbor down and a neighbor up it also has one to the right but since the one to the right is an obstacle we don't look at that and for the one that's below us here we see that the one below us is an element that we've already looked at and the reason we know that is because it's in this visited set so I can skip the neighbor below us because we've already looked at it I don't need to process the same element twice and I can just go directly to the element above so I'm going to add a single neighbor here to my q and this neighbor is going to be uh in one and then zero so now I've processed this element it was not the final node that we were looking for so let me delete it here and now we're going to add this into this visited set now I didn't mean to butcher my element here so let's go here uh what was that position that was two and zero so let's add this in to zero like that and now we've visited those two notes now we're going to continue so we're going to take the next element off of the Q which is 31 so I'll just delete it here we will add it into this set so you might as well just add it right now okay three and one and then from 31 that's right here we need to look at all of its neighbors so it has one going to the right and it has one going to the left well of course the one to the left we've already processed so we can just add the one to the right which is right here and that has a position of 32 so what I do is I add 32 to my Q uh if we can that's a really bad three we get the point we add 32 and we continue and this process is going to repeat until eventually we hit this end node and again as soon as we hit this end node we know that we found the shortest path because that's the first time we found it and we would have found it on another path if there was a shorter path to get to it so I mean I could continue this example but hopefully you kind of get the idea we're expanding outwards one node at a time until eventually we find the ending node and then I will show you in the code how we actually kind of keep track of what path we were on because that is a little bit more complicated but this is the basic idea we have a Q we add elements onto the que we process them one at a time in the order in which they were inserted into the que this guarantees that every kind of new element that we're looking at is only expanding our current path by at most one node as soon as we find the end node then we can just say okay well we found the shortest path let's end the algorithm let's draw the path out hopefully that gave you a very brief explanation of how this works I don't want to go through the whole thing CU it will take uh too much time now though let's start coding this out and hopefully everything will be cleared up all right so let's code out a function here called findor path and we're going to take in here the Maze and then this is going to be the standard screen uh and I think that's all we need for find path now for find path I'm just going to declare a few variables here I'm going to say start is equal to X end is equal to O uh and actually is this no we're going to say start is equal to O end is equal to X and what else do we want here uh we want to figure out what the starting position is of our maze now we could just hardcode in the position right here but instead I'm going to write a function that will essentially look for this o and tell me where in my maze I'm starting from because we're going to start from this position we need to know the coordinates of this right so in this case it'd be 0 1 2 3 4 5 okay it's in uh row zero so it would be 0 five that would be the the position here of the start but we want a function that will tell us that so we don't have to manually do that so for now I'm going to say Define find underscore start and just because I didn't really explain this I just jumped right in uh what we're doing here is we're going to start coding out that breath first search algorithm that you just saw so that's what fine path is going to do but first we need to find the starting position so we're going to take in the Maze here and we're going to take in whatever the starting symbol is and what I'm going to do in here uh is simply say four and this is going to be I comma row in a numerate maze and then for J comma value in a numerate row I'm going to say if the value is equal to start then I can simply return I comma J so I'm going to return the row and the column where I found this starting symbol and we're going to assume that we just have one of those symbols okay now otherwise we'll just return none if for some reason we couldn't find the start okay so now in here we're going to say startor pause is equal to find start then we're going to call The Maze and the starts now we know the starting position now what we want to do is set up our q and set up those iterations and finding the neighbors and all that stuff I was discussing so for the Q we have this Q module and we're going to use it so the way we do that is we're going to say Q is equal to and then q.q and again this is a first in first out data structure so the first element I insert is the first element that comes out that's very important because the order in which we process the nodes really matters when we're doing the bre for search we don't want to process the most recent node we've added to the queue we want to process the node that's been in the queue the longest just like we would if you were accepting you know a bunch of phone calls or if there was a lineup or something like that that's exactly what a q is right so we have our q and we need to insert something into the queue so to insert something we use this put method here and we're going to put a actually um a tupple and the tupple is going to contain the starting uncore position and and it's going to contain a list that has the startor pause in it now the reason why we're adding two elements in here is because in the queue I want to keep track of the current position or the node that I want to process next as well as the path to get to that node now the reason I want the path to that node is because as soon as I find the ending node I'm going to take whatever path I currently have and I'm going to start drawing that onto the screen I'm going to show that on the screen so for now since we haven't found the end node our current path just includes the start position but every time I process a new neighbor or something along those lines I'm going to change the path and the path will continue to grow uh and I'll be able to see what path we're at for every single note hopefully that makes a bit of sense but that's why I'm storing two pieces of information the position I'm currently on as well as the path and in fact we could even optimize this further and just store the path and grab the last element from it uh but I'm just going to do two things here just so it's Crystal Clear when I code this out it's not the most efficient thing in the world but for this tutorial it's fine okay so for now we put that in the queue we also want to make a visited set which is going to contain all of the positions that we've currently visited now that we have all that set up I'm going to say while we still have any elements in the Q so while not and then Q Dot and I think this is either is empty or just empty I believe it's just empty so while the Q is not empty what we're going to do is we're going to get the most recent element from the Q the one that's kind of next in Q so I'm going to say current underscore position and path is equal to q.g now get's just going to give me the element at the front of the Q and since I have two things for every element I have my path as well as the position uh I'll grab the current position which will just give me the first element and the path which will give me the second element okay now that I have the current position I'm going to say the row and column is equal to current position so I'm going to break down the position into its two components the row and the column and I'm going to find all of the neighbors of this position and start processing them if they are not the end node so first I'm going to say if Maze and then this is going to be at row call is equal to and this is going to be the end so we're going to say end like that so we're going to look in the Maze and see if this position is equal to an X if it is that means we found the end and so what we can do here uh is simply return the current path because again as soon as we find the end node we know that we've found the shortest path or one of the shortest paths because there could be two paths that are both the shortest we'll find one of them so we can just return the path and then we can draw that if we want okay continuing now what we need to do if we haven't found the end node is we need to continue branching out so we need to find all the neighbors of the current node and then expand towards them so we're going to write another function here called findor Neighbors now the tricky thing with the neighbors is that we need to make sure that the neighbor that we're finding is not an obstacle and that it's a valid position in the Maze so you'll see what I mean here but we're going to take an a maze a row and a call and we're going to say our neighbors is equal to an empty list and we're going to determine programmatically what all the neighbors are of this current position so we're going to look up left right and down if you wanted to you could do diagonal but I'm not doing diagonal in this tutorial but adding that is is fairly easy so for now I'm going to say if the row is less than then uh not zero sorry if the row is greater than zero then I'm going to add a neighbor and this neighbor will be the neighbor above I'm going to say neighbors. append and I'm going to append the row minus one and then the current column so we can add a comment here and say this is going to go up now the reason I have to check if the row is greater than zero is because if the row currently is zero I have no more rows to look up I'm at the bounds of my Maze and so I can't add that but if the row is greater than zero so it's one at minimum then I can subtract one from it and that's still a valid position next I'm going to say if the row and this will be+ one is less than the Len of the maze then I can add the row below so I'm going to say neighbors. append row plus one and then call again because if the row + one is equal to the length of the maze then that means if I were to add row plus one I would get an index out of bounds eror I'd be too far that means I'm already at the bottom of my maze but if this is true then that means I can add one more without going out of bounce so that's for the rows now we want to do the same thing with the columns for so for left and right so I'm going to say if the column is greater than zero then this is going to be left what I can do is say neighbors. append and I can append the current row and the column minus one okay and I'm going to say if the column is column + one is less than the Len of maze 0 now the reason I need to check maze Z is because my maze may not necessarily be squ Square in this case I don't actually think it is square we may have more columns than we have rows so I need to check how many columns we have and I can just do that by grabbing the first row and seeing how many elements are in there so that's what I'm doing here if we don't have a first row this will cause an error but we're always going to have first row so that's fine and then I'm going to say neighbors. append row and call plus one and then here I'm going to return neighbors and let's just put a comment here for right now in here we did not check if these positions are obstacles we'll do that inside of here for now we've just got all of the valid positions that are neighbors now we're going to check if they're obstacles or not as we Loop through them so I'm going to say neighbors is equal to and then this is going to be find neighbors uh not find path find neighbors and we are going to pass to it the maze as well as the row and the column of the current position that we're processing right finding all of their neighbors we're then going to say for neighbor in neighbors and we are going to check if this is an obstacle or not and if we've already visited it before because if we've already visited it we don't need to process it so I'm going to say if the neighbor is invis then continue because we don't want to process it and I'm going to say if the neighbor and actually sorry I need to break this down I'm going to say row call is equal to neighbor and actually we'll just go RC so that we don't Shadow the variable name up here but I'm going to say RC is equal neighbor standing for row and column I'm going to say if the maze at and this will be RC is equal to a pound sign okay then what we want to do is continue okay now if this is not the case so if the neighbor is not inv visited and the neighbor is not a pound sign then that means we need to process this neighbor so I need to add it to my Q so I'm going to say q.p put and I'm going to put inside of here my uh position so I'm going to put the neighbor okay which is going to be a topple containing the row and column and I also need to put the new new path that now contains this neighbor so I'm going to say my new path is equal to and this is going to be whatever the current path is up here okay so where do I have path path is right here and then this is going to be plus and inside of another list because I can add two list together I'm going to put the uh what is it the neighbor so all this is doing is kind of tacking the neighbor onto the current path this is not the most efficient possible way to do this uh you guys can try to optimize this if you want but for now this is fine and for the Simplicity of the video I'm going to do it in this way and then I'm going to put New Path so I'm adding the neighbor as well as the New Path and the New Path is just whatever the current path is plus the current neighbor that I'm considering right uh that's what I have uh when I'm adding to the que okay hopefully that makes sense uh lastly what we need to do is say visited. add and we add the neighbor to that to make sure we don't process it multiple times and that's actually all we need for the breath first search algorithm again I know this looks pretty complicated but that's all we need uh now what we want want to do is make it so that we draw all of this stuff out so we can kind of see this happening and then I'll walk through the algorithm one more time just to make sure it's Crystal Clear so where we had this here right where we were printing the maze I'm going to copy that and I'm going to put that inside of this wallo because at every step I want to draw out what I'm currently considering so I'm going to go up here and I'm going to paste this before we're checking if we're at the final uh element or the the final node and I'm going to print the maze except this time I'm going to pass my path and when I pass the path now this will allow me to draw out the path right so I'm going to clear the screen I'm going to print the Maze and I'm also going to add something to print maze so we draw the path and then I'm going to refresh the screen and I'm going to do this every while loop iteration so that I can see the progress going on as I go through this algorithm so now let's go to print Maze and let's make it so that we print the path in a different color so here I'm going to say if and this is going to be I comma J is in the the path so if it's in the path that we have right here that's valid to check that then what I want to do is draw this in a different color otherwise I'll do this so I'm just going to copy this line I'm going to paste this in here I'm going to change from value to be X because X is going to represent the current path and I'm going to change the color to be red so now rather than drawing an empty string I'm going to draw in X and I'm going to draw it in red and I'll draw it at the same position I would have before but again we're just changing what we're drawing okay so that's pretty much all we need last thing we need to do here is just call this function so this function is find path and it takes in the Maze and the STD screen at least I believe that's correct and I think with that this should all work now there's a chance I made a mistake and we'll have to fix that but for now let's run the code and give this a test so let's make the terminal nice and large let's run this and notice it just instantly found the path and we get that now of course we want to be able to visualize this so we can make it a bit slower and the way we can do that is by using this time module so if I go here uh where my refresh is pretty much anywhere in here what I can do is time. sleep and I can sleep for like 0.2 seconds 0.5 seconds whatever you want just so that you have some time to kind of process what's going on so let's sleep for 0.2 let's make this larger and let's run this and notice that now you can watch the breath for search algorithm in action and see every path that is currently considering and there you go we just found the finished path and the algorithm is done all right so there you go that project is now finished uh was a bit longer than I was expecting but obviously I want to explain this as best as I could let's walk through it step by step to make sure everything's clear uh and then we'll move on to the next one so we start here with main we've already talked about curses we know how this works and we call fine path now we call fine path we pass the maze in the standard screen and inside of fine path the first thing that we need to do is determine where the start position is in our mace because we're using coordinates right and we're trying to use that so we need to know the starting position so in start of fine start we just Loop through the maze we go through all the rows we go through all of the values in each row and if we find a value that's equal to the start symbol which I'm denoting as O then we're just going to return whatever position that's in and that way I can now very easily change the start position put it anywhere in the Maze and this will adapt and in fact let's just do that by putting an O up here okay let's save and let's make sure there is a path uh yes that's fine okay uh continuing we then have our Q so we Define our first in first out data structure and we add our starting position and the starting pause now I'll give you guys kind of a challenge here if you want try to do it by just having the path and not having the starting position there is a way to do that again I just haven't done that in this video then I have my visited set keeping track of all the elements I visited I'm saying while the queue is not empty what I'm going to do is get the current position and the path from whatever's at the front of the que I'm then going to get the row and the column of the current position and I'm going to draw out the main is with whatever current path I'm on whatever one I've got to at this point I'm going to check if I'm at the end if I am at the end then I can return the path because I found that end node if I've not then I need to continue looking for the end node right so I'm going to say neighbors equal to find neighbors maze row and call I'm going to Loop through all of the different valid neighbor positions I'm going to check if they're visited and I'm going to check if they're an obstacle if they are I'll skip them if they're not I need to add them to the path and add them into the que because we need to check now if they're the end node and if we need to expand from them right that's how this algorithm works then I add them to the visited set and this continues until we either find the path or we visit every single node that we have so every single one of them has been added into visited that's not an obstacle and we can't find a path so this will end if either there's no path or you find the PATH that's how that works all right find neighbors pretty straight forward forward gives us the valid neighbors and then print maze I won't explain that we walked through that already okay so that is that project let's just run this one more time for a sanity check that it's going to work when we change the starting node and let's see what the shortest path is here okay uh and there we go we have found the shortest path of course make this maze as large as you would like and you can see you know how that works all right so with that said that is Project number one hopefully you guys enjoyed that definitely actually the most complicated one that we have now that I think of it now though let's move on to project number two all right so now we're moving on to project number two which as I said is going to be the NBA project where we're grabbing basketball data there's a ton of data you can get if you're into basketball this is going to be really cool for you and even if you're not you'll learn how to work with an API how to process some data external data in an application kind of display that in some format send a request Etc so what I'm on right now is a link it's data. nba.net prv1 today. Json this is a free API and what this gives you is links to all of the pieces of data that you have access to for free so it's kind of weird but this link gives you the links that you're going to look at to get specific data so for example if I search for let's zoom in oh that's a lot easier to see so for example we have this calendar okay so this says calendar and it's prod v1c calendar. Json what that means is I copy What's called the endpoint and I just tack that on oops that's not what I meant to click uh to the end of this here so I paste that so now I'm going to calendar. Json and if I hit that it gives me a calendar uh that contains I guess some calendar data I don't know exactly what this is doing or what this is showing uh but the point is that it gives you a bunch of links for all different types of stats that you can get so you can get like Allstar R roster League config standings League div standings whatever you want you can have a look at and you can grab that data but you first go to this link and then it gives you the link to that data that's how that works okay hopefully that makes a bit of sense I'm going to leave that open now though we want to essentially grab the data that that links providing from Cod and the way we're going to do that is we're going to send a request to that link it's going to return to us something called Json which stands for JavaScript object notation I have an entire video on Json on this channel but pretty much this is a python dictionary that's the way you can think of it and we can access the different key value pairs grab the links for data sources that we want and then send a request to those links and get data from that so it's kind of a two-step process we send a request to that URL it gives us some data on the different links we then send a request to one of those links and get the data that we actually want and a request is essentially our computer requesting information from a remote server we're going to send something called a get request which as it says request information there's other type of requests like post request put requests patch delete requests uh that do other types of stuff but that's kind of beyond the scope of this tutorial however before we can do all of that we need to go and install the request module now the way you do that is similar to how we installed curses before go to your terminal and type pip install and then request like that again if that doesn't work try pip 3 if that doesn't work try python hyphen M pip install otherwise you can watch those two videos that will be linked in the description and it should show you how to fix that but you need the request module installed if you're on Windows and Mac you do need to install this unlike curses it uh will not be installed by default and again just reminder try pip 3 in case that doesn't work uh and then you can try python hyphen M pip or Python 3 hyphen M anyways I have this installed so that's all working for me and let's now go in here and start writing some code so I'm going to say from requests import and we're going to import get and I'm going to say from and this is going to be print import and we're going to import the pretty printer like that I'll show you the pretty printer kind of a cool thing in Python it's built in and it gives us a nice formatted output for Json data then what we're going to do is have our basore URL which is going to be equal to htps col slash slash and this is going to be data. NBA do and then net okay this is the base URL and then the endpoint is going to be the specific data that we want so I'm going to say all Json is equal to and this is going to be SLR slv1 slay. Json and today. Json is the original one we were looking at that gives us all those links now though we want to send a request to this link so the way we do that is we say our response because every time you send a request you get a response is equal to and we're going to say get and we're going to say base URL we're going to append this or we're going to concatenate this to all Json so we'll have you know the full URL built out and then we're going to have a look at what's known as the Json of this so whenever you send a request here you have access tojson again think of this as a python dictionary and now we can print all of that out however you're going to see if I print this with a print statement so let's try this here if I print the response then we get get kind of this garbage in the terminal that's just impossible to read so instead of printing it using a regular print statement we're going to use a pretty printer really cool thing if you haven't seen this so to do this we're going to say printer is equal to pretty printer make sure you add your parentheses and then we can use the printer by saying printer Dot and then PR print so pretty print and we're going to print the response and really we should call this data because we're grabbing the data the Json associated with so let's say data okay so let's run this and now notice that I get much nicer formatting here everything's kind of separated on different lines that's what we had before this is what we have now when we use the pretty print so inside of here uh we can see that we have a bunch of links now these links give us access to all of these different things right so game book lead tracker um mini box score whatever data it is that you want you can pretty much get all of it so what we want is the current scoreboard because we want to get information about games that are currently going on or that are going to happen today so what I'm going to do is try to grab this current scoreboard key and get the uh link that's associated with it so the way I do this first of all is I need to access the links key right so that I can start looking at this dictionary then I need to access the let's have a look the current scoreboard so we'll do it step by step uh let me just close this terminal and let's do this so we have our data now we want to say links is equal to data at and then links and let's print this out so printer. pprint and then links okay so let's have a look at that and now when I print out the links we just get all of the links in here and now the link that I want is the current scoreboard so I'm going to grab the current scoreboard links so I'm going to copy that there and now I'm going to say that my scoreboard is equal to and this is going to be links and then we're going to paste in here the current scoreboard so now let's have a look at the scoreboard okay let's run this and notice here that this is the URL so prod V1 2022 whatever scoreboard. Json now that I have that as it was saying I need to send a request to this endpoint the endpoint is the slash after the base of the URL so that I can get that information so now that we have that we have the scoreboard URL let's make a function here and let's say getor scoreboard okay let's put uh let's put this inside of here and we're just going to separate things to make it a bit cleaner I'm going to say Define getor links okay and inside of here we're just going to return links and now what I'm going to do is rather than links I'm going to say get underscore links like that and then I'm going to access the current scoreboard so I've just made it so I can reuse this function here so that GES G gets me all of the links sorry so now I get the links access the specific link that I want and now I'm going to send a request to that link so I'm going to say get and we're going to say base URL and this time we're going to say plus scoreboard okay and we'll say that this is response and actually I guess we could just do data is equal to and then we can get the Json and then again we can use the printer so printer. pprint and we can print out our data okay so now all we need to do is call the get scoreboard function so let's call that and what's going to happen now is it's first going to send a request to what was it to the all Json URL it's going to give us the links we're then going to access current scoreboard then we're going to send a request to that get the data and printed out so let's clear this and let's run and notice that I get all kinds of data here right and this is kind of hard to read um like there's a lot of stuff so it's difficult to look at what the keys are so what I like to do here to actually see how I can kind of Traverse this data is I would like to print out the keys because remember this is a python dictionary so since it's a dictionary what I can do is just grab all the keys of the the dictionary and then I can see what data I want to grab next so if I run this now and we scroll to the bottom notice that my keys are internal num games and games so I probably want to access the games so let's clear that and just access the games for now so now I can go Json and games and now let's have a look at what this data looks like so let's run this and notice again I got a bunch of stuff so now I probably want to have a look at uh the keys of this so let's say data dokeys okay let's run this and what does it say here a list object has no attribute Keys okay so what that means sorry guys is that the games is a list of all of the different games so what I can do instead now is I can say for game in games because this is a list we just found that out and now I can simply print the game. keys and just break and what that means is I'm just going to do this one time so I'm just grabbing you know the first game and printing out all of the keys associated with a game so I can view that that so now let's run this okay and name games is not defined oh my apologies let's call this games not data okay let's clear the screen let's run and now I get all of these Keys okay all of this information I have access to for every individual game and the games are games that are going to be happening today uh that that's what the games are so now I got to pick what information I want to display because I probably want to print out you know who's playing with the score the game is uh you know what time is it is in the game that's the stuff I had before at least so I'll probably do the same here so we can kind of pick what we want but we have V team and we have H Team those stand out to me as the visitor team and the home team we also have period and we should have clock so I think those are the four ones I want for right now so let's grab those so we're going to say homeor team is equal to and this is going to be game at and then this is going to be H Team right because that's the key we want to access and then I'm going to say I guess away team uh is equal to and not a team but V team and we can print out I guess the clock and the period as well we'll say clock is equal to game clock and we'll say period is equal to game period and now we don't need to use the pretty printer because we're just going to print these uh on one line and we will print an F string and we can say home team versus and then a away team and then we might as well just print the clock and the period as well just to have a look at what those are and then we'll continue from there okay clock and period so if you're unfamiliar with this in F string allows you to embed Expressions directly inside of a string when they're in curly braces so I mean this is pretty intuitive but in F string only works in 3.6 plus so python 3.6 plus so I'm just putting the home team versus away team comma clock comma period just so I can see what those look like and I'm going to do that for every single game so just just to separate these a bit then let's add a bit bit of a separator just so that we can see uh the difference in games that's clear let's run the code and notice that I get all of this data okay so for each team I have a team ID a TR code wins losses Series wins series losses I get a bunch of data right and then the score of those teams because I guess some of these games are actually happening right now so what I can do is print out the TR code if I want to see you know the actual name of the team and then I could print out their score as well so let's try doing that now so for our home team that's fine uh now we're going to say home team and inside of here we'll say TR code and for the away team same thing we'll say TR code uh just to clean it up a little bit so let's run this now and see what we're getting in terms of the difference uh so now we notice we actually get the uh abbreviations for the team then we're looking at what was the next thing we're printing the clock okay so 44.1 is what's on the clock for this one uh and then we have the period And it says what the current period is for the games that are currently going on okay nice so let's get rid of clock and period so those are the teams next thing that I want to print is the score of each team right so I'm going to print F and then this is going to be the home team and not the tri code but the score this is the score in the current game and then we'll print the away team and the score as well and so now we get the teams that are playing as well as their scores the game and then we can print the clock and and period after that okay so let's clear let's run and notice here that we get uh I guess what is that Chicago I I don't know what these teams are but something 171 19 3122 14 19 Etc Great and then here we're just getting a hyphen because these teams are not yet playing and z00 I guess those guys just started okay continuing now we want to print the clock uh as well as the period so let's say print and we'll print F and I guess we'll go we should probably do should we do clock or period first let's go clock period and then we'll see what keys we have on those so let's run this okay and we get current so that's what we want to access for the period and then it looks like the clock just gives us a value uh so that's fine we can just grab the clock itself okay so let's go clock and then period and we want to get current like that okay let's run this again and now notice that we get 32.0 and then that's period 1 and then 142 period 1 409 period 1 you guys can format this better I'm just giving you the basics obviously okay so that's what we wanted for getting the scoreboard now we also can get a bunch of other data and like I showed you we can get uh stats for the teams so their points per game I guess their points allowed per game there's all these different stats I'm not a huge basketball guy I just thought this would be cool but let's write one now that gives us the teams and we can view their stats and like I had before we will rank them based on points per game so to do this one we're going to want to look at get links again so let's not call get scoreboard let's call get links okay let's clear this and let's run the code and let's see what links we have for stats ah I didn't print sorry need to print this let's print get links and actually we should probably use the printer to do this so printer. pprint okay so let's have a look here and these are all the ones that we have now let me remember which one I was using I think it was League team stats yeah League team stats leaders okay this is the one that I want to get stats of course there's a lot of other ones so I'm going to copy that key and now we're going to write another function I'm going to call getor stats uh okay that's fine for now and I'm going to say stats is equal to and then this is going to be getor links and we're going to reference this right here the league team stats leaders okay then we will send a request so let's just copy this and rather than games I guess this is going to be teams and we'll have the base URL plus the stats and then Json and then we want to print out all those keys so we see what we have access to so let me take this in here and rather than get links we'll print out should really call this data so let's call this data okay now let's call get stats so get stats like that okay let's run this and let's see what we get and notice we get a lot of information okay uh I want to print out just the keys that's my bad I meant to do that so let's do do keys and let's see what we actually get for that okay scroll down and we get League okay so that's the only key so let's access league so let's just put League here uh there's internal as well but we don't care about that that's some other data let's see what keys are associated with league so let's run that uh we have standard Africa Sacramento Vegas Utah I'm assuming we want just the standard League okay so let's grab standard okay let's run that and for the keys we have season year preseason regular season playoffs uh I'm assuming we probably want regular season but again you can change this if you want so let's now grab regular season let's print that and we only have the key teams okay so now let's grab teams and then this will be called teams let's see if there's any keys for teams so let's run this now and it says oh data is not defined so let's change this to teams okay and rerun list object has no attribute Keys okay so this a list meaning that if we want to grab the keys for each team we can just do something like teams zero. keys and if we have a look at this now we get all of these different pieces of information for the stats of each team so I can get the nickname the name the team ID team code abbreviation min fgp TPP I don't know what a bunch of these mean but I know PPG is points per game so that's the one that we're going to use cuz I know what that means anyways those are the different Keys we can get for each team so now we can Loop through every single team uh and we can print out information for them so let's do that so let's say for team in teams and then we'll grab the names say name is equal to team name uh what else do we want I guess we'll get the ID we'll say the ID actually no I don't need the ID we'll just go with name and I suppose we get the nickname as well nickname is equal to team nickname and let's go PPG is equal to team and then PPG okay and then let's just print for now we'll do an F string and we'll print the name the nickname and the points per game okay so let's have a look at this now let's clear and let's run and there we go okay so apparently we have a bunch of teams here that are not in the regular season or don't have a rank or something so we'll have to filter those out we'll do that in a second but for now we have the uh all the teams right so we have the name we have the nickname we can choose which one we want to use and then we get average and we get rank for points per game so this is where it gets a little bit more complicated I want to display these teams in the order of their rank right so I want rank one to be at the top and I guess rank 29 30 whatever to be at the very bottom but I also need to filter out these guys because I guess there're a bunch of teams that we don't really need in our data set I don't know why those are being returned to us so the first thing I'm going to do here is I'm going to filter all of the teams that have a name of team so way I'm going to do that say teams is equal to filter I'm going to say Lambda X I'll explain this in a second don't worry and I'm going to say x at Team like this does not equal and then we're going to say team because anyone that had the name team was like a blank team that we didn't really need and then we'll do this on teams okay so what the filter function does is it will run a function against every single element in our teams in this case that's what we're passing and if the function returns true it will keep the element if the function returns false it will remove it so this is an anonymous function that's what a Lambda function is this is our uh parameter essentially the function called X so I write Lambda x uh and then I say colon X team does not equal team I'm saying let's grab whatever the team key is of every one of our dictionaries and if it is not equal to team then we will return true so like this expression returns true or false so if the function returns true we keep the element uh if returns false we don't keep it hopefully that makes a bit of sense I can't really explain it more than that however when you have a filter function here it returns a filter object not a list so you just need to convert it to a list okay so now that we have that let's just run this again and you should see that all those kind of empty teams will be removed so let's run it and uh key error team uh oh sorry not team this needs to be name okay let's fix that let's rerun and there we go so now all the ones that had just team are removed now what we need to do though is sort our teams by their rank in their points per game so to do this we're going to say teams. sort and we're going to say key is equal to and again we're going to put an anonymous anonymous function we're going to say Lambda X and then this is going to be x p perg PPG for points per game and then this is going to be rank like that and this is going to be int now this is going to sort in um what is it ascending order so we're going to get rank one first rank 30th 30th last now the reason I'm doing this is because points per game is a dictionary containing the rank and the average I want the rank so I'm grabbing points per game rank for every team converting that to an INT so then we sort it as an integer not as a string because notice these are string values right uh and that's that's how this works you can pass this key function and that's what you're going to sort every element by when you're sorting now let's run this and notice that we're going to have all the ranks in the correct order now of course I don't want to display you know this weird dictionary I'd prefer to display the following PP PPG and then AVG like that for the average so now if we rerun this we get the average number of points that each team scores per game and we get them ranked from 1 to 30th lastly if we want another touch here we could do the following I'm going to say I +1 Dot and I'm going to say for I comma team in enumerate teams and now it will say the rank beside each team so let's do that now and let's run and notice that now I get my rank and I also could have just done uh PPG at rank as opposed to doing i+1 but this works as well okay so that is going to wrap up this project let me quickly walk you through it so we start by defining the URL that we're going to send our request to we had to import and install the request module we set up our pretty printer we have get links which gives us the link we're going to send our request to to get specific data we then have this function to get the scoreboard that is the games that are currently running uh and so we have current scoreboard we get the Json we grab all the games associated with that for every single game because this is now a list we Loop through we get the home team uh the visiting team the clock and the period and then we display this data and of course you can display this nicer you can get some more info I thought this was good enough for the tutorial then we have our get stats function and get stats is going to grab the league team stats leaders uh it's going to do the filtering it's going to do the sorting and it's going to go through and display all of the teams ranked by points per game so I just called get stats to run that uh you can call get scoreboard to run this you can run both of them you could write a little program that asks the user which one they want to run I'll leave that to you guys now we're going to move on to project number three all right so now we're moving on to project number three which is a currency converter now for this project we need to go to this website free. currency converter ai.com to get an API key that we can use with this API now this a free API as it says in the name you are rate limited which means you have two requests or sorry 100 requests per hour uh you can do a maximum of two currency pairs when you're getting the exchange rates per request uh and you're allowed to go back one year in history now you can pay for a premium version of this obviously we don't need to do that for this tutorial though we just want to get uh the exchange rate data now this data is updated I believe every 60 minutes when you're on the free version I think if you go to the paid version you get it every minute or 60 seconds or something like that again doesn't really matter for this tutorial anyways go to the website link in the description click on get your free API key enter your email it will send you the API key but make sure you verify your email because if you don't do that then it won't activate your API key anyways I already have my key uh and you don't want to share this with anyone of course it's the video I don't really care I'm going to have to share with you uh but what I'm going to do is make a variable here in a new file called API key and I'm going to paste in my key which I'm just going to grab from my other screen now while we're at it we're going to paste in another variable here called base URL now this is going to be equal to a different URL than you just saw it is free.cc kurv.com so that's the URL we want to be sending our requests to for this project to get the um up-to-date currencies right okay then what we're going to do is say from uh request import get now if you were not following along with the previous uh project which is fine what you need to do is install requests so pip install requests like that you can also try pip three install requests and if that doesn't work try python hyphen M pip install lastly you can try Python 3 hyphen M pip install if that doesn't work there is two videos Linked In the description that will show you how to fix that command one for mac and one for Windows okay now that we have that we're just going to import the pretty printer as well just so we can use that again we used this in the last uh videos sorry so from PR print not last video last project we are going to import the pretty printer okay so this API Works a little bit differently than the last one we need to send what's known as some query parameters when we want to get some specific data and the first thing I'm going to do here show you how we can get a list of all of the currencies and then how we display those currencies then we can get the exchange rates and all of that stuff for now though I'm going to set up a printer so I'm going to say printer is equal to pretty printer again if you weren't following with the last video then what this allows you to do is get some nicely formatted output for your Json the Json is essentially a python dictionary that's going to be returned to you when you send a request to a URL uh okay so now that we have that let's get the currencies the way that we get the currencies is we say endpoint is equal to and then I need to copy this in so let me just copy this from my other screen and this is going to be API v7c currencies and then question mark now this starts what's known as a query parameter a query parameter is essentially a parameter some data that you're going to send to the URL uh and in this case what we need to add is our API key so we're using an F string available in Python 3.6 and above we're embedding the API key directly in here and that's what's going to allow this to work if you don't have the API key uh then this won't be validated and you won't be able to send a request now let's actually do this in a function so I'm going to say Define get currencies like that and we're going to say this is our endpoint and we're going to say that our URL is equal to our base URL plus our endpoint and then we're going to say that our data is equal to and this is going to be get we're going to send a get HTTP request to this endpoint uh so we're going to say get URL and then Json like that and for now we're going to say printer. pprint standing for pretty print and we're going to print out the data and we'll just call the get currencies function okay so that's all we need for now to look at the currencies so let's run this uh and no module name requests okay it needs to be request plural my apologies let's run this again and notice that we get all of our different currencies okay so when I have a look at what we're getting returned here uh we get a key that says results now again this is just a python dictionary that's the way you can think of it really is Json but we it gets read in as python dictionary so I can access this results key which is then going to give me a dictionary that has keys for every single currency and then the value of all of those currencies is going to have an ID a currency name and optionally a currency symbol so I want to be able to display that data to the screen so what I'm going to do here is from this function I'm going to return the data and then this is going to be at results like that uh and I'm also going to sort all of the results before I return them so I'm going to say that this is results okay I'm then going to say here data. sort so actually what I'm going to do here on a new line is I'm going to say data is equal to and then this is going to be the list of data. items the reason I'm doing this is because data right now after I get results is going to be a dictionary as we can see I don't want it to be a dictionary I want it to be a list and the reason I want it to be a list is so that I can sort it by the different currency names so I'm going to convert it into a list by getting all of the items the items will give me topples that contain the key so that be the currency and then the dictionary associated with each currency then I'm going to sort this by default it will sort by the first item in Python so it'll sort by the currency name and then I'm going to return my data like that so now I can say down here data is equal to get currencies and I can say printer. pprint and data and hopefully this will look a little bit cleaner now and it should be sorted so let's clear the screen let's run this uh and then notice we're getting tles here right where it contains the currency I guess you could call it ticker uh and then the information associated with that currency and it's in alphabetical order based on I'm going to call it the ticker or the ID whatever for the for the currency so now what we want to do is write a function that can display this in a much nicer format so we're going to say Define printor currencies we're going to take in our currencies and we're going to Loop through them and print them out so we have data there that's fine so now we're going to say for uh currency and then this will be well we should probably spell currency correctly so for currency in currencies uh we are going to grab the name of the currency so if we look here we see we have currency name uh we want the ID and then potentially the currency symbol but not all of them have it so we're going to have to write some code for that okay so let's say name is equal to and then this going to be currency and I believe it's currency name and then we want the ID so we're just going to say underscore ID I don't want to use ID because that's a built-in keyword in Python and this is going to be currency actually no it's just going to be ID okay and then the symbol uh will be so symbol is going to be equal to currency and then this is going to be doget and we're going to try to get the currency symbol like that and if it does not return a symbol then we're just going to get an empty string so when you use. getet that will try to find this key in the dictionary if it exists it gives you the value otherwise it gives you the default value which is an empty string which I'm passing right here okay now that we have that we can print this out so we're just going to print an F string again and we'll have the ID first because that's going to be the threel symbol uh then we will have the name and then optionally we will have the symbol there there okay hopefully that makes sense let's now call this so printor currencies let's pass our data and let's see what our output looks like here after I clear the screen okay let's run it and tle indices must be in integers or slices not string my apologies guys so we're going to say for currency uh let's do this for name comma currency and currencies the reason we have to do this is because this a list of tles forgot about that so now if I run this it should be good and there we go now we fixed the problem so we can see that we get our little ticker currency if there's a symbol it will display the symbol uh if there's not a symbol then well we don't show it okay nice so now that we have that we want to write something that can get an exchange rate so I'm going to say Define uh exchange uncore rate I guess like that and for the exchange rate we need two currencies that we want to get the rate for right right so we're going to say currency 1 and currency 2 now these currencies are going to be the IDS of the currencies we listed out so like CAD USD whatever the like the IDS is what we need to pass to this function for this to work now the endpoint for this I'm just going to copy it in here is going to be the following endpoint is API V7 convert uh question mark Q okay for query right we're going to say is equal to currency one and then notice this is underscore currency 2 so a little bit weird how this works but for this specific URL you pass the first currency uncore the second currency and that's the pairing that you want to get information about now you can pass multiple pairings like I could do USD CAD here and it would give me both of the results now we're just going to do one at a time and then you say and compact equals Ultra and API key equals API uh when you do compact Ultra gives you the most compact uh version where it's just going to give you the exchange rate and then of course you need your API key as well so we're going to embed that in this way hopefully that makes sense now we're going to send a request here so we're going to say URL is equal to base URL plus endpoint we're going to say response is equal to get url. Json and sorry not that Json we're going to say data data is equal to response. Json and let's now just print this out so let's go printer. pprint and we're going to have to handle potential errors that can occur here if you pass invalid currencies so for now though we can comment this out and we can just call the exchange rate and let's pass this with USD and Cad and it will give us the exchange rate between USD and CAD not from CAD to USD although I guess you could go both ways okay let's run this and notice that we get USD Cad and it's 1.25 9 025 looks about right and if we passed the second pairing it would have given us this key for whatever ever the second pairing was and then the value uh hopefully that is clear but that's what we're getting from that so what we need to do now is essentially check to make sure that this actually worked and the reason I'm saying that is because if I pass something like you know random string here and I run this notice that my data is empty because there was no pairing with that name so what I'm going to do here is I'm going to say if the Len of data is equal to zero then I'm just going to print out invalid currencies I guess we could just do uh I guess that doesn't really work we'll do invalid currencies and then we'll just return otherwise though we want to get the pairing and we're only going to have one pairing here in here one pairing here and here okay interesting how I said that but we're going to return data and then this is going to be do items actually not do items do values and we're going to convert this to to a list first of all because when you get the values it gives you kind of this special object and then we'll grab the zeroi value uh and we can actually that's already a float so we don't need to convert that okay so let's now say rate is equal to that and then print rate okay and then this will be USD so what I'm doing is I have my endpoint right I have my URL I'm getting my response I'm getting the data associated with that I'm saying if the line of data is is zero then print invalid currencies I also realize that we can just clean this up so let's just make this data like that uh now if the length is zero that means well we didn't have a valid pairing so we print that out and we return otherwise though we're going to convert all of the values it's just going to be one value really uh to a list we're going to grab the zeroth element which will just give us whatever the rate is and then we can print that out here okay so let's run this and notice we get 1.25 925 nice okay so now that we have gotten that uh maybe I want to add some output in here actually that tells me a bit nicer what the rate is so let's do that I'm going to say uh actually not print I'll say rate is equal to this and we will return the rate but before I return the rate I'm just going to print out and we'll do an F string here and we will say that um what is this going to be currency one okay uh to currency 2 is equal to rate I don't know if this is exactly the way that I would write this but I think that's fine like usd2 CAD for example is this rate yeah you know what for now we're just going to go with this uh we'll say is equal to that that that's fine for me okay so let's just run this one more time and notice that I get USD to CAD at 125 9025 okay perfect that works for me now that we have that we're going to write one more that is going to take a dollar value and convert that do dollar value uh to the other currency so we're going to utilize this function but I'm going to say Define and then this is going to be I don't even know what I would call this here I guess convert and convert will take currency one currency 2 and an amount now in here we're going to say the rate is equal to exchange rate of currency one currency 2 and I'm going to say if the rate is none so if we're returning from here meaning we had an invalid currency then we're just going to return we don't need to do anything otherwise though we're going to try to convert the amount that was passed here to a float so I'm going to say try and then I'm going to say amount is equal to float amount I'm going to say accept and then what I will do is say print invalid amount so if you pass like a string amount for example here um something that I can't convert to a float I say invalid amount and then just return so that that way we don't have any issue when we try to do a multiplication which you're going to see in a second okay so we try that that doesn't work we we say invalid amount otherwise we're going to say converted uncore amount is equal to and this is going to be rate multiplied by whatever the amount is right and then what we can do is print with an F string here and we can say uh let's say amount and then currency one and let's just say is equal to and then we'll say converted amount currency 2 okay and then just because we might as well just return the converted amount okay so now we have four functions get currencies print currencies exchange rate and convert so now what we want to do essentially is just write a program that keeps asking the user for a command and allows them to quit but they can type in a command and do whatever they want with the currency converter so I'm going to say defin main inside of here I'm going to say currencies is equal to get currencies okay uh and then I will just print out like a little welcome message so welcome to the currency converter okay exclamation point uh and then we'll print the different commands so I'll say list list the different currencies okay we'll say print and then this is going to be convert uh convert from one currency to another okay and then print uh we'll just call this get the exchange rate of two currencies okay now that we have that let's just do one empty print statement just there's a separator and now we'll say while true and we're going to ask them to enter command so we'll say the command is equal to input and we'll say enter a command and we'll just say that they can type Q to quit like that okay so now in here we're going to say actually first let's convert this to to do lower just so that we can check um even if they type something uppercase we'll still get the command so first we'll check if they quit so if command is equal to Q uh we need two equal signs here then we can just break out of the wall Loop so let's break we'll say l if the command is equal to list then simple enough we can just print the currencies okay so print currencies like that uh that's all we need for list we'll say l if the command is equal to and then I guess we can handle convert then we need to ask the user for two currencies as well as an amount so we're going to get currency one which is equal to input uh enter a currency name okay actually let's say ID all right then we'll convert that uh actually we're going to convert it to uper not. lower now let's copy this again so let's say that's currency 2 actually we'll say enter a base currency ID enter a currency 2 convert to uh maybe we'll just do this I think this reads a bit better enter base currency enter currency to convert to and then we want one for amount so I guess I could have just written this from scratch we'll do this in between I'll say amount is equal to input enter and amount and then we'll say in and this will be in the base currency so we can say in uh and then currency one okay and well we don't really need to convert that to Upper because it's just going to be at a value once they do all of that then we can call our function which is convert and we can pass our value so we can say convert like that and we pass currency one currency 2 and amount okay lastly so we say l if the command is equal to rate then we just want to get the two currencies so let's grab currency one and currency 2 and let us call exchange rate so exchange rate of currency one and currency 2 and else we'll say print unrecognized command okay I think that is all we need now we need to of course call the main function okay let me zoom out a little bit just so you guys can read a bit more so we have our main function we're getting all the currencies we're just printing a little welcome message and then we're running a wall Loop and we're saying while true we're going to ask them to enter a command uh Q to quit of course if they enter Q we will break so that will quit if they enter list we will print the currencies if they enter convert we'll ask them for the information we need then we will convert and convert here here uh we'll do everything we need and print out the output then we have our rate where we get our two currencies and same thing we get the exchange rate and that will handle printing out uh the output as well so I believe that's it let's run this though and test it out so run and welcome to the currency converter let's zoom in a bit here uh list convert and rate enter command so let's try list okay there we go list everything out let's try to do the rate and let's do USD and Zar okay and gives us 14944 okay let's now try was it exchange no is convert convert enter a base currency let's go USD uh enter an amount in USD let's go 1,000 let's go xoff which is one I just saw up here West African CFA Frank okay and there we go gives us the conversion nice then if I hit Q I can quit and that is all the program needs to do for this project we're going to build a YouTube video downloader now the way this will work is you will just type in a URL of video you want to download you will then open up the browse window so you'll kind of select the location you want to save it to and then it will just be downloaded very nice so let's create a new file here I'll just call this YouTube dopy and similarly to the last project we are going to install a module here that will make our life easier so we're going to go here and say pip install PBE same thing as before gonna want to change this to pip three depending on your operating system okay so let's install P tube you can see I've already got it installed all right so now that that's installed we're going to do a few Imports here we're going to say from PBE import YouTube you can guess why we need that we're then going to say import tkinter this is built into python by the way as TK and we're going to say from tkinter import the file dialogue like that now you'll see why we need this in a second but tkinter is a very basic 2D Graphics library or kind of like goey utility library and python that lets you build some graphical user interfaces we're simply going to use it just to have a directory popup so you actually get like a visual kind of place where you can select where you want the file to be saved you'll see what I mean in a second but you can do some more cool stuff with it so if you're interested you can check out teer pretty simple to get started with anyways first thing we want to do is figure out how to download a YouTube video so we're going to make a function here which is download video and what we need to download a video is the URL and the path that we want to save the file to now similarly to before we're going to do a try and accept block because stuff can always go wrong when you're using these kind of apis so we're going to say accept exception as e and then we're going to say print e here and inside the tri block we're going to start writing the code that we need to actually download the video now we're going to say YT standing for YouTube is equal to YouTube and we are going to pass in the URL now what this will do is grab kind of an instance of the YouTube video based on the YouTube url that we pass and then we can kind of do a few things with it like we could get some stats about it but in our case we actually just want to download it now to download it there's a few ways to go about doing this but we want to download the highest resolution version so the first thing we're going to do is get access to all of the different streams of this video so we're going to say yt. streams. filter we're going to say progressive is equal to true and we're going to say the file uncore extension is that how you spell extension I think it is is equal to MP4 now you can change this if you want but I think MP4 is just the default that most of us are going to use okay now that we have access to all of the different streams this is all the places we could be downloading it from we're going to get the highest resolution stream so we're going to say highest res stream is equal to streams. getor highest uncore resolution like that now this is going to give us access to that stream now that we have access to that stream we're going to download the video so we're going to say highest res stream. download we're just going to say the output uncore path is equal to the save path which is the parameter passed into here that's it we can then go and say print video downloaded successfully exclamation point okay pretty straightforward but we can go ahead and test this out so we can just say URL is equal to and we'll grab a YouTube video URL and then for the save path we want to specify where we want to save it now if we don't pass anything it will just save it in the current directory where we currently are uh but I'll show you again in a second how we can kind of fix the path a little bit so that it's a bit easier to figure out where we want to save it now in my case I'll just manually type in the path so I'm going to say C drive SL users SL Tim SL desktop SL python automation which is the name of the folder that we are currently in okay now we can call the function so download video URL and save path and now what we need to do is just get a YouTube video URL let me just grab one of my videos and I'll be right back all right so I just loaded up one of my YouTube videos three types of projects that make you a programmer but I couldn't help but notice look at this link here enroll in my free software development introduction course that looks interesting let's click on that and you can see that we have start your career in software development and there's actually a free intro course you guys can take if you want that teaches you about how to break into software development if you are looking to actually land a job not going to show this too hard obviously there is a paid course here as well but there is a completely free one that gives you a ton of value it is 1 hour long if you guys want to check it out do that from the link in the description anyways we have our link let's copy the link and paste that inside of the URL variable and now let's save and let's run our code so python youube dopy give this a second to download okay and you can see now that we get the three types of projects that make you a programmer video downloaded successfully and I'd be able to open that up now and actually watch it if I wanted to pretty straightforward so now similarly to before what we want to do is make this code a little bit better just so that we don't have to manually type in this path and we don't have to manually type in the URL so let's scrap all this and let's now write something that makes it a little bit more user friendly so what we're going to do is make a function here called open file dialogue this is going to open the file dialogue which will kind of pick where we're going to save the folder with a file sorry first though we're going to say root is equal to tk. TK now what this does is just instantiate the TK module and kind of creates a TK window uh TK window right to be able to use this file dialogue you need a window but the thing is it doesn't have to be shown so what I can do is I can say root do withdraw now what that will do is it will just hide the window so you don't see it uh kind of appearing on the screen so we initialize the window hide the window and now we're actually able to use this root variable here um or really any tkinter typee stuff to be able to open the file dialogue so what I'm going to do inside of this directory is say folder is equal to the file dialogue okay and this is going to be ask directory and then I'm going to say if the folder path so if they actually type something in then we're going to say print the FST string selected folder and I'm just going to print out what the folder was that they selected and then I'm going to return the folder here okay great so now I'm going to go down and I'm just going to make one single line here I'm going to say if uncore name is equal toore uncore maincore uncore now you might be asking what the heck is this crazy line that I'm looking at Tim well what this line will do is make sure that you are directly running this python file before it executes anything that happens under this that's it all that means is that if you run this code directly this will run if you don't it won't the reason you would ever even need this is because sometimes you'll have some code inside of here that might be reused by another file so for example maybe our currency. file uses something inside of here if we don't have this line and currency were to import this module that would actually run all of the code like it would run all this stuff here so actually with that in mind let's put this here so that anything we do is only going to happen if we directly run this python file I'm hoping that makes a bit of sense but you guys can ask chat she with here look it up if you want some more clar ification pretty standard uh python syntax anyways we're going to say the video URL is equal to input and we're going to say please enter a URL and this is going to be a YouTube URL and notice I just added a space here the reason for that is this input doesn't automatically put a space after it so I just put a space so that we'll get some separation with the colon okay so we're going to get the video URL we're then going to get the save directory so I'm going to say save is equal to the open file dialogue and I'm just going to quickly do something here I'm going to say if not folder like this and I'm going to say print please select folder dot dot dot we got to change this to say save directory and then I'm going to type continue like actually not continue uh yes please select the dur okay then I'm going to put an else here and I'm going to say download video video URL and save directory and actually rather than please select the folder I'm going to say invalid save location okay so what did I just do here I wrote a very simple line that simply asks for some input so it's going to get the video URL I then had this save directory so we're going to open the file dialogue you're going to see how that works in one second I'm just going to make sure that they actually did select a folder because it's possible they could just exit out of it if they did so which is actually in the lse statement here I'm going to download the video if they didn't which is what this is checking I'm going to print they have an invalid save location now if we want this to be a bit more clear we could actually swap these around and say if they have a save directory then we'll download the video otherwise we'll do this and if we want we could do a little print statement here and say print started download just in case the download takes a while or you have slow internet so people know something is actually happening got zoom out a bit so we can read more of the code at once again all of this will be available from the description and let's give this a test python youtube. enter a URL uh okay that's not the URL that I wanted let's go back here and grab my URL paste that in okay then notice it brings up a location so I could go desktop and what was this python automation okay now it's actually going to this isn't going to be good because it's going to save in the same thing okay let's just save it to to my downloads I'm going to select downloads as folder notice it says started download okay we'll give this a second and then it should be downloaded inside of my downloads so if I go to my downloads CD dot dot CD dot dot CD downloads LS you can see that we have three types of projects that make you a programmer and it's been downloaded okay so that was it for project number two hope you enjoyed let's move on to the last project moving on to our last project we are going to write some code that will do an automatic folder backup for us this is actually pretty simple uh but I just wanted to show it to you because it is kind of a realistic and real world project anyways what we need to start by doing is installing a python module just like before so we're going to say pip install and we're going to install the schedule module you could probably guess what this is going to do but it is going to help us schedule a kind of task to run now this will show you how to schedule really any task task doesn't have to be a folder backup we're going to make a new uh python file here I'm just going to call this backup dopy and inside of here we're going to import a few things that we need so we're going to import OS which stands for operating system we're going to import shoe util or however you pronounce this which will do some copying operations for us we're going to import date time because when I back up a folder I actually want to save the new folder as the date that this was backed up so we can kind of have a history of all our backups I'm then going to import the schedule module and I'm going to import the time module okay we've got our Imports now what we need to do is specify what the source directory is so the thing that we want to back up and what the destination directory is so what I'm going to do is say my source dur is equal to and I'm just going to manually type in the path for this that I want it to be so I'm going to do c/ users SL Tim SLP pictures SL screenshots now you can do any folder that you want you just have to find the path to it now if you're wondering how do I find the path to it well there's a few ways you can do this now I have to show you on uh what do you call Windows CU I'm obviously on Windows but if I open up my file explorer here and I go to my if I can do this pictures and screenshots what I can do is just click in the address bar here and it just gives me the path okay so that's how you would do this on something like Windows now on Mac you should be able to just open up a folder so you should be able to like right click on it and go to the properties of that folder or get more info about the folder and it should show you the path to where that folder is that's how you can pick the location although I'm sure you guys can probably figure out how to find the PATH now we also need to have the destination directory so I'm going to say destination dur is going to be equal to and then here what I'm going to do is C colon SL users SL Tim SL desktop SLB backup now I just made a new folder on my desktop called backups you can put the folder wherever you want but obviously just make sure the folder exists that you're going to be backing up into okay so now we have the source directory and the destination directory we're going to make our function so we're going to say copy folder to directory and inside of here we're going to take in our source and our destination and we're going to say first of all today is equal to date time. date do today now what that's going to do is simply give us the current day today that's all this does okay just gives us the day today based on our computer we're then going to say the destination directory is going to be equal to os. path. jooy and we're going to take in our destination which is passed here and we're going to combine this with the string of today's date now the reason I'm doing this is that we're essentially going to have this backups directory okay and inside inside of here we're going to have a bunch of folders all these folders will be our backup and those folders will be labeled like 11 you know 23 2023 right which is the current date so what I'm doing is I'm getting the current date and I am combining the current date with my destination directory so that inside of this directory I have a new directory which contains the backup which is named today's date okay now similarly to before we're going to do a try and we're going to say show you till. copy tree now copy just copies everything recursively which means anything inside of the folder it will copy and we're going to copy from our source to our destination directory okay make sure you don't use DES use destination directory because that's the new directory we just set up awesome then we'll do a little print statement here we can do an F string we can say folder copied to the destination directory and then we can do accept exception as e and actually I'm going to do something different because I'll show you how this works I'm going to accept the file exists error and I'm going to print NF string and say folder already exists in the destination now what this is doing essentially saying okay it's possible that an error occurs here when I try to copy my source directory to my destination directory if that's the case that means there's actually already a directory with the same name inside of this uh what do you call it base destination directory so we are just going to catch that error so that our program doesn't crash and we are going to handle that by just printing out hey this is the error that occurred okay we're almost done so first of all right now if I want I can just do this so copy folder directory and I can pass my source directory and my destination directory now let's just open that up so if we go here and we go to desktop you can see I have backups nothing's inside of here okay now if I go ahead and run my code python backup. py we'll see if we get an A not it says folder copied here okay so if I open this up now you can see we have screenshots appearing now the name is a little bit glitched uh don't worry this actually will be named the correct thing for some reason whenever you copy a Windows created folder which is the one that I did it uh it kind of glitches in the ID so you can see date created actually shows the correct name here right but it just appear as screenshots cuz there's some kind of weird caching issue in Windows Explorer so it does actually have the correct name just trust me I was messing with this before too uh for some reason it it has like this weird um kind of caching thing if you were to like restart the computer you should see the correct name anyways not a huge deal I'm sure for you guys that worked because I got it working before but now what we want to do is we want to schedule this to run every single day at a certain time right because we want to back up consistently so what we can do is the following we can say schedule every. day do at and we can specify a time and 24-hour time code that we want to do this backup at now for me right now it's about 652 so I'm going to just put this to 655 right now we can change that in a second and I'm going to do do and I just put the name of the uh function that I want to run whenever this schedule occurs so what we've done now is we've scheduled this task which is just a function right so notice I didn't call the function I just put the name of the function and what this will do here is call the function on my behalf now what we're going to see is that there's a little bit of an issue because we have our source and we have our destination which are parameters that we need to pass to this function so what we can actually do is write kind of a fancy line of python code which if you made it this far I will treat you with which is something known as a Lambda now I'm going to say Lambda and inside of here I'm going to put my sourcer and I'm going to put my Des J now what I've done is I've essentially written what's known as an inline or Anonymous function so the idea is this. do takes a function that it needs to call the problem is we need to pass some parameters to that function there's a few other ways to do this but one way to do this is okay we're actually going to write the C of the function with the parameters that we need but we don't want to call the function we got to pass a function to this argument so what we do is we write our Lambda and now what this does is it actually wraps a function so it says okay Lambda is a function that's going to call this so now we're saying okay well we have a function inside of here so when we have do we call this Lambda function which then goes ahead and does this I know it seems weird but it's the same thing as doing this Define l and then inside of here you put this okay so let's copy this and paste that here and then rather than writing the Lambda we just put l which is the name of our function okay this is the exact same thing so the function does this which just calls this rather than doing this we use this Lambda which is this kind of inline Anonymous function bit more of advanced python syntax but hopefully you found it cool okay last thing we need to do we're going to say while true like this and we're going to say schedule. runor pending and we're just going to say time do sleep 60 seconds now let's just move this down a bit and I'll explain so what we're doing is we're scheduling a task run every day at 655 however the way this schedule works is that it's not actually going to execute the task for us until we have this schedule. run pending call so what we're doing is inside of a w Loop which means just infinitely we are going to consistently run this run pending command which will look for any scheduled tasks that have been scheduled that haven't yet ran and it will run them for us we're then going to sleep for 60 seconds or 1 minute so we don't just constantly keep calling this but every 1 minute we're going to check because this will go up every minute right if the task needs to be ran and if it needs to be ran we'll run it if it doesn't well nothing will run so technically you could just leave this python file running forever in the background on your computer and every day at whatever time you put it's going to update your code obviously if you turn off the computer you need to rerun the python file but this is how you schedule a task to run at certain increment now you can also do every week every year every minute every second like any increment you want pretty much you can set and you can schedule a tasks in our case we did every day but you can do any increment you want now I need to make the time a bit further because it took longer to explain and we can test this so I'm going to say Python and backup. piy currently it is oh issue invalid time format for a daily job uh okay I think we need to do sorry it's cuz I have 650 7 it would need to be 0657 but what I actually want to put is the 24-hour time code which is 1857 so now if I run this it's good it's just because I didn't have four digits for my time code so actually a good error to run into there uh we want four digits now it's 6 uh 56 p.m. not 5656 a.m. s so that's why I had that issue anyways I'm just going to wait 1 minute here and we should see that it will automatically actually do the backup for us let's give this a second and I'll be right back all right so it actually worked it says folder already exists cuz the folder is already in that location that we're trying to do anyways though it did automatically run this task as soon as it hit 657 now we could just continue to let this run and tomorrow at the exact same time it would then go ahead and run this backup task okay so I'm going to close this by hitting contrl C that's how you can actually quit this program when you have it running and there you go that will finish this uh video If you're looking for a quick pipe python project that you can use to practice your skills and learn about some new python features then this video is for you what we're going to do here is build the popular game known as Mastermind this takes about 75 lines of code I'd rank it kind of intermediate difficulty and it's going to teach you a lot about python especially if you're kind of a beginner or getting into those intermediate stages I'm also going to show you how to properly lay out a program even though this is small you're going to see how an experienced programmer names their variables creates the different function and kind of just sets up the general structure of the program which is some valuable information so with that said let me give you a quick demo of the game so you understand how it works and then we'll get into building the [Music] project all right so I've got VSS code open here this is where I'm going to run and write all of the code for this project if you don't already have it I'd recommend you download it from the link in the description regardless you can still use the python idle or whatever your preferred environment is this is just what I'm using for this video now I've already ridden the project just so I can demo it for you so let's have a quick look at how it works so this game is Mastermind the general idea is you're going to have a player in this case that's going to be us who has to guess a four col or kind of four-digit code so in this case the computer is going to be the one generating the code typically you play with two people and one person is kind of the code maker okay so I've actually printed out what the code is here just so that we can see it and kind of compare to it as we go through this demo typically you wouldn't show the user what the code is so it says welcome to Mastermind attempt to guess the four-digit code you have 10 tries the colors that can make up the code are red green blue yellow white and orange so you're going to make a guess of four colors try to guess what the code is I always like to start with just one color so red red red red okay so now we can see that we have zero colors that are in the correct position and zero colors that are in the code that are in the incorrect position so now I'm going to go with say white white white white okay zero again now obviously we can see the code so let's speed this up and go with four yellows now it tells me that I have two colors here that are in the correct position and zero that are in the incorrect position that's because these two y's are in the correct position if there was another y but I didn't have it in the correct position then this would give me a one okay so now we have y y y y so let's do GG y y now it tells me I have three in the correct position but I don't know which those are necessarily so I'm going to go with maybe W actually not W let's go with like o uh actually g o y y okay and now it tells me I have two in the correct position one in the incorrect position the reason I'm getting incorrect is because I have a green here so I've put that there it's in the code but it's in the incorrect position so hopefully that makes sense that's why it's showing it to me and now we can just go ahead and guess the code all right and there we go we guess the code in six tries there you go that is The Mastermind game it'll make more sense as we go through the tutorial all right so let's go ahead and start building this project now I'm just going to spend a minute here and discuss what it is that we actually need in terms of the sub components for this project then we can build those one at a time and then kind of tie them all together at the end this is a good practice whenever you're writing code you want to think about it for a second before you just dive into the code so the first thing we need to do is we need to generate a random code this is going to be four colors or four digits whatever you want to refer to it as and they have to use kind of the six colors that are part of the game okay that's step one generate a code next we need a way for a user to guess what the code is and we want to make sure that what they're guessing is valid so if they guess only three colors or if they guess five colors or if they guess a color that doesn't exist we need to give them some feedback and tell them hey that's invalid make another guess now after that we need to compare their guess to what the real code is to do that we need to determine the number of correct colors the ones that are in the correct position and the number of colors that are in the code that are in the incorrect position so we can give them that output this is probably the most challenging part don't worry I'll walk you through how we do that after that we kind of just need to tie the game together right we need to do 10 guesses we need to constantly give the output saying this is how many correct this is how many are incorrect we need to determine if the user got the correct code and we need to determine if the user lost the game that's really all we have to do what I like to start doing is building out each of the individual components and then at the end I kind of tie them together so let's go ahead and do that step one is going to be to generate our code so since we're going to be generating a random code I'm going to start by importing the random module and now I'm going to Define all of the colors that we're going to be using so I'm going to say colorss in all capitals the reason I'm doing capitals is because this is a constant and that's kind of a convention in Python it's a variable that's not going to change so for my colors I'm just going to refer to my cheat sheet here for what we have we have red green blue yellow white and orange I don't know if these are the real colors that are used in the game but these are just the one that we're going to use and in the real game it has six colors that's why I'm doing six okay next I'm just going to Define a variable called tries I like to put all my constants at the top of the program just so they're easy to find to find sorry and this is the number of tries you get in the real game so I'm doing kind of the same thing 10 tries okay next we're going to write a function which is going to generate the code for us so I'm going to say Define generate uncore code like that now I'm actually going to make another constant called code length and make that equal to four just because if I wanted to make this game harder maybe I make the code length five and I increase the tries you can kind of make this Dynamic by changing these different values assuming that we use them properly throughout the program okay so for generating the code we need to create in this case a list the list is going to contain all of the elements in our code and we're going to have four elements so I'm going to say my code is equal to an empt list inside of my function by the way a function is just a reusable block of code that you can call mult multiple times if you're unfamiliar with it it's just something that we can use later on so I wanted to mention that okay now that we have our code list we're going to insert four random colors into that list to do that I'm going to say four underscore in range and then I'm going to go the range of my code underscore length and this underscore is essentially a placeholder for what you would normally put here which is like I or X or some value in this case I don't care about what iteration I'm on so I can just put an underscore meaning I don't really care about what that variable is it's kind of like a placeholder it's known as an anonymous variable okay what I'm going to do now is select a random element from this color list the way that I do that is I say color is equal to random. Choice and then of colors okay that's going to randomly select a color from this colors list I'm then going to say code. append and then I'm going to append that color into my code this for Loop is going to run four times which which is our code length it's going to randomly select four colors and then put that into our code okay then I can return the code from this function uh which is what I can access when I call this function so the way this would work is I'd say code is equal to generate code then it's going to give me a list of four random colors perfect okay now we have a way to generate the code the next thing we need to do is allow the user to guess the code so I'm going to make a function for that and I'm going to call this guess uncore code all right so for guessing the code we're going to have to ask them to enter some input so I'm going to say their guess is equal to input this allows the user to type in the console and I'm going to say guess colon like that now what I'm going to do is convert their guess to all upper cases just so that if they type like a lowercase G here we're going to convert that to an uppercase G so when we compare it to the real code we don't get an issue if they typed in lower case then what I'm going to do is use the split function now I'm going to put a space inside of here and what this is going to do is it's going to take all of the input and turn it into a list based on all of the spaces so for example if I have g g g g like that and I have spaces in between them then what that dos spit function is going to do is use all of the spaces to create elements in a list so I'm going to get a list that has four G's inside of it and it's going to remove all of those spaces for me hopefully that makes a bit of sense but it's just going to take all the spaces and kind of grab all of my individual colors uh using the spaces as what's known as a delimiter if you wanted to do it with commas you change this to a comma and then you would expect an input like this uh if I could type that correctly okay hopefully that makes a bit of sense but that's what split does all right now that we have a list containing all of the different colors the user inputed we're going to check the length of that list and see if it's equal to four that will tell us if they inputed four colors or not so I'm going to say if guess or if the Len of guess does not equal four then I am going to print you must guess four colors okay and really rather than doing four I'm going to change this to be the code length so that later on if we want we can change what the code length is and then here I'm going to use an FST string and do code length as well an F string is available in Python 3.7 and above and allows you to embed variables directly inside of a string using curly braces you put an F before the string and then curly braces like this and you can insert the variable directly in the string now while I'm at this I'm going to put all of this inside of a wall Loop because if they input an invalid code then I need them to go through the loop again and give me another guess so here inside of this if statement I'm going to have a continue and what continue will do is just bring me to the top of this Loop okay so if the length of the guess uh is not equal to the code length we print this and then they're going to have to guess again and keep doing that until they give us four digits lastly I need to make sure all of the colors that they guess are actually in the colors list so to do that I'm going to say four color in guess which is now a list and I'm going to say if color not in colors then what I'm going to do is say print another F string invalid color and then we'll put what the color was and we'll say try again okay then what we can do is we can break out of this then we can do is we can put an else statement here and we can say break now I'm going to explain what this means uh but here I'm just going to return my guess okay I think that's all we need uh but let's have a look at it so essentially what I'm doing here is I'm looping through every single color in the user's guess because now this is a list and it contains all of the individual colors that were separated by spaces I'm going to say if any of the colors are not in this colors list so that's all of the valid colors here then I'm going to tell them hey this is invalid please try again and I'm going to break out of this for Loop now when I break out of this for Loop what that's going to do is essentially just make it so I continue with this wall Loop now what this else statement does here is essentially check if I didn't break out of the for Loop so what I'm doing is I'm saying if I never encountered this break keyword inside of the for Loop this L statement is going to run that means that all of the colors they had were inside of the colors list because if this never happened and I never break that means every single color I had was valid okay now that brings me into the else here because I didn't break so that's what the else is doing telling you if you didn't break out of the for Loop and then from this else I'm breaking out of the while loop so this is while true so the only time I get out of this W Loop is if I pass through this for Loop and all of the colors are valid hopefully that makes sense but this is what you can do on a for loop it's actually a really cool syntax allows me to determine if I broke or not I didn't break so I'm going to break here out of the W Loop and then return with whatever the guess is that the user gave me okay so that is guess code now that we have guess code the next thing we're going to do is say check code okay and here we're going to take the guess and the realore code and we're going to check uh how many are correct all right so this is a little bit more complicated and what this involves is essentially looking through every single color in our code and first of all determining if the guessing color matches the real code color that's the first thing that we need to do that's the easy part now we can determine how many colors are in the correct position once we do that though the more difficult part is determining the colors that are in the code but that are not in the correct position the reason for that is that we could have colors that are in the correct position and we don't want to count those as being in the code but being in the incorrect position again I know this seems a little bit weird but there's a few things we have to do here so just try to follow along with me and I'll explain it as we go kind of Step by Step but step one is going to be check the the correct position then we need to check the colors that are in the incorrect position and it's important we do it in that order to make sure we don't double count a color so what I'm going to do here is I'm going to say colorcore count or counts is equal to a dictionary and then I'm going to say corrector pause is equal to zero and incorrect underscore pause is equal to zero to keep track of the colors in the correct position and the incorrect position all right first thing I'm going to do here is I'm going to say for color in the realore code and I'm going to keep track of the counts of all of the colors so I want to know do I have two Reds do I have one yellow do I have one green I'm going to store that inside of the color counts dictionary so I'm going to have something like green and then two which means we have two greens inside of the code the reason I want that is so that later when I'm checking the incorrect colors I can make sure that I'm not using colors that were in the correct position or counting those towards my incorrect you'll see what I mean but just try to follow along all right so I'm saying for color in real code I'm going to say if the color is not in the color counts which means the key right so like key meaning like this green and sorry I need to get out of this uh if the key is not inside of the dictionary then I want to add it so to add it I'm going to say colorcore count and then this is going to be at color is equal to zero and then no matter what let me just close this I'm going to say color counts at color plus equals 1 so again I'm looping through all of the colors in my real code I'm saying if this color is not a key in the dictionary then we need to add it so I'm setting that key to zero the reason for that is that if I try to increment a key that doesn't exist I'm going to get an error so if the color is not there I add it in and then no matter what I increment the count for that color in my dictionary if you're unfamiliar with dictionaries I have a ton of python tutorials I think I have one specifically on dictionaries you can check that out from my Channel all right so now that we have the counts what I want to do is find all of the colors that are in the correct position so I'm going to say for Guess undor color realore color in and then I'm going to use a fancy function called zip and I'm going to zip the guess and the real code now what this ZIP function does is the following it's going to take my two arguments and it's going to combine them into tles so if I have guess and real code let's say my guess is equal to like G and R and my real is equal to like w and yellow then what the zip is going to give me is the following it's going to give me a list that has if we could do this properly has G and W and has R and Y okay so it's going to essentially combine the elements at the same position into topples and then give me a list of that the reason for that or the reason I'm doing that is so I can easily compare them because now I have a tupple and then what I'm doing here is decomposing the tupple into its two individual elements so I'm getting the real color or sorry the guess color and then the real color which are the two elements from my tle hopefully that makes a bit of sense but that's how the zip function works so now that I have that I can compare them so I'm going to say if the guess color is equal to the real color because again these are at the same positions in our um codes then what I'm going to do is say my correct uncore positions plus equal 1 and I'm going to decrease the count from my col counts dictionary so I'm going to say color count at and then we can use either the real color or the guest color because of the same it doesn't matter at Guest color minus equals 1 the reason I'm doing this is I want to mark that this color that I just found is in the correct position so I don't want to potentially count that when I'm counting the colors that are in the incorrect position so you'll see how it work works when I start looking at the incorrect position but I'm essentially getting rid of that color from the count to make sure that I don't use it again and count it as an incorrect color because it's not incorrect it's in the correct position so now I need to kind of remove it and forget about it because I've already handled it okay now we've done all of the correct colors pretty easy straightforward with the for Loop now we need to do the same thing but for the incorrect colors so again I'm going to copy this kind of for Loop structure and now I'm going to say if the guess uncore C is in the coloror counts I could use the real code or color counts it doesn't matter if I use color counts it's checking if I have a key that exists in color counts so it's the same thing and colorcore count at the guor color is greater than zero all right sorry for the cut here but I wanted to quickly demo to you an example of a real code versus our guess and what we would tell the user user and kind of why we're writing the code the way we are so here we have our real code which is green orange orange orange and then we have our guest which is green green ww in this case what we tell the user is that they have one color in the correct position that's it they have zero colors in the incorrect position the reason for that is that the greens here are in the correct position so that means if I see another green I'm not going to say that's in the incorrect position because there's not another Green in the code that it doesn't match with right here we have these two greens they kind of cancel each other out and now as we go through the rest of the guess and we compare that to the real one we don't say to the user hey this is in the incorrect position we would only do that if there was another Green in the code so hopefully that makes a bit of sense now the reason we're going through this whole process of keeping track of the count is so that as we go through here and we see this green we make sure we don't tell the user it's in the incorrect position just because a green existed before it this green since it matched up with a green that was in the correct position shouldn't be looked at anymore hence why we're subtracting it from this color count hopefully that makes a little bit of sense but that's why we're keeping track of the counts and that's why we need to First go through and keep track or find all of the colors in the correct position then only after we do that and we determine how many other colors are left to kind of match up we go through this okay you can mess around with a few different examples and try kind of changing the code around and you'll see what I mean uh but hopefully that gave you somewhat of idea of why we're writing the code the way we are anyways what I'm doing here is I'm saying if the guest color is in the color counts so if the key exists and the key there is greater than zero meaning we still have a color that we can use to kind of match with this one then we're going to say the incorrect position plus equals 1 and again we're going to subtract our color count so color count at the guess color minus equals 1 because now we found one color that's in the in in correct position so we want to make sure that we're not going to say another one is in the incorrect position if there was only say one color to match with so we need to every time we tell the user one's in the correct position or in the incorrect position kind of eliminate that color from the code to be matching against as we continue kind of doing this check and matching all right now that we have this we should know how many correct and incorrect positions there are so we can return both of those pieces of information with correct pause incorrect pause separated by a comma uh we can just get both those pieces of information out of the function okay now we have the three main components of our game we now need to link them together with some main kind of game logic so I'm going to make another function called game inside of here I'm going to start by generating the code so I'm going to say the code is equal to generate code like that all right that gives us our code next I'm going to have a for Loop and I'm going to say four actually attempts in range and then this is going to be one one comma and then tries plus one Okay the reason I'm doing this is because the range function will go up to but not include the last value here so I'm going to just start at one and go to in this case 11 which means I'm going to go from one to 10 uh so that I have kind of the correct try number hopefully that makes a bit of sense but you'll see why I'm doing that in a second all right then the first thing we need to ask the user to do is guess the code so I'm going to say guess is equal to guess unor code very simple you can see how our functions are helpful now this is going to get the user's guess once we get the user's guess we want to compare that to the code so I'm going to say correct pause incorrect pause is equal to and then what I call this check undor code we're going to pass the guess and the code then we need to tell the user some output so we're going to say print F string and we're going to say correct positions and then this is going to be corrector pause I'm going to do a pipe and then I'm going to say incorrect positions and then incorrect undor pause okay uh very good and then it's going to ask them to guess again so that's really all we need uh although I want to check if the user one or if they got the code so actually before I do this I'm going to say if corrector position is equal to the code length that I'm going to print U guest the code in and we'll do an F string here as well and then this is going to be attempts and then tries like that and then I'm going to break out of the for Loop so I don't tell them this after I already told them that they guessed the code all right then we're going to have an else statement here and I'm going to say print you ran out of tries the code was and then I'm going to do Asis and then the code now what this will do is just print out every individual element from my list so essentially what asterisk does is just takes every individual element and kind of passes it to the print function which means the code is going to be printed space separated uh from this variable you'll see what I mean if we actually encounter this case but it's kind of a cool thing you can use to print out a list and have it look decent with kind of space separated values all right I think that's all we need uh I'm just looking here and making sure this is okay and yeah I think that's it lastly what we can do is just print kind of some intro text here so we're going to say print you know welcome to Mastermind you have and then this is going to be F string tries to guess the code dot dot Dot and then I'm going to say print and then the valid colors are and then again asteris and then this time we're going to do colors okay lastly we need to call this game function so I'm going to say if uncore name equals uncore main then game this will run the game one time if you wanted to run the game multiple times you could put this inside of a while loop and then continue asking the user do you want to play again if they enter yes you run the game again by calling the fun fun if they enter no then you just quit and stop running the game if you're wondering what this line is here this just makes sure that we're actually directly running this python file because you can import python files and if you were to import this file without having this line like let's say you just had game here then it would run the game when maybe you don't want to do that you just want to be using some of the functions that are inside of our code so this just makes sure you're directly running the python file all right I think that's going to be it for the game I want to quickly run through the code then we'll just just make sure it's working so let's go through this first we're printing you know our welcome messages we generate the code and then for the number of attempts that we have we're going to do this we say the guess is equal to guess code okay that just gets the user to guess our code we then compare the code to the real code and then we tell them or sorry we check first if they actually guessed the code if they did guess the code and we can determine that by seeing if their correct position equal to code length we tell them they guessed it in this number of attempts and then we break out of this for Loop otherwise we tell the number of correct positions and incorrect positions they had in their guess if we get to this else statement here what that means is we never broke out of this for Loop which means the user never guessed the code and the for Loop ended so they ran out of tries we tell them you ran out of tries and then we tell them what the code was Prett straightforward that is game we have check code we already ran through that guess code and generate code and then all of our constants at the top of the program and you can see kind of how this program is well laid out it's very easy easy to understand what's going [Music] on all right so now let's run our code and see if this works okay so I'm going to run it here we have welcome to Mastermind you have 10 this should say tries to guess the code the valid colors are the following I always like to start with just one color okay so correct position one incorrect position zero okay now let's try this uh correct positions two okay that tells me the Y is in the correct position or sorry not the Y the R so I'm going to go r y ww okay so now I know my Y is somewhere else so I'm going to go R Let's Go Blue y w two correct positions okay let's go r o y o and we guessed it okay nice got the code that was actually pretty lucky there that we guessed that on uh Tri five now of course we could run the code multiple times test out all of the different cases but I think for now that's it and our code is working in this video I'll share with you how to build a custom aim trainer in Python that you can make as easy or challenging as you want now this is a great project for anyone who's a beginner or intermediate python programmer just looking to work on something fun that will help you practice your skills I don't assume any advanced python knowledge in this video but I am assuming that you've worked with python before you've maybe done a project or two in the past and you have some idea about basic syntax like for Loops functions classes Etc regardless this is a great project I won't delay the intro anymore let's go ahead and get into it and I'll show you how we can build this aim trainer so now that I've gone through that let's go into a new file here and let's start working on this aim trainer but actually I'll just quickly demo it so we can talk about kind of what we need to do here so you can see that what I'm doing is tracking some different stats so I've set a number of lives that's essentially how many targets you have to miss before the aim trainer is going to finish and tell you what your stats are I've set it really high for the demo but typically we'd have this at something like three or five we then have stats that are keeping track of the number of hits you have the number of targets you press per second and the total time elapsed obviously we have targets that appearing randomly on the screen you can press on them and you'll see that they are shrinking and kind of growing as they appear so they grow up to a certain size pause for a second and then shrink back down that's exactly what we're attempting to do okay so now that we've looked at that quick demo we have some kind of idea of what we need to build here let's go into a new python file which I'm in right now and let's start working on this project now for this project I'm going to use a module called pame now pame is something we need to install so what we're going to do here is go to our command line or terminal and type pip install and then py game now I already have this installed so I'm not going to run that command for you you may need to do pip three install pame if you're on Mac or Linux you can also try python hyphen M pip install py game or Python 3 hyphen M pip install P game if none of those work I will leave two videos on the screen that show show you how to install py game okay so now that we have pame installed we can start working it so we're just going to do a few Imports here Define our pame window don't worry if you've never used pame before it's super straightforward and it's actually a really great thing to build some basic user interfaces in Python so I'll walk you through all the steps let's start by importing pame we are then going to type py game. AIT which is going to initialize pame and initialize the fonts and some other things that we need I'm then going to go up here and before pame I'm going to import math because we're going to use that I'm going to import random we're going to need that as well and then I'm going to import time okay I think that's all we need now that we've done that we're going to define the width and the height of our window we're going to create a window object and then we're going to create what's known as the main Loop for our P game project so we're going to say width comma height is equal to and then I'm going to go with 8600 now keep in mind if you're on a smaller display you need you may need to make this a little bit smaller I'm on quite a a large display so you'll see that this is kind of a good size but for some of you you may want to do 600 by 400 this is the number of pixels you're going to be using for the window okay so now that we have the width and the height I'm going to define a window object so I'm going to say wind is equal to py game. display. setor mode and inside a set of parentheses I'm going to pass my width and my height now what this we'll do is initialize a pame window and display that on the screen so this is going to pop up kind of a black window that will have an 800 width and a 600 height because we passed that inside of the parenthesis once we have this window we can then draw things onto it which we'll do in a minute so next we're going to say py game. display. setor caption and the caption for this is simply going to be aim trainer now the caption is just the name of the window you don't need to set this but I like to do this for my projects okay so now that we've done that let's create what's known as the main Loop of our program which is essentially an infinite Loop that we'll check for different events so pressing on the screen quitting the window if a Target appeared or disappeared that's what we're going to be doing inside of the main Loop so we're going to say Define main which is our main function now inside of here we're essentially going to create a while loop that will run forever until we quit the window so we're going to say while run and we'll Define a variable here called run we'll make that equal to true and inside of the while loop what we're going to do is Loop through all the different pame events and see if the user quit the window now you'd think that it's already built in when you press the x button it's going to close the window that's actually not the case here in pame what happens when you press the x button is an event will be triggered and we then need to respond to that event and close the window for the user so to do that we're going to say for event in py game. event. get now what this is going to do is Loop through all of the different events that are occurring so that will be kind of equal to the event here and then we will check if this event is equal to the quit event if it is then we'll quit so we'll say if event . type is equal to pame do quit like that then we're simply going to say run is equal to false and we're going to break out of this for Loop here okay so now what we have is a wall Loop that's going to run while this variable is true we then Loop through all of the different events that are occurring as we go through this wall Loop so pretty much every millisecond or however fast this wall Loop is running we're looking at all of the events if one of the events is quit then we're going to break the loop and get outside of it so now if we're out of the loop we're going to say py game. quit and that's going to quit the pame window and close it and then we're going to come down here and we're going to say if uncore name is equal toore main then run the main function now what this will do is just ensure that we're only running the main function if we're executing this file directly don't worry too much about this if you haven't seen it before just a nice line to add in to make sure if we import one of these functions from another file it doesn't cause this game to run so now let's quickly test this out you can see when I run this a window appears that says aim trainer which is 800x 600 and then if I click on X it closes the window and all is good perfect that's all we needed for right now okay so now that we have our main Loop implemented what we need to do is start putting some Targets on the screen viewing those targets then seeing them kind of shrink and grow so what we're going to do is create a class which is going to represent our targets so we're going to say class Target like that and inside of the class we're going to define a few variables that we need for the Target remember it's kind of growing and shrinking so we're going to set a maximum size for the Target which is essentially the size at which we want to start shrinking so we'll grow up to the maximum size as soon as we hit that we'll start shrinking so the max size will be 30 you can change all these values by the way I'm then going to say the growth rate is equal to 0.2 now this is how many pixels we want to grow the target per frame now we'll talk about frames in one second but both of these values you can adjust and as you adjust it it will make the aim trainer more difficult or easier depending on the direction you go in then I'm going to set the color for my target equal to Red uh you'll see why we want that in a second just so that we can kind of change the color Target quite easily okay next we are going to Define an initialization this is what's known as The Constructor for our Target inside of here I'm going to take in self X and Y self will refer to the Target itself that we are calling this Constructor on and X and Y will be the position where we want to place this target Target on the screen so we'll kind of randomly generate those positions and then we'll store them inside of the target object so we'll say self.x is equal to X and self.y is equal to Y we're then going to Define two variables here one is self. size is equal to zero now the size will be the radius of the target it's going to start at zero and then we're going to increase it by this growth factor until it hits the maximum size once it hits the maximum size we'll start shrinking it down so then it gets to zero and then once it's at zero will make the target disappear from the screen we're also going to have an attribute here called grow we're going to start this equal to true but then we need to make this false as soon as we hit the maximum size so we start shrinking rather than growing great so now let's write a method that we can call to update the target size which we'll need to do so we're going to say Define update and we're going to take in s now what we'll do in here is we'll essentially check if we should be growing or shrinking and then adjust the target based on that so we know that we need to start shrinking the target as soon as the current size of the target is going to be greater than the maximum size so I say if the self-d size plus the self. growth rate is going to be greater than or equal to the self. maximum size then I need to say self. grow is equal to false so as soon as I add this growth rate and it causes the size of my target to be greater than or equal to the maximum size I need to set grow equal to false okay then I'm going to come down here I'm going to say if self. grow so if we are growing then self. size plus equals the self do growth rate otherwise if we're not growing we must be shrinking so we'll say self. size minus equals the self. growth rate okay so now we have a function that will handle sizing our Target and making it larger or smaller based on if we're growing or not okay now we need a function that actually draws the target onto the screen so we're going to say Define draw we're going to take in self and we're going to take in a window object that we want to draw this target onto Now The Way We Draw Something in P game is different depending on the thing that we're drawing but in our case we want to draw a circle so we're going to say pame dot draw do Circle okay now what we pass here when we're drawing a circle is the window we want to draw the circle onto the color of the circle and then the center position of the circle Circle as well as the radius okay having all of those different pieces of information allows pame to put this on the surface so in P game we're constantly dealing with surfaces this window here is going to be our window object that we've created and we're saying yes we want to draw this circle onto the window where do we want to draw it what color is it how big should it be that's what it's asking us so we're going to put when because that's where we want to draw it we're going to put self.cut because that's the color we want the target to be and then we're going to pass a tupple that contains the XY position of the center of the target so we're going to say self.x self.y that's the center of the target then we're going to pass the radius or the size of our Target so we're going to say self. size and when we pass self. size whatever the current size is well that's the size we'll be drawing for the radius of the target meaning as the size increases we'll be drawing larger and larger circles now for now this is just going to draw a red circle however if we want to draw kind of that Target style Circle where we have you know red white red white Etc we actually need to draw four circles the first one will be the largest Circle then we'll draw smaller and smaller circles that will will overlap each other sory and cause this kind of ring pattern to appear so what I'm going to do is draw four circles here so I'll just kind of copy this down four times and what we'll do is we'll adjust the size so we'll say self do size times 0.8 now it's important that we do this by some kind of multiplication Factor so that as the size of our Target changes so does the size of all the Rings inside side of the target sorry I can't just say draw this size 20 draw the next one size 30 I need to do it dynamically based on what the current size of our Target is because it's going to grow and it's going to shrink right okay so we do time 0.8 then we're going to do time 0.6 and then time 0.4 and if you want the Rings to be spaced out differently then you can adjust these values but I think this will give us a nice ring shape for our Target now what we need to do is just adjust the size or S out the size the color of our targets so we have self. color here and in fact let's go and say we have a second color which is equal to White okay so we'll use the color variable for the red rings and the second color variable for the white rings so now I'm going to go here and change each uh kind of second target drawing here to be the second color so we have color second color color Second Color you can see that we're constantly going smaller in size so what happens is we draw this very large Circle then on top of that Circle we draw one that is a little bit smaller then on top of that a little bit smaller on top of that a little bit smaller and what that does is overlap these different circles causing us to have this kind of ring shape in pi game the order in which you draw things is important when you draw something after something else it's going to go on top of that object or overlap it so that's why we're able to accomplish this here with these four draws okay that's fantastic so now we have our Target we've created that and what we need to do is start making these targets appear on the screen so how are we going to do that well we need to go into domain here and we need to create a variable called targets now this is where we're going to store all of the different targets then what we'll do is we'll Loop through all the targets we have we'll update their size and we'll draw them on the screen but every X seconds we need to kind of place a new Target onto the screen so to do this we're going to create what's known as a custom event now this event will essentially be triggered every 500 milliseconds or 600 milliseconds or whatever we want we can then check for that event when that event occurs we can then make a new Target at a random position and add it inside of this array so let me show you how that works we're going to go to the top of our program and we're going to Define two variables here the first variable we're going to Define is the target uncore increment now this is going to be equal to 400 milliseconds now you can change this if you make it uh slower or sorry if you make it less so like 300 200 it's going to be much harder if you make it larger it's going to be much easier cuz the the targets appear later so I've gone with 400 milliseconds you can adjust that as you want next I'm going to say Target event is equal to py game. user event and then I'm just going to Define another variable here which is the target padding which is essentially how many pixels I want this to be off the edge of the screen we'll just put this here for now and then we'll kind of look at that in a second but I'll set that to be 30 okay so we have a custom event which is the target event which is a pame do user event we then have the increment which is the number of milliseconds that we want to delay until we create another Target now that we've defined those variables we're going to start using them down here sorry I didn't mean to kind of scroll through that crazy so what I'm going to do is essentially create a timer so I'm going to say py game. time. setor timer and the timer that I want to trigger is the target event then I'm going to put the target increment now what this says is trigger this event every Target increment milliseconds so we're going to trigger the target event every 400 milliseconds that's what we're doing okay so now that we have that timer what we'll do is we'll go inside of our event Loop here and we'll listen for that event and when that event occurs we'll make the target appear on the screen so I'm going to say if event. type is equal to and now we're going to use our custom event which is the target event so as soon as I see this occurring I want to create a new Target to create a new Target I need to randomly generate an X and Y position for it then create the Target and add that to my target array or my target list so I'm going to say x is equal to random. random integer and we're going to generate a random integer for X in the range of our Target padding and our width minus our Target padding now the reason I'm doing this is to ensure that my targets don't appear off the screen since we're drawing from the center position of our Target that means the radius of our Target will go to the right and it will go to the left so if I had a position like 10 10 so I'm drawing at X position 10 x position y but my target has a radius of 30 that means my target will really appear from kind of -20 here all the way to 30 right uh or sorry not 30 all the way to 40 because the radius is 30 so it's going to take up 30 pixels on each side of the X and Y coordinate hopefully that makes sense but if this is the center position then the radius kind of expands outwards so I need to make sure my Center position is such that when the radius is applied to my target it doesn't appear off the screen so that's why I have this target padding here I'm generating a random integer between the target padding and between the width minus the target padding to ensure the center position causes the target to not be off the screen now I'm going to do a similar thing for my y I'm going to say Y is equal to the random. randint and this will be again the target padding and then the height minus the target padding okay I'm then going to say Target is equal to Target and I'm going to pass my X and Y so I'm initializing a new instance of the target class then I'm going to say targets. append Target and what this will do is now push this new Target object into this list so then we can use it and loop through it great so now every X seconds every 400 milliseconds whatever we Define in the variable we will create a new Target what we need to do next is update all of our targets and draw them on the screen now what I like to do is put all of my drawing inside of a separate function so I'm going to write a new function here called Draw I'm going to take in a window object and I'm going to take in my targets now in pi game remember I told you that the order in which we draw things is important if we draw something over top of something else what that's going to do is overlap it so essentially what we need to do inside of this draw function is we need to clear the screen every single time we draw so we're going to wipe the entire screen clear by drawing something over top of it then we're going to draw all of our objects then we're going to update the display and we're going to do this every single frame so every frame we wipe what was on the screen previously then we draw onto it what we want to see next so it's kind of frame by frame rendering that's what we're doing here that's not how it works in every single system anyways what we do is we type win. blit uh sorry not blit do fill and then we can fill the window with a specific color now you can just write in a string the color you want so if want it to be yellow you can write yellow if you want it blue write blue but if you want a more specific color coding like what we have then you can use an RGB value so what I'm going to do is go to the top of my program and I'm going to say my BG color is equal to and then I'm going to specify the red green blue value that I want to draw so in this case it's going to be 0o 25 and 40 now if you're not familiar with how RGB works this is essentially three values in the range of 0 to 255 now all three of these values tell you the number of red green and blue so the first value zero means I want to have no red 25 means I want 25 uh green and then 40 means I want 40 blue and the maximum is 255 so as you kind of change these values you get different colors that's kind of how RGB Works in Python you define three values in a tuple and then you can use them inside of a function like this so I can pass my background color and now I'm going to fill the entire window with the background color next I'm going to Loop through all of my targets so I'm going to say for Target in targets then what I'm going to do is say target. draw and I'm going to pass this window object so if we go and we look at the draw function here you can see that it accepts the window so we just pass the window here Loop through all of the targets draw them all on the screen lastly we type py game. display. update now the display is only going to draw all of the things that we've kind of rendered up until this point when the update function is called so once we've drawn all of the targets and we filled the screen in then we will call update and we'll draw them onto the screen perfect that's the draw function so now we need to make sure we call the draw function so I'm going to go inside of my wall Loop and I'm going to call draw and then I need to pass my window in my targets so I'm going to pass win and targets like that now we're almost done at least with this step what we need to do next is we need to make sure that we update all of our targets before we draw them so I'm going to say four Target in targets and I'll simply call target. update okay so now what this will do is update all of the targets by updating them we're going to change their size right we're going to make them grow or Shrink depending on where they currently are in the animation now there's a few more things we need to do but for now let's run this and see what happens okay so actually just need to fix something there let's run and you see that the targets kind of appear very quickly on the screen now the reason they're going so quickly here is we haven't set what's known as the frame rate for our window so let's fix that then you should see that things get a little bit better okay so how do we fix the frame rate well inside of this W Loop here essentially what's going to happen right now is all of this stuff is just going to run as quickly as our computer can execute this wall Loop because it's kind of an infinite Loop right but what we can do is regulate the speed at which this runs by introducing a frame rate so to introduce a frame rate we're going to create a clock object we're going to say clock is equal to P game. time. clock we're then going to go inside of here and we're going to say clock. tick and we'll just put a 60 inside of here now 60 means I want you to run this W loop at 60 frames per second meaning that no matter what computer we're on as long as it can run minimum 60 frames per second then we're going to run at 60 frames here so this tick just regulates the speed at which this W Loop runs which means this code should run at the same speed on your computer as it does on mine if we didn't have this we're running based on the processor speed which can vary drastically even just based on what you're doing on the computer okay so let's go ahead and run this now and we should see that now our targets are kind of appearing a little bit better right so they're growing they're shrinking yes some of them are overlapping that's fine we have an introduced Logic for that and they're appearing on the screen now what you'll notice is if we let this code run for a while it will start to get slower and slower now the reason it's going to get slower and slower is because we're not disposing of our targets once we put them uh or sorry once we shrink them down to a zero size right now what happens is this targets list just keeps getting larger and larger and larger and larger every time this event happens what we actually need to do now is we need to make sure we remove these targets as soon as they have a zero size so we start growing them and then as soon as they shrink all the way down to zero we want to get rid of them so our computer doesn't have to handle them anymore so how do we do that well the way we do that is the following we're going to say if the Target do size is less than or equal to zero then we want to remove this target from the target's list so we're going to say targets. remove and then Target now that's just going to get rid of it and take it out of this list meaning the next time we run this code we're not going to be iterating over it which means we won't kind of be doing all of these unnecessary operations on a Target that's currently invisible hopefully that makes a bit of sense why we're doing that but we just need to remove it as soon as it has a zero size now the reason we put this if statement here and not before the update is because we want to update it first which means if it currently had a size of zero cuz it starts out on zero size and it's growing then what will happen is it will get a size of 0.2 or 0.4 whatever the size ends up being meaning we don't remove it if we just added it inside of this array if I had put this if statement before then we would never see a Target appearing on the screen because as soon as it was added it would have a zero size and then we would remove it so since we're updating first that means if we just added the target it will be growing so it will have a larger size than zero so we won't we won't remove it Sor until its size shrinks back down to zero after it has already been displayed okay so let's run this now and you'll see that the code works the exact same now what happens though is as soon as the target reaches zero we remove it and we don't get any errors okay there we go so now our targets are appearing on the screen the next thing we should probably do is make it so that we can press on the targets so what we need to do is essentially get our Mouse position whenever we click see if that's colliding with the Target and if it is then we need to remove that Target and then increment some kind of variable indicating that we pressed on the target so how do we do that well the first thing that we're going to do here is just Define some variables related to kind of our analytics as we play this game so we're going to have a variable called Target pressed which is equal to zero we're then going to have the number of clicks that we've made in total which will be zero we then want to track our time so we're going to say the start time is equal to time.time you can find the time imported all the way up here okay so the reason I'm doing this I just want to say okay when did we start running this code and then what I can do is track how much time has elapsed since we started and that will give us the total duration of the round that we're currently in now I also want to have misses now misses essentially means that we missed a Target so it popped up on the screen and then it disappeared as soon as we have a certain number of Misses then we're going to end the game so that's kind of what we're tracking here and I think those are the only variables we need right now okay so now we have those let's go here and where we have if Target size is less than or equal to zero what we need to do is increment our misses by one so miss plus equals 1 because as soon as the target is removed because the size is equal to zero that means we didn't press on the Target and it appeared and disappeared and we didn't see it so we need to increment misses whereas if we collide with the target when we're pressing our Mouse on it then that means it was a successful click okay so now what I'm going to do is I'm going to write a variable called click and I'm going to make this equal to false what I'll now do is I'll look inside of my events I'll see if the user pressed the mouse down if they did then I want to set click equal to true so then we check if the current Mouse position has collided with the target so I'm going to say if event. type is equal to and this is going to be pame do event dot actually no it's going to be pame do mouse button down sorry that's the event there then we're going to say click equals true and we're going to say clicks plus equals 1 cuz we've pressed so we're going to increment the number of clicks that we have in total okay great so we've Now set click equal to True clicks plus equals 1 now we need to handle colliding with our targets now the way that I like to do this is just by writing a simple method on each of my targets or on my target class so I'm going to go here and say define collide and we're going to take in an X and Y position which will represent the mouse position that we want to see if if we've collided with this circle all right so performing Collision for our circle is fairly straightforward because we're just looking at the center coordinate of our Mouse position versus the center coordinate of our uh Circle position so what we can do is we can simply take the straight line distance from the two points and see if that distance is less than or equal to the radius of our Circle if that's the case then we've pressed on the circle I don't really know how to explain it much more than that but essentially if you have some kind of distance between your mouse position in the circle and it's less than or equal to the radius then you're within the circle if it's greater than the radius then you are outside of the circle there's other ways to reform this Collision but this is probably the easiest so how do we get this well what we need to do is use the distance to a point formula uh and that is going to be the following it's going to be self x minus X and then all of this is going to be raised to the exponent 2 we're then going to add that to the self.y minus the Y and we're going to raise that to the exponent 2 and we're going to take the square root of all of this we're going to say math.sqrt of all of that that's going to be the distance between the two points I'm going to double check this because it's been a long time since I've written this formula and then we are simply going to return if the distance is less than or equal to the size and this is going to be the self. size okay now the only thing you need to kind of follow when you're writing this formula is that whatever order you put the coordinates in you need to maintain that so in this case I'm using the coordinates of my circle first and then the coordinates of my mouse since I'm raising this to the exponent to it essentially gives me the absolute value of this first component then the same thing will happen here all I'm trying to say is I can't Swap this and do like y minus self.y if I wanted to do that I would have to swap the other coordinate as well and say xus self.x either order works you just have to maintain the same order when you do this we'll go in this order and you'll see this is fine okay so now we have this Collide function now that we have that we can start using it so notice we've kind of tracked if we clicked here so if we did click then we want to check if we're colliding with our different targets so I'm going to say if click and then we will say target. Collide and then we need to get our Mouse's position so up here I'm going to say the mouse uncore position is equal to pame mouse. getor pause and then what I'll do is pass that position so I'm actually going to pass an asteris and then the mouse pause now when you use an asterisk inside of a function arguments what this will do is break down the topple into its individual components so that might be confusing but Mouse position gives us the XY coordinate of the mouse in P game so since this is a tupple this is considered one object right like pause is equal to XY but you can see that inside of our function right we're taking X and Y we're not taking an a tupple that contains X and Y so what we need to do is break this tupple into its individual Elements by using the asteris so when I do this it essentially takes the first element passes that as one positional argument takes the second element passes that as another positional argument so it's equal or equivalent to me passing most position zero and most position one it's just a short hand for doing that okay so we're just going to use the asteris this is known as the Splat operator okay so if we have clicked and we are colliding with this target then make it disappear so to make it disappear we'll simply remove the Target and we'll increment the targets pressed by one okay so Target pressed plus equals 1 there you go that's all we need to do for handling our Collision so let's run this now and let's see if this works and we get an error what is the error here it says some issue let me just run this again with the terminal open for some reason my terminal keeps cutting off the errors uh it says int object has no attribute self a y do self okay so I can see why we got that error so let's go back and fix this I'm sure you guys probably caught that yourself it's not y. self it's self.y okay so now let's run this and see what happens when we press the targets and notice that they disappear meanwhile if I click outside the target it doesn't disappear because well we weren't within the bounce so now we've already kind of got the core logic working here for pressing the targets what we need to do next is really just display some of our statistics and then end the game and we'll be finished with this tutorial all right so what we're going to do now is we're going to draw kind of a top bar that will contain some of the statistics uh for our app or for our round or game or whatever you want to call it so the way we'll do that is we'll write a new function here called Define draw top bar now to draw this top bar we're going to take in the window and we need to take in some stats right some information that we want to display so what we'll take is the elapsed time we'll take the targets PR rest and we'll take the number of Misses that you currently have because what we'll do is we'll kind of track the number of lives remaining until we need to end the game right so that's the next thing we need to do as well if you've missed more than three targets well we need to end the game or however many lives we Define so let's actually Define that up here let's go and say lives is equal to and let's set our lives equal to three we can then just quickly write some code down here we can say if the misses is greater than or equal to the lives then what we we will do is we'll just say pass but really this is where we need to end the game okay so if the number of Misses we have the number of targets we have impr pressed is greater than or equal to the number of lives we have then we end the game we also could just subtract from the lives but I think this is fine uh as well okay then while we're at it we'll just call draw top bar and we'll pass in the information we need so we need the window we need the elapse time well to get the elapse time we'll create a variable so we'll say elapse time is equal to time.time minus start time so remember I was telling you if we have access to the start time then we can get the amount of time that's been elapsed by taking the current time and subtracting that from the start time that's all that's doing gives us current time minus the time we started this will give us the number of seconds that have elapsed so now we'll pass the elapse time variable we then will pass the targets pressed and then we'll pass the number of Misses that we had okay uh why is that kind of highlighting here all right not sure what that's giving us that weird error but regardless let's go here okay so now inside of this function we want to draw this top bar now this top bar is really just going to be a rectangle that has some text on it so let's draw a rectangle and then we'll draw the rest of the stuff we need so let's say pame do draw. rect now this how you draw a rectangle you use rect not rectangle then we're going to draw this on the window we need to choose the color we want so I'll just go with gray and then we need to pass a rectangle object now rectangle object is going to be the X and Y of the top leftand corner where we want to draw the rectangle and then the width and the height for that corresponding rectangle so we're going to draw this at 0 because we want it to take up the entire screen 0 0 by the way is going to be the top leftand corner of our P game window okay so we always start at 0 from the top left then we need to pass the width and the height well the width of our rectangle is going to be the width of the window so we'll just pass width and then the height is going to be some defined height that we're actually going to put in a variable so we'll go here and we'll say top bar height is equal to and we'll just go with a height of 50 we can use whatever height we want but I think 50 is fine then I'm just going to pass my top bar height here and draw it there okay so now this will draw a rectangle onto the screen next what we need to do is draw a bunch of different kind of text objects on the screen that represent our different statistics so this is where it gets actually a little complicated but whenever we want to draw text in pi game we need to create a font object and then render an instance of that font so what we'll do is go to the top of our program and we'll say our label font is equal to py game. font. Sy font and then we need to pass a font so in this case I'll go with comic Sands you can pick any font you want uh that's supported by pame but I just recommend going with this and then you choose the font size in this case I want to go with 24 now you can see there's some other uh kind of things you can do here too like you can pass if it is bold it's metallic Etc in our case we'll just go with the standard comic Sands of size 24 okay so now we need to render this font so the process is create the font object then you render an instance of the font then you draw that onto the screen so the first thing we'll draw is our time so we're going to say the _ Lael is equal to and this will be our label font. render now what you do in the render is you pass a string of the text you want to render you pass one for anti-aliasing don't worry about that just pass one and then for the color you pass the color that you want it to be in this case we can draw it in Black now for the text that we want to draw here essentially we want to take our time which is in seconds and we want to convert it into minutes seconds and then milliseconds so the way I'm going to do that is I'm just going to write a function called formator time now format time is going to take in the number of seconds that we have and it's going to return to us a string that contains a number of milliseconds seconds and minutes in a nicely formatted kind of thing okay so we're going to say Millie for milliseconds is equal to math. floor which will round something down inside of here we're going to take the int of our seconds multiplied by 1,00 modulus 1,000 divided by 100 now what this will do is just give us the number of millisecs um that we want to be displaying okay I know this seems a little bit weird I'm not really going to explain it too much you can try to kind of break it down yourself it just gives us the number of milliseconds from the seconds which will contain a bunch of decimal places then we're going to have seconds now seconds is going to be equal to the int of the rounded seconds mod 60 and we're going to round this to the first decimal place okay what we're doing is we're taking the number of seconds we're modding it by 60 that'll give us the number of seconds that we have and then we will handle the number of minutes here by doing an integer division so I'm going to say minutes is equal to int and then this is seconds integer ID 60 we need the mod here to make sure we don't get something like 70 seconds or 90 seconds because that's going to be handled by our minutes okay so now actually sorry this shouldn't be seconds this should be sex like this because we need to use the same value all right now that we have that we're going to return a string I'm going to return an F string which is new in Python 3 I believe s and above or maybe 3.6 and above anyways inside of the F string you can use these curly braces to embed variables so I'm going to say minutes colon 02d now this 02d means I want to pad this number such that it always has two digits and if it doesn't have two digits start it with zero so this will format it such that you get like 0 1 02 03 or 0 0 if we have no minutes which is kind of what we want then we're going to do seconds we're going to do the same thing 02d and this is also why I need to convert these into ins because this only works when you have an INT type as opposed to a float type okay so we have our 02 02d for the formatting and then we will just put our milliseconds here like that which I actually already formatted for us and we can put that with a DOT we can do a DOT or we can do a callon up to you I'm going to go with a DOT okay so format time will give us a nicely formatted time string so now inside of our label font we're going to put an F string we're going to put time colon then we're going to call format time with the elapse time so that will give us the string that we want to display inside of here after we have time okay okay now that we have this time label we want to display this on the screen to do that I'm going to say window. blit blit is how you display another surface in this case I want to display the time label surface which we've just created I'm going to put what I want to display which is time label then I'm going to put the XY coordinate of the top left hand corner of the object I want to display so I'm going to go with 55 which means the top leftand corner of this time label will be at 55 and we will draw downwards and to the right from there to draw our text okay so I think that's all we need now uh what I'm just going to do is I'm going to take this py game. display. update out of my draw function and I'm going to put that inside of here all right so I'm going to kind of put that down here and what's the issue here it says targets pressed is not defined did I not have that defined targets press okay and then let's go here to The Click targets pressed plus equals 1 okay so I just need to fix that variable name apologize put that I have my display now outside of these two functions so we're displaying afterwards and now if we run the code we should see we get our time displaying up here nicely so notice since I drew at 5 five it's five pixels down five from the left that's kind of what we're seeing okay so now that we have the time we want to display some other information like the number of Misses number of lives Etc that we have remaining so let's go here and do the rest so the next one I want to do is the speed now your speed is simply equal to the number of targets you've pressed based on the current time so like the targets per second so the way we do that is we take the targets that you've pressed and we divide that by the elapse time so I'm going to use my round function I'm going to take targets press and divide that by a lapse time and I'm going to round this to the first decimal place so we get something like 2.1 or 1.1 or something along those lines now that we have the speed we'll create our speed label right which can be equal to the label font. render and then we can go here with an F string and we can say speed colon speed and then I'll put a t/s standing for targets per second I'm then need to put my one for the anti- yellow thing to be true and then black and then we can draw this on the screen so we'll take this paste this down here change this to our speed label and then we're just going to set the x coordinate we want to draw this at so I want the y-coordinate to be the same but the X I need to space this out from my time label so I'll just set this to be 200 so it goes a bit further to the right now let's do the rest of our labels so let's copy this so next we'll have the hits label this is the number of targets that we've currently pressed so we'll say hits and this will be targets pressed get rid of the t/s and then we'll blit that one so copy this and then draw the hits label rather than 200 this time we can go with something like 450 and then lastly we need to display the number of lives we have remaining so we'll say lives lab is equal to and then I really should just copy this so let's copy that there and we'll say lives is equal to the total number of lives minus the number of Misses that we currently have okay then we'll draw this one with the lives label and we'll draw this at 650 okay so I think that's going to be good for the top bar let's run this now and you should see that as we press targets we start updating our different stats however you'll notice that some of our targets are appearing at the top bar I'm going to show you how we fix that in one second and you can see our lives are subtracting kind of as we miss the targets okay so why are they appearing in the top bar well the reason they're appearing in the top bar is because we haven't padded where we want to render the targets based on the position of the top bar so what we'll need to do now is go to where we have the randomly generated positions and for our x coordinate we'll just say our Target padding plus the top bar height just to make sure the minimum y-coordinate is always going to be beneath that top bar so now that we've done that if we run this we should see that none of our targets will be rendered in that top bar anymore they can be close to it but they're always going to be bordering it they'll never be kind of beneath it meaning we're not going to miss them now obviously I'm performing quite poorly here because well I'm under pressure and I'm on the video I'm sure you guys will be doing better than me okay almost done here last thing we need to do is simply end the game once the user uh has no more lives so how do we do that well to end the game we are simply going to call a function that will display the user stats so very similar to drawing the top bar we're going to draw a bunch of stats onto the screen so I'm going to write another function called n screen now this is the last function we need and inside of n screen we're going to take win the elapse time the targetscore pressed and the number of clicks that you had that we can calculate what the accuracy is now what we'll do in here is we'll essentially kind of pause the execution of our code and we will render something onto the screen that displays the stats and then as soon as the user presses a button we'll just end the game okay so what I'm going to do is say win sorry win. blit and then we're going to blit the background color so that we clear whatever was currently on the screen because what I want to do is just have some text that appears in the middle of the screen so what we'll now do is we'll copy kind of all of the text we had from here and we'll paste this in but now I only want to display a few things so I don't need to display the lives anymore I can display the hits but I also want to display the accuracy okay so accuracy I don't know if I spelled that correctly and then I'm going to define the accuracy here so for the accuracy this is simply going to be equal to the number of targets we've pressed divided by the number of clicks that we had so I'm going to say round the targets pressed divided by the clicks multiplied by 100 we'll round that uh actually do we even need to round this yeah we'll round that to one decimal place okay so this is going to be the accuracy that we have so now we'll just change this text to be accuracy and then we'll display the accuracy and then percent now what I'll do is I'll take these different labels and I'll just render them in a slightly different position on the screen so that it uh is in the center right cuz here we're displaying them on the top bar now we want to display them in the middle of the screen so to display them in the middle of the screen I'll actually copy this rather than the lives label now have the accuracy label and we just need to change these here so that we're rendering in the middle of the screen now the way we render in the middle of the screen when we're using a label is we need to take the middle coordinate of the screen okay so it's a bit difficult to explain this uh visually or without having visual so let's actually go into paint quickly here let's imagine we have a screen okay if we want to display something in the middle of the screen like this the natural thing to do would be okay well let me just find kind of this middle X position and then start drawing here well that works if you have something like a circle where you're drawing in the middle of the circle but in our case we're drawing from the top leftand Corner which means if we draw something from the middle coordinate we end up drawing it to the right and down so what we actually need to do is draw from the middle so let's say this is X over 2 minus the width of the object we're drawing minus two or sorry not minus two over two so if you take the width of the object over two which is this right here and you now move back by that to here then you start drawing the object in the middle of the screen hopefully that makes a bit of sense what I just explained we're going to take the kind of width of the entire screen divide that by two then subtract that by the width of the object that we're drawing over two that will then give us the EXP position where we need to draw the top left hand corner such that the object will be in the middle so let's get rid of that and let's make a function that calculates that for us so we'll say Define get middle this is going to take in a surface okay and what this is going to return turn is that middle position so we're going to say width over two minus the surface. getor width over two so now we can use this function on our different labels to determine what x coordinate we should draw them at so we're going to say for the time label well we want to draw this at get middle of the time label then for the speed this is going to be get middle of the speed label and then for the hits this is going to be get middle of the hits label and then for the accuracy get middle of the accuracy label okay so that should be good and that should draw everything on the screen however what I want to do is have it so it kind of pauses until the user presses something so what I'm going to do here is I'm going to manually update the screen so py game. display. update I'm then going to run a while loop in here that will wait for the user to press something once they press something it will then close the screen so I'm going to say run equals true I'm going to say while run I'm going to say for event in pame do event. getet I'm going to say if event. type is equal to pame Dot and all capitals quit then I am simply going to say quit like that otherwise I'm going to say if event. type is equal to pame and this will be Dot and we'll go with key down so this just means if we press any key down then I'm going to say run equals false and I will break out of this Loop now what this quit function will do is just completely quit the Python program for us and then what this will do is kind of just exit the loop which will then cause us to get out now what I could actually do is just put quit here as well or I could make this even a little bit more elegant and I could copy this all and say or it equals this and now we just have that in one line so we really just have this one wall Loop this just kind of running forever and just waiting for us to press and any key or to click quit as soon as we do that we just close the window okay so now all we need to do is call this end screen function as soon as we uh kind of lose the game so we'll go here and rather than pass we'll call end screen and we'll pass this the information we need so we need the window what else do we need the elapse time the targets pressed so targets pressed and the number of clicks okay so now we should be fully finished our program let's run this and make sure it works and let's just see what happens now if we kind of click a few of the things here and then we kind of let some of our Lives run out okay two one and we got an error let's see what that error is uh was it an error or did it just quit immediately let's see here give this a second okay argument one must be pame surface not tupple uh wind up blit ah okay sorry about that guys let's go fix this now go in end screen and rather than wind up blit this is going to be win do fill so we need to fill with the background color not blit with it that's my bad let's give this another shot here click a few targets okay and now let's lose so two lives one live and it shows our information however it's showing it all on one single line that's because we didn't change the Y positions so let's make these like 100 200 300 and 400 and while we're at it let's change the color here to be white because black is a little bit of an eyesore there on the blue background so let's change these all to be white and white and let's run this and now let's just run a few targets or click a few targets and kind of let this lose and see if it displays correctly for us all right so there you go we got our time our speed our hits and our accuracy and we have finished this project in this video I will be teaching you some valuable python scripting skills by running you through a complete project specifically I be showing you how to deal with command line arguments how you can copy different files or directories search for different files or directories use modules like OS Sy subprocess and a bunch of other modules that are very helpful when you're trying to create python scripts that can automate workflows and just make your life easier personally just knowing a few of these commands has helped me and Sav me countless hours in different development projects and the project that I'm actually working on here with you is kind of a variation of something I actually had to do when I was working for my startup and creating kind of an advanced script that had to go through and automatically compile a bunch of code for me anyways thank you guys will find some great value in this so with that said let's get into the video all right so let me start by walking you through the project that we we're going to complete now this is a project that kind of mocks what you would be doing in a real world scenario obviously I don't know what you guys need to automate or what scripts you need to write so I've tried to create something that's very general that allows you to get a bunch of knowledge in a ton of different areas so this may not cover everything you need to do but it will give you a ton of that base knowledge and show you what's possible with python scripting and how you can kind of set up these scripts to be as effective as possible and what commands you should be using for a lot of the common operations so let's have a look at it here first thing that I want to look at is just the directory I have on the left side of my screen now you guys can download This by going to my GitHub uh I will leave a link in the description of course and just clone the repository download the repository and get access to this data directory here now this data directory is going to kind of simulate kind of a large project some code or some files that you would already have and that you want to Traverse through and do something specifically with now that's usually what automation is or scripting is for me in Python it's going through some existing data or an existing file structure and kind of parsing things out grabbing specific data looking for certain names or writing code into different files so I've tried to kind of emulate that here so you can see we have this data directory here and inside of here I have a bunch of stuff right I have some empty directories I have some directories that are representing kind of games that would be written in go I have some random python files they're just empty just for example purposes I have a text file I have another kind of go file here and you can see that there's a bunch of stuff in this directory now what we're interested in here for this kind of mock project is parsing out all of the game directories so what we want to do is want to take all of the games that are inside of this directory we want to copy these into a new directory we want to change the names of the directory such that we don't have this game kind of suffix on them and then we want to compile all of the game code that exists inside of these game directories now this is something I actually had to do when I was working for my startup as I mentioned in the intro so I've kind of put a variation on it here now to go even a step further once we get all of this game data we parse it out we put it into a new directory and we compile all of the code I want to write a Json file into that directory that gives us some metadata or information about what we just did so how many games are there what are the name of our game directories Etc and that's something that we could kind of quickly look at to get a summary of the information so you could imagine this would be something similar to what you may want to do when you are writing your own Python scripts okay so I have uh kind of the project text here excuse any spelling mistakes that are in this file but I just wanted to walk you through very organized step by step what we're going to be doing some so some assumptions here sorry uh the data directory contains many files and directories so imagine this is massive right there's a ton of different code in here and it's not feasible for us to do this manually we want to have a script that automatically does it for us obviously that's not really the case here but again kind of picture that we had you know thousands of files in that case it would be very helpful to have a script to help us do this you are only interested in the games contained in this directory so you don't care about the rest of the junk in there you just want the games which are going to be stored in a directory that contains the word games so whenever we see the word game and that's in the directory name that we know that we're interested in that directory next each game directory contains a single Doo file that must be compiled before it can be run okay perfect that makes sense and these go files could be named different things notice one is called main one is called code one is called file so we're going to have to do um kind of special stuff to handle these different names and compile all of this code okay so now what are we going to do for this project well we're going to find all of the game directories from the data directory we're going to create a new slash games directory or whatever we want to call it that's going to contain all of our game code we're going to copy and remove the game suffix of all of the games into the games directory so that means copy the directory strip off that kind of game aspect of it put it into the new directory we're going to create a Json file with the information about the games so how many games what the game names are Etc we're going to compile all of the game code and then run all of the game code now we may not actually run it here but we will at minimum go to the compile step perfect so the only thing we need to do here to get started is make sure we have python installed I'm going to be using python 3.9 I believe but I think anything above 3.8 should work and if you want to be able to compile and run this go code then what I'm going to suggest to you is that you download a go um interpreter or compiler so let me just bring this up here go code I'll leave this link in the description as well but if you go to go dodev pretty simple URL click download it will download and install go it will automatically add it to your path then you'll have access to the go command that we'll be using later in the video last thing if you want there's some helpful extensions here here in VSS code if you're using VSS code you probably want to install the python extension and the go extension as well okay so now that we've got through that let's start writing our code so I have a python file here called get game data you can call this whatever you've want and notice I've put this in the same directory as where my data directory is now you don't need to do that but it is going to be helpful to have it kind of close to the data directory so you know the path to where that is so again if you want go to the GitHub I'll leave that link in the description download this code it will have the finished code as well but you can just kind of delete the file and write it along with me if you want and then you'll have this data directory so you don't have to kind of create this on your own so you want to work in a python file that is in the same directory as the data directory now the first thing we're going to do here is just import a bunch of modules that we're going to be using so we're going to import the OS module which I believe stands for operating system we're going to import Json which is how we're going to work with Json files we're going to import shtil pill uh which is going to allow us to kind of do some copy and overwrite operations we're going to say from subprocess import and we're going to import pipe and run now this is going to allow us to run really any terminal command that we want so we can for example compile and run the go code using this and then we are going to import Sy which we are going to use to get access to the command line arguments so the very first thing I want to start by doing here if we go back to our project text is we want to find all of the game directories from some directory in this case is called SL data we want to create a new directory some kind of Target directory where we're going to be copying this into so what I want to do is I want to grab from commandline arguments what the source directory and the target directory is relative to the current path so that I know where I should be storing kind of all of the games that I find and where I should be looking for those games to make this script a bit Dynamic so what is a command line argument well let me just show you down here in the terminal so a command line argument is something like python I pass my uh file name so get game data and then I do something like Hello World okay so hello and world are command line arguments you've seen this before whenever you've ran any commands like when you make a folder MK dur and then you put the folder name the folder name is a command line argument so in this case we might do something like python get game data then we pass slash dat which is going to be our source directory and then we pass something like Slash new games or something like that and that's our output or Target directory so I want to show you how we can parse out those command line arguments so to do that we're going to use the system uh module so first I'm going to say if uncore name is equal toore main then in here I'm going to grab the uh command line arguments now the reason I'm using this is because I only want to execute the main script here if I'm running this python file directory uh directly sorry if I'm not Direct directly running this python file I don't want to be executing the code that's going to run through and do all of our operations uh otherwise if we tried to import the python file and we didn't have this line it would go ahead and run all of that code when we don't want that to happen so when you have this here this just checks that you ran the file directly and it won't execute anything in here if you were importing say a function or class or something from this file hopefully that makes sense what I'll do here is say args is equal to sy. argv okay now just to show you how this works we'll print out args and let's run our code so I'm going to say python get game data data new data okay hit enter and notice that my command line arguments are first of all the name of the Python file and then I have my two command line arguments so data and new data that I passed here now if you are on Mac you will probably need to run Python 3 get game data okay so now that we have our arguments I want to make sure that we have a valid number of arguments which in this case is going to be three three because we have the file name and then we have the two extra arguments and we want to make sure we have those two extra arguments so I'm going to go here and say if the Len of args does not equal three then I will raise an exception and here I will say You must pass a source and Target directory only okay so that's fine so now if we run our code here and I only pass for example The Source directory then notice that I get my exception if I pass my target as well then all is good okay so now I want to get my um source and Target directory so I'm going to say Source Target is equal to sy. argv and then I'm going to do one like this and actually we can put this as args now the reason I'm doing one is just to strip off the name of our python file which we don't want and just get the two arguments here and then store them in separate variables okay now that we've done that I'm going to create a function and this main function is going to accept our source okay and our Target and I don't know if that's actually the right thing that we want to call it um yeah I guess that makes sense source is where we're looking Target is where we want to put our new directory so that's fine we can leave it like that and then here we'll go and call the Main passing our source and Target directory names perfect now that we've done that what we actually need to do here before we go any further is we need to create a complete path from the location where we're running our python file to whatever this directory is so in the case where I pass you know data or Target well I want to get the full qualified path from say like my C drive all the way to this directory so that it's going to work in my program if I if I just try to use data or I just try to use Target uh we can get some weird errors depending on what operating system we're running on so what I'm going to do here is say my source _ paath is equal to os. path. jooy and the first thing we need here is the current working directory which I can get by using the command I got to check my she cheat sheet here because I always forget os. getet CWD okay so I'm going to join the path of CWD and my source directory now now you should always use os. path. jooin when you're trying to create paths don't think you're going to be clever here and have a path like you know C drive colon SL slash and then you add like you're doing a string concatenation don't do that the reason you should not do a string concatenation is because if you're working on different operating systems the path dividers are different when you use os. path. jooy it automatically will join the path based on the operating system you're working on so you always want to use this don't do string concatenations uh to try to create paths it might work sometimes but it's not kind of a good practice to do that okay so we've created our source path now just with to explain this line here CWD is our current working directory which means the directory we ran this python file from so wherever we ran this python file from uh that's the working directory so in this case it's going to be users Tim desktop python scripting then whatever these paths are are going to be relative to that working directory so I combine them together right so now directory will be this and then it will have my source which would be data right and the next one will be my target okay so let's copy this and make this Target and change this here to be Target okay so now we have our source path and our Target path now what do I need to do next here well I need to find all of the game directories from my source directory so let's write a function that can do that we'll say find all game d like like that we need to know where to look so we go Source okay now I'm going to create a variable up here and this is going to specify what we're looking for in our directory so like what needs to be in their name so in this case I'm going to say game dir pattern is equal to and we'll just call this game which essentially means we're going to look for the string game in any directories uh and that will tell us that we want that directory right now what we're going to do is we're going to to essentially walk through the source directory look at all the files and directories and then match any directories that have this game in them um and if we have that then we'll add them to a list we'll return them Etc okay so let's do this I'm going to say my gamecore paths is equal to and this is going to be a uh what do you call it just empty list and actually I want to change this say find all game paths because it's going to give us the full path not just the directory name next I'm going to say for or root I believe this is going to be dur files in os. walk and I'm going to walk the source path okay now what walk will do is walk recursively through whatever the source directory is that you pass uh to this this os. walk command so it's going to give you the root directory the directories and the files that are contained in the current level that it's walking through now what this will do is recursively continue to look so in this case it'll look in data but then it would after looking in data look inside of blank then look inside of hello world then look inside of rock paper scissors game it would look through all of those directories now we only care about the directories that are immediately inside of data however if you wanted to recursively look through all of them this is what you would use hence why I'm showing it to you here now since we only care about the first kind of top level directory we only really need to run this command one time so at the end of my for Loop I'm just going to put a break so that I only do this once and this is just an easy way for me to grab kind of all of the values one time right so you just break at the end of the four Loop so we only run this one time okay now that we've done this uh we need to Loop through all of the directories so I'm going to say four and you should not use dur because that's a built-in command so I'm going to say directory in dur like that and then I want to get the name of my directory and match that against my game dur pattern so what I would do is say if my game dur pattern is in my directory. lower and I'll put this lowercase just in case we have a capital game or like a capital on the G or something like that you don't have to do this but I think it makes sense to do that if this is the case then I'm going to add this path uh to my game paths so what I will do here is say my path is equal to os. path. jooy and then I'm going to take my source and I'm going to take my directory like this and I'm going to say game paths do append my path okay then down here we will return our game paths now the reason I'm doing this is because this uh dur list here gives me all of the names of directories not the paths to those directories now here I want the full path the reason I want the full path is so that I can easily copy it later on if I don't have the full path I can still create that full path but it's just easier to return all of the full paths right now so that's why I'm doing it so I'm saying path is equal to os. path. join taking my base path where I know this directory is contained inside of and then I'm joining them together right taking the directory name adding it to the base and then adding this to my array or list of paths and then I will return that fantastic so let's try this out now uh and make sure that this works so let's say our gamecore pass is equal to find all Game Pass and and then we'll pass here the source path and will'll print our Game Pass okay so let's give this a shot here and see if we get any errors or not so here we're going to pass data that's going to be our source directory so make sure you have data there and then Target will be our Target although it doesn't matter right now all right so notice now that I get my full paths to all of the directories that contain the name game so I have my hello world I have my rock paper scissors game and I have my Simon Says game now not no that I've ignored the blank directory I've ignored any files even if my file had the name game inside of it because I was only looking in directories fantastic okay so that is working the next thing that I want to do here is I want to take all of these paths and I essentially want to just get the new directory name that I want to copy these directories to I know this seems a bit weird but remember what we're doing here is we're taking all of these directories and we're copying them into a new directory but we're removing the game part from that directory name so when I copy you know Simon Says game I'm just going to copy Simon says not the game part into a new directory so I need to get that kind of destination path before I can perform that copy because to do a copy I need a source I need a destination right now we just have the source so we have to create the destination now one thing we also have to do is create the new directory and we can actually create the new directory right now so let's make a new um function here and say creatore dur and all we'll take for this is the path to the directory that we want to create inside of here I'm first going to check if this directory exists if it exists I don't need to create it if it doesn't exist then I will create it so I'm going to say if not and then this is OS do uh actually is this going to be I think it's os. path. exists yes okay that's correct so if this does not exist then I will say os. MK d which stands for make directory and I will make the directory at this path okay that's it for creating the directory so let's go here and let's say creat D and the directory that we want to create is going to be the target path right so we'll just pass the target paths path there sorry okay next we want to get all of those destination paths so I need to make a function that is essentially going to look at this whole path and it's just going to give me the directory name uh but removing the game aspect now I know this seems a bit backwards how I'm doing it I'm doing it intentionally so that I can show you how you strip apart paths and take like certain components of the path so believe me I know there is an easier way to do this but I'm trying to show you like how you can use a lot of different commands here so hopefully appreciate it anyways let me just quickly look at my cheat sheet here okay uh and I'm going to say that this is called get name from path and I'm going to take in my paths and I'm going to take in what I want to strip off of my directory name so I'll call that two strip I don't really know what else we would call that okay so I'm going to go here and say new names is equal to an array and I'm going to say four path in paths now what I want to do is I want to split my path into the just the directory and the base part right so like The Parent Directory of just the directory because remember we have the full entire path so when we had game passs we have the entire path to the game directory so we're going to split it to just the game directory and then whatever that base path is now the way we do that is we can say underscore because we don't care about the beginning part and then we can say duror name is equal to os. paath dosit and then we can just split the path now this is automatically just going to give you the very last aspect of the path whether it's a directory or a file or whatever it is and then the remaining part of the path on the left side again don't try to get clever and do this Yourself by splitting different uh like slashes or trying to find the PATH divider just use these buil-in functions because they handle the different operating systems for you okay so now we have the dur name now what we need to do is remove the game aspect or whatever aspect from this durame so I will say new durame is equal to my durame do replace and I'll replace whatever the two strip string is that we pass which will be game with an empty string which will'll just get rid of it from the uh the directory then I will say new names do append my new dur name then I will return my new names fantastic okay so now let's get our new names so let's say new game dur is equal to get name from paths and our paths are going to be the game paths and to strip we're just going to strip off the string game fantastic now let's print our new Gamers all right now notice I've have create directory as well so we should see that a new directory gets that's created here when I run this let's try it and see what we get and notice now that we get Hello World rock paper scissors Simon Says plus the target directory was created so I'll delete that uh so we can create again later okay now we do have the underscore here now that makes sense right because we're just looking for game now in this case we can look for underscore game and we can remove that entire thing but it's up to you how you want to do this right if you look for underscore game then if you started the directory name with just game it wouldn't count or wouldn't remove it so can do some Advanced logic to remove this if you want but for now we'll just make it underscore game I think you guys know what I'm saying here okay so let's clear that uh and what do we need to do next well now that we have our kind of destination our source directories for all the games as well as where we want to put these games now we need to well need to write them right like we need to actually do the copy operation so what I'm going to do is make a new directory uh or new function not directory and I'm going to call this copy okay now what copy is going to do is take a source and a destination and it's going to copy the source into the destination now I will actually um kind of change this a little bit and I will say copy and overwrite now the reason for this is that if the directory already exists I want to overwrite it and I will show you how we can do that now keep in mind the commands I'm going to use here are just one option to do this there's like a million ways you can go about copying and deleting directories but I'm going to show you how we delete a directory if it already exists and then of course how we copy it and this will be a recursive copy which will copy everything so if there was another directory inside it would copy that directory as well and all of the contents of that directory a lot of the copy operations don't do that so just keep in mind if you want a recursive copy you probably want to use the option I'm showing you here so I'm going to say if os. path. exist destination then I need to start by removing the destination folder which I'm going to use my Shu till uh for so I'm going to say Shu till. RM tree which stands for remove tree which is essentially a cursive delete and this is going to be the destination now after this I'll say s huil do copy tree and then I will copy the source to the destination all right that's all good that's all we need for copying and overwriting or overwriting however you want to I think overwrite is the correct term there okay so now that we've done that we can use this function so we need to essentially Loop through all of the different paths that we have so The Source paths as well as the destination paths and then we need to run this copy command so I'm going to say for and we'll call this uh SRC destination in I'm going to use this ZIP function I'll explain how this works in one second but I'm going to pass my game paths and my new game directories I'm going to start by saying my destination path is equal to os. path. jooin and I'm going to join my target path with my destination folder name then I will run the copy and overwrite function with my SRC and my destination path okay so let me explain how zip Works what zip will do is it will take matching elements from two arrays and combine them into a tupple which then gives me access to them at the same time so notice right these arrays or these lists are going to be the same length so this first one is going to be all of the original game paths and this is going to be our new game directory names that have this underscore game removed now I want to be getting the game path associated with the new game directory name because I want to copy whatevers here into this new directory name so I zip them together so show you a quick example if we have one 2 3 and we have like a b c then if you zip these together what you're going to get is an array that has one and a or a topple sorry that has one and a 2 and B Etc it just combines them together so the matching elements at their indices get kind of matched up and that's why I can say Source destination here and iterate through the zip okay so now this should actually be good however I need to make sure that I create this directory before I do this otherwise we're going to get an error where it say our path doesn't exist okay so let me slow down for one sec I'll explain what we've done we can run it and then we can continue so what we've done here right is we've gotten the source path as well as the directory path we have found all of the game paths that we're interested in so essentially those d dories from The Source directory we have then found what we want our new game directory names to be we have then created the target directory where we want to copy all of these into and now we are actually performing that copy operation okay so we're at that point so let's run this and see how it works so python get game data and then we're passing data and Target I hit enter and when I look in Target here you can see I now have Hello World rock paper scissors and Simon Says with the contents of those directories CU I just copied them in perfect so now let me delete this and we can continue so the next thing I want to do is write a Json file that just has some metadata about the different games so what the game directory names are and how many of them there are this is fairly straightforward so let me create a function I'll say make Json metadata file and here I will just take my path so what do I want the file to be or where do I want it to be and then I will take my game dur okay now here I'm going to say that my data this is the data I want to write into the Json file is going to be equal to I will say my game names is simply my game directories and I will say number of games and this will be the Len of my game very straightforward not the most useful data but just want to show you how we write Json so now there's a few ways to do this but the preferred method is to do the following I'm going to say with open path in W mode W stands for right this will override the file if it already exists if you wanted to read the file you'd use R so I want to write and override if it exists so I'm using W and I'm going to say as F and then I'm going to say json. dump and I'm going to dump my data into my file now if you've ever seen Json be used before with dump s dump s stands for dump string and that's going to dump the uh Json data you have into a string we don't want that we want to dump it into a file or just really save it into a file so we pass the data that we want to save which in this case is a python dictionary which can kind of be represented as a Json object and we want to save it into this file object that I'm opening using something known as a context manager now the reason I use this is because as soon as we're outside of this with we are automatically going to have the file closed for for us if we didn't use wi we would have to manually close the file and there can be some problems doing that especially if an error occurs before we're able to close the file we can have kind of a memory leak going on so it's just preferred to use this it's referred to as a context manager that just makes sure your cleanup operations happen no matter what essentially okay so we have this uh Json metadata file so let me copy this function let's paste it here we'll say make Json metadata file and now we need to pass a uh path that we want to use so I'll say Json path is equal to os. path. jooin and I will join my target path with my metadata. Json name so I've just come up with this name you can name it anything you want and then I will pass here the Json path and my new game dur right there we go okay so let's run this again and see if it creates the Json file okay go go to Target and notice we now have our Json file if I save it will auto format here and you can see we have our game names and our number of games fantastic okay so let me delete that all right now that we have done that I need to show you how we can compile this go code and how we can run the go code all right so let's write a function here that will allow us to compile the code inside of a directory now let me just space up my functions here so bit easier to read okay and let's do it here so Define this will be compile game code now here we'll take a path which will be the path to the directory we want to compile the code inside of now what we need to do here is we need to locate or determine the name of the file that we want to compile you know no pun intended or rhyme intended there but you know what I mean so we have main we have code we have file now in this case we get hard code that but we don't want to do that we want to have this Dynamic so it works with kind of any go file no matter what the name is so essentially we're going to look through the directories of our games uh and we're going to search for any file that ends in Dogo right so let's create a uh variable here and say game code extension and I'll just make this.o so that's what we'll search for now if we find that uh then we'll compile that code now we could compile all of the files that have that name or we could compile just the first one and this case I'll just do the first one because we're assuming we only have a single code file in each of our directories all right so let's say code file name is equal to none uh and then let's walk through this directory like we did before so we're going to say root dur files in os. walk our path and this time we're only interested in the files so I'm going to say for file in files and let's not forget to break here at the end of our four Loop so we only do this one time not recursively okay so four files in files I'm going to say if the code what did I even call this the what game code okay game code extension if the game code extension is in the file then I will say my code let's do this my code file name is equal to file and then I will break okay that's actually all we need I know I went fast there but that's all we need to determine what the name of our code file is so we Loop through all of our files here right so for file and file and we say okay if this Dogo extension uh is associated with the file then we'll say code file name is equal to file uh and then we'll break which means we'll just find the first one we don't need to continue looking now what I just realized though is that this could be a little flawed because I could technically have a file that's likego dopy I know that would be a weird name but that wouldn't be a dogo file that would be a python file right well I think that a python file but it would be a bit weird either way if we had something like that so what I'm going to do instead uh is use a little bit of a better way of doing this I'm going to say if file do ends with so I'm going to check if this is at the end of the file I think that's a better way to do this check okay perfect so now what I'm going to do is I'm just going to make sure that we did have a code file if we don't have one I'm going to return if we do have one then I'm going to run the command to compile this so I'm going to say if the code file name is is none then just return just so that we don't get an error when we try to compile a file that doesn't exist now we need to actually compile the file so the first thing I'm going to do is say my command is equal to and then I'm going to make a variable up here which will be my compile command so I'm going to say game compile command now the way you write these commands is just in an array of or I keep saying array and a list of strings that represent the commands that you need to run so it's going to be go and then build so this is the command go build then whatever the name of the file is so this is my like base command so I'm going to say my command is equal to my game compile command plus and then I'm going to put another list here and I'm going to add inside of here the code file name now what this will do is make the command be go build and then whatever the file name is then I can pass this to a function that I'm going to write which will just run any command that I pass it so we're going to say run command uh we do actually need the path that we want to be running this command from okay so now I'm going to say that our current working directory is equal to os. getet CWD is that is that what it is get CWD yes that's correct and I'm going to show you how we change our working directory into this path the reason for that is that I need to run this command well I don't need to but I'm going to run this command directly in the directory where our game code is so rather than being in the directory where my python script was run I'm going to change into that directory run the command and then change back to a different directory just to show you how you do that so I'm going to say OS uh CH dur which stands for change directory and I'm going to change into the path directory then I going to go and run the command now to run the command we're going to use the subprocess command run which I believe I imported from up here yes I did so we're going to say run and we're going to run our Command and we're going to say our standard output is equal to pipe and our standard input is equal to pipe and I'm going to say Universal new lines is equal to true now this is where the command gets a little bit complicated right um you know what does all this mean well the standard output and the standard input is the location where the command is well accepting input and spitting out the output now pipe is kind of kind of this special thing that we can use that makes a bridge between our python code and the process that we're using to run this command now I'm not really going to explain it more than that but just understand that that's why we're putting it here it essentially allows us to communicate between the process that can actually run this special command because this command is not a python built-in Command right like this is a command we just run in our terminal or in our Command problem again you don't have to understand it maybe that explanation was good maybe it wasn't but this is how you do it you import run and pipe from sub process you pass the command again the command is just going to be an array of all of the different words that are in that command or a list of all of the different commands uh and then if you wanted the result uh it will be given to you in this result variable so you could print out the result you could read it in as a Json object blah blah blah you could do whatever you want and you could see what that result is and in fact we'll print out the result uh just so you can see what it looks like so I'll say compile result like that okay now the last thing we'll do just as good practice is we're going to change our directory back to the current working directory we were in before we ran or before we changed directories into this path just to make sure when we run this command another time uh we don't get any potential errors okay so we got the working directory we were in changed into this path directory ran the command and then we went back into whatever the previous directory was just so that we don't have any potential problems here now we need to call this function so we'll say run command uh and command and path that's actually fine we can just pass those values great so now where do we call our compile game code function well we're going to call that from inside of our copy here so I'm going to say compile game code and I will compile game code in the destination path because once we've done the copy and overwrite once this is finished now that directory exists let's compile the game code then move on to the next directories so at this point the project is pretty much finished let's run it though make sure it works okay compile result compile result and notice it gives you kind of this like result object right I'm not going to uh again kind of dig into exactly how this works but you can see that if you wanted to look at the standard out then it would be STD out from this compiled process or sorry not compiled completed process and if this had any result like if there was an error you'd be able to see it there and the return code would most likely be an error return code as well now let's look at Target here so we have Target we have hello world and now notice inside of my directories I have my compiled code right I have main.exe code. exe file.exe Etc if you were on Mac or Linux you would get I believe a sh file uh or an executable file on your operating system it would be different than if you were on Windows okay so I think I'm going to wrap up the video here all of this code will be available on on GitHub I will also zoom out a bit and kind of slowly scroll through in case any of you want to pause the video and have a look at any of the lines here but I thought this was a useful project just to teach you some basic kind of automation I don't want to call it automation scripting um syntax tools commands you can use in Python I write code like this all the time in Python it's really helpful this is kind of my go-to language when I need to do like file or file system operations so hopefully you guys found some value from this and of course if you did make sure to leave a like subscribe to the channel you guys can check out my programming expert course if you want to learn how to become a python programmer or a software engineer as fast as possible and I look forward to seeing you in another YouTube [Music] video