[Music] hello and welcome to nearly nine hours of python tutorials and instruction for beginners this video is made up of 23 tutorials that build upon each other much like the chapters of a book throughout the lessons in this video I will mention links being available in the description below I've compiled all of these links into one GitHub resource that you will find in the description hi I'm Dave gray and I'm the creator of these python tutorials for beginners you can subscribe to my YouTube channel for more tutorials like this one you can also follow me on Twitter and if you're feeling generous you can even buy me a cup of coffee let's get started learning python with chapter one python is a great first programming language to learn but if you already know another programming language like JavaScript python is still a great addition to your resume congratulations on your decision to Learn Python it's a great first or additional programming language to learn but don't take my word for it I asked chat GPT why anyone should learn Python and here's what it had to say python is easy to learn and use it has a simple and straightforward syntax and it's an excellent language for beginners versatility python is a versatile language and it's used in a wide range of applications from web development to Scientific Computing and data analysis a large and active Community python has a large and active community of users and developers and there's a lot of resources and support available for you good for rapid prototyping python Simplicity and ease of use make it an excellent choice for rapid prototyping and job opportunities as one of the most popular programming languages Python's in high demand in the job market top five reasons essentially that python is a good programming language to learn and add to your resume and we need to start with the right tools so go to python.org which you should see here in my URL bar and from there we can download python so there is a downloads Tab and when you Mouse over it should show you the current download for your operating system as you see I'm on Windows here and it says we are currently at python 3.11.2 of course if you're watching this in the future there may be a newer version now if you're not on Windows you can also choose Mac OS or other platforms over here and note here it says Windows note that python 3.9 plus cannot be used on Windows 7 or earlier so if you're using Windows 7 or earlier maybe you need to go to this Windows link and find an older version of python to run which should still allow you to complete this Python tutorial so for now click on the download for your operating system download and install Python and then come back to the video now that you've got python downloaded and installed we're going to install a code editor and there are many different ones to choose from my choice is Visual Studio code and I'm going to use it throughout the following in Python lessons as I build the course so to follow along with me I recommend that you download and install Visual Studio code for your operating system again the website should identify which platform you're on Windows Mac Linux Etc and I'm at code.visualstudio.com and then download the version for your operating system and install that after you install go ahead and open Visual Studio code and then come back to the video and now with Visual Studio code open on your machine you should see some type of welcome screen like I have here you can go ahead and click the X to close that we won't need that but afterwards we need to install the python extension for visual studio code now on the left hand we see the activity bar and we need to click the extensions icon right over here on the left so I'm going to click that and then I'm going to search for Python and we should see python from Microsoft if you click on on that you can see python intellisense linting debugging and other things that are available now I've already installed this extension so I have uninstall and disable you will need to go ahead and click install that should show up here where I have uninstall and install this extension for visual studio code it should not take long at all after you do that you can go ahead and close out of this you can click the file Explorer icon over here just to show the file tree again for whatever folder that you currently have Visual Studio code open in I should mention that I created a folder you can see I have lesson one as the name of my folder and there are currently no files in it whatsoever so my visual studio code is empty my folder is empty over here now in Visual Studio code we're going to open the command palette and to do that I'm going to press Ctrl shift and the letter P if you're using a Mac when I say control you probably need to press command so either command shift in the letter P or Ctrl shift in the letter P that will open a command palette and you can see my Top Choice says python select interpreter that may not be your Top Choice so you can just start by typing the word Python and seeing all of the different commands that come up and you could type all of this out or you could scroll through and find the select interpreter and once you do that it's going to show the version of python that you currently have installed you can see I have python 3.11.2 64-bit and I'm just going to select that once I've made that selection I can then open a terminal window and there's a terminal menu here at the top when I click that you can go to new terminal or you can also just use the shortcut which is what I usually do a new terminal is Ctrl shift and the back tick or just control backtick to open a terminal that may not be new so if you already had it open say I could type something here like my name which won't really amount to anything if I were to try to run my name for example that wouldn't work but if I close it and then press Ctrl and back tick it opens up the same terminal not a new terminal so that is the difference control and back tick opens an existing terminal if one exists and control shift back tick opens a new terminal and you can have more than one terminal if you click this plus button here you can see now I've got two terminals open mine says bash because that is my default terminal however you might have other choices on Windows there's Powershell there's a command prompt I'm using git bash if you don't have that installed that's okay you can use a command prompt and now I have a command prompt terminal window open and you can see the difference over here one's name command and one's named bash so either would work and on Mac or Linux it could be different for you as well but now we need to verify our python installation so on Windows I'm going to type Pi just P Y dash three and then dash dash version now that's for Windows if I'm on Mac or Linux I need to type Python 3 then dash dash version and that would work on Mac or Linux and then you press enter so I'm going to go back to what I need to type for Windows just keep that in mind anytime you see me type Pi on the command line like I am now if you're on Mac or Linux you need to type python3 so it could be just a little different now I'm going to type dash dash version and press enter and it gives us the version of python that we currently have installed I have python 3.11.2 now we can drag this window for a little more room also so I'll drag this up to make this command prompt or terminal because I'm not really using a command prompt I'm in git bash But whichever terminal window you have open you can make bigger by dragging it like I just did now I'm just going to type Pi once again on Mac and Linux type python3 instead but now I'll just press enter with nothing after that and now you you can see we have something different here we can actually run python commands right here at this prompt you see the three arrows this is the python reple and that stands for read evaluate print Loop and we can just put in a command python for example can be a calculator so I can press two plus two press enter and it outputs 4. I can also do something with a string like my name which I had typed earlier but let's do this I'll say name equals Dave and now I'll press enter notice there's nothing output currently but if I type name it's going to Output my name we assigned the string Dave to a variable called name and so then when we typed name it output the string Dave now it's good to know that we can run commands at the prompt like this but this is not how we're usually going to provide commands to The Interpreter we are going to do that with files and essentially creating a file is a bunch of commands put into one file that we tell python to execute now python is not a low level language in a low-level language is more machine oriented instead Python's a high level language and it uses an interpreter and this allows us to write code which is easier for people to read so in other words python is more user friendly to read and to write so for example when I want to get out of this I'm just going to type quit and I need to put parentheses after and press enter and now we have quit our Rebel environment and we're just back to our normal prompt here now there are several ways to close this terminal window preview obviously you saw me click the x that works and then if I wanted to reopen it and still have this here I could do that with control and backtick however I could click the trash can and then that will get rid of this window and if I were to open it this stuff wouldn't be here any longer so I'm just going to click X in case I want to bring that back up so I mentioned creating a file and we can do that a couple of ways in Visual Studio code one would be to go over here to this file tree that we see on the left and click the plus button by the file icon that would create a new file and then we could name it I can also just press Ctrl n for a shortcut and that starts a new file which is what I'm going to do now and then I'm going to say something like greeting equals and I'll put hello world because that's something just traditional that you have to have any time you're learning a new programming language and after that then I'm going to say print and then I'm going to pass in that greeting variable that we created above on the previous line now notice this file is Untitled and it has a DOT here meaning we haven't saved this yet so I'm going to press Ctrl S I could go to the file menu and from there I could also choose save or save as I'm just going to do control s and it's still going to ask me what to name the file and I'm going to save it in my lesson one folder so I'm going to name this hello and then I want it to end with the dot py extension right now it says save as type plain text that is not what I want I want to find the python extensions here inside of the file types and make sure I'm saving as type python which you can see it can have different types I'm using the dot py so I'll click save now I have saved my python file type hello.py and you can see Visual Studio code now acknowledges this is a python file type and it is color-coded part of the code so the string has a different color and the command here for print has a different color the parentheses are also in a different color so it makes it a little easier to read the code and now that we've created this file we can run this command or commands whatever we would have in the file we can tell python to execute in three different ways one is to go to this play button that we see over here in the top right of Visual Studio code now there's a little carrot here that I'm going to click it gives us a drop down I'm going to choose run python file and when I do that it opens up this terminal window notice it's named python over here now it's not the one we had previously named bash so I just clicked the trash can to get rid of that but here is what it ran when we told it to run the file it put this command and this said exactly where the python executable is and then after that we have this other long string here that says exactly where the Hello dot Pi file is and then we get the output from that file that says hello world now when we were to if we were to run this file ourselves we would not have to type all of this although we could copy and paste this in we can use a shortcut or two for this one we already know that we can just call python in windows with py again Mac and Linux type python3 after that a space and since we're already in this lesson one directory that I have or folder you could call I said directory but it's the same thing if you've created a folder with a different name you would be in that folder so if you're already in that folder and you see your file over here I can just type in hello Dot py and now we're telling python to run that hello file that will accomplish the same thing that we saw executed above when we used the play button up above so now I'm going to press enter and we get the same output hello world also we could go to the file tree and right click I believe in Mac that would be a command click and then we scroll down here and we find run current or run python file in terminal so I'll select that and it runs it again just like when we did the play button so you see these extra commands so three different ways to run our python file so congratulations again on getting started with python you've created your first file you've got it all set up on your computer and we've got much more to learn ahead in the previous tutorial we set up our Python Programming environment in Visual Studio code and today we're going to learn the basics of the Python programming language let's start by opening a terminal in Visual Studio code you can do that in a couple of ways you can go to the menus at the top and if your terminal menu is not showing click the three dots and then choose terminal and then new terminal otherwise you can just use a shortcut which is control and backtick in Windows in Mac it's probably command and backtick but either way we now have a terminal window open and if you remember from the last lesson we can start the python reple by typing p y just for pi and this is in Windows if you're in mac and Linux you need to type Python 3 and then that will start the python Rebel so I'm just going to type pi and press enter and now I am at the python reple so let's start today by discussing variables and you saw a variable in the previous lesson when I took name and that is a variable people and then I assigned a value to name and I just assigned my name so when I press enter nothing happens but now the variable name holds the value Dave which is a string so if I type name and press enter it Returns the value which is the string Dave now variable names can be made up of letters just like name is or it could be made made up of numbers or a mixture of the two or even use the underscore character so I could say name zero zero zero one and set that equal to Dave and press enter and we have no problem I could also use underscore name and set that equal to Dave and we still have no problem however there are some things we cannot use in variable names other characters for example so if I said name exclamation mark set that equal to Dave and press enter python tells us that's a syntax error so we cannot use that and it highlights the problem characters we see right here also we could say name Dash first maybe I wanted to use that for a variable name but the hyphen is a problem and we see that issue as well and now of course it tells us the whole thing is a problem really so that won't work either it says maybe we meant to use double equals which is something we'll get to later when we cover operators but we can't use the hyphen in a variable name either so maybe we decide to put the numbers first and then name and we really can't start a variable name with numbers either so once again we have a syntax error this mentions leading zeros but it doesn't just have to be leading zeros I could just say one name and try to set that equal to Dave and we still have a syntax error so again we can use letters and numbers and even underscores now we cannot start a variable name with numbers though and we can't use any other characters either so we do have some limitations now one other thing to consider is there are some reserved keywords that python uses for other things and we cannot use those but no worries you don't have to memorize them python will let you know just like it did here with the syntax error if we're trying to use a reserved keyword so if I took the word if and tried to assign that to Dave we're going to have a problem as well because here it doesn't point it if it points at the assignment operator here the equal sign we cannot use the keyword if and the same for some other keywords like four that is also a reserved word so I'll type 4 equals let's set 4 equal to Dave and once again python has an issue with that because 4 is a reserved keyword as well okay let's look at Expressions versus statements now you've seen me type an expression before like two plus two that's an expression when I press enter it Returns the output of 4. likewise I could type in a string and let me just use the word expression and Surround that in quotes press enter and it Returns the value of the string which is also expression these are expressions in contrast to statements that perform operations on values so now let's use a statement and I'll just say my name equals Dave here we're assigning the value of Dave and it's a string value we're assigning that to the variable my name so that's a statement I'll press enter and now I can just type my name and it's going to return the value of Dave so we want to create a python file and put statements inside of that file so it executes as a program so let's close out of the terminal well first we need to exit our Rebel so let's type quit input the parentheses press enter now we have quit the rebel and we can just click X to close out of the terminal window I have created a python file called Welcome dot Pi now remember you can do that by clicking the new file icon over here on the top left or you could press Ctrl n to create a new file and then save that file as welcome dot ey welcome dot Pi so now inside this file we're going to use some statements so my first statement is going to be assigning a value to a variable and I'm going to call this variable line 0 1. I'll set it equal to a line that has 20 asterisks so one two three I believe that's 20. from there we're going to take a shortcut in Visual Studio code so I'm going to press shift alt and the down arrow and copy this down now we don't have a problem right now however we're reassigning this variable what I want to do is change this to a 2 and I want to change this to a 3 and actually I don't need these last two I was thinking I'm going to use five lines but I only need the first three lines now here in the middle I am going to remove all of the middle asterisks and then space this back over so it matches up with the edges now in the middle of this one I'm going to remove them but then I'm going to space over five times one two three four five and I'm going to type welcome if I get my thing fingers on the correct Keys then one two three four five and there I'm finished with the three assignments now let's go ahead and create some more statements that print these values but my first print is going to be an empty string so I want a blank line first so this is the print function here and it's going to just print this empty string but on the next line I can say print line whoops line 0 1. you can see Visual Studio code even wants to help me it knows what values we have already once again I'm going to press Ctrl alt and the down arrow and this time I actually do want five and so now I'm going to have line one and then I'm going to switch this to line two and I'm going to switch this to line three and here's something about programming we want to be efficient there's no reason to create the line four or five if they're going to be the same as line 2 and line one so now I just want line two printed again and then line one so what I'm going going to do is create a welcome message but it's actually going to have this header and footer because it starts with this and it ends with this so Ctrl s to save our file with those changes or you could go to the file menu and choose save but it's faster to learn the shortcuts like control s from there we can run this file do you remember how to do that from the first lesson there were three different ways what I'm going to do is go up to the play button here choose the little drop down and choose run python file and let's see what happens and it outputs our print statements and we get our welcome message here in the terminal so that worked out nicely let me drag this down a little bit because now we also want to discuss comments and comments would be notes we would leave for ourselves or for other programmers inside of our file so here I'm going to just put a comment afterwards and it starts with the hash mark or you might call it a hashtag as made popular nowadays so we've got our hashtag here and then I'm going to just say header slash footer because that's what I'm using that line for and here I'll put another comment and I'll just say reuse so anything that comes after this hashtag is grayed out and the hashtag itself is too and it doesn't impact the code at all they're just notes for us now here I could put a note before everything starts I could say starts with a blank line so I'm just leaving some comments inside of our code file here and these are reminders to me so when I look at the code maybe I know what it's going to do or another programmer that might look at the code in the future and this would help them understand what the code does I'm going to close the terminal window again just so we have a little more room as we look at our code and we need to talk about indentations in Python they have special meaning and if you're used to another programming language like JavaScript and others they ignore white space but python does not so I'm going to indent here several spaces and then type line04 set that equal to a line that has some more asterisks for example and this is just an example not anything that I really need but here we have a red squiggly in vs code it's already telling us that this is not going to work and if we Mouse over it we'll probably get a message yes it says unexpected ending you can also see our file name is red over here in the file tree that means there's a problem and even in the scroll bar to the right we have some red marks telling us that there are some problems in the file but no worries when I press Ctrl s to save we get some Auto formatting and visual studio code fixes that indentation for us so that's very nice so let's make sure that you have that set up it might be set up automatically after you already installed the python Visual Studio code extension like we did in the previous lesson you want to make sure you have that extension installed click extensions over here this is the icon and then search for Python and then you can check python from Microsoft click that and if you have it installed you should have the same messages I do that say uninstall and disable instead of being able to install the extension so this means you already have and it says this extension is enabled globally so we've confirmed that I have that extension so now let's go into the settings of Visual Studio code and confirm that you have the auto format on Save set as well so I'm going to press Ctrl and comma and this will open up the settings again command comma on Mac I believe so once you do that we need to search for these settings the first one is going to be format on on there we go save and when we bring that up we have editor format on save you want this checked and besides that the mode that I have here is when I save the file so make sure this says file as well now after that setting once you confirm that now we're going to search for Python and then type the greater than symbol and then after that we want formatting not just the word format and then a colon and then let's see what comes up after that we're still going to need to scroll down just a little bit I believe let's find this here provider that's the one I want to find you should have Auto Pep 8 here in this choice and this should have been installed with that python extension as well but this is the formatter that should be used by default and that's what I'm using for these tutorials so once you've checked those settings you should then be able to type your line 4 in your file well add some extra spaces you can see Visual Studio code doesn't like this and then press Ctrl or command s depending on your machine and then when you save the file it should fix that for you now I'm going to remove line four because we really don't need it at all but you can just play around with that in your vs code and see if you get Auto formatting as well now we've covered the basics of python today but there's much much more to explore in future lessons in the last lesson we defined a statement as an operation on a value now we can Define python operators as symbols used to perform operations on values and the variables that hold those values so let's look at some examples and we'll do that by opening a terminal window first so you can go to the terminal menu and from terminal menu you can choose new terminal or you can just press control in the back tick which will also open a terminal window from there we need to start our Python reple and I do that in Windows by typing pi and you might remember in mac and Linux I believe you type python three just like that I'm just going to type pi and press enter and now my python reple has started so the first operator that we have used already and that I'll introduce today is the assignment operator so you have seen me type this example before I'll just type name equals and I'll set the variable name equal to the string Dave after I do that it's now assigned that's the assignment operator and I can type name and I get the value back likewise we can assign other values so I'll take meaning as a variable name and assign the number 42 and if I type meaning I get the value 42 back so I think it's easy to see how assignment works and how the assignment operator which is just the equal sign Works in Python from there we'll move on to arithmetic operators now you have your standard edition say 2 and then plus two press enter we get four so we can use Python just like a calculator we can have 4 minus 2 and we get 2 back we can also do multiplication so 2 times 2 we get four and we can do division so let's do something here that's a little different let's say 24 divided by 5. now what would you expect to get back from this possibly 4 if it's rounded down or five if it's rounded up but maybe we'll get a decimal back let's see and yes we get 4.8 but there's also floor division so we could say 24 and then use two slashes and that's floor division which means it's going to round the answer down and now we get four or we could also use the round function and then we could say 24 divided by five and now it's five because it rounds up but what if we just want the remainder well then we use a different operator and that's the percent sign and then I have 24 5 and let's see what we get back we just get the remainder which is four also there's exponents so if we said 2 to the power of which is two asterisks three that would be two times two times two and yes we get eight so what if we said 2 to the power of 5 that's 32 and so you see how that works as well and now when we're working with variables we can combine the assignment operator and arithmetic operator so let's take meaning and set it equal to 42 and now I can say meaning and then I can say plus equals one and now what do you think the value of meaning is if I type in meaning and we get the value it's now 43 so it added 1 to that so that was a lot like saying 42 plus 1 but the variable mean mean holds the value of 42. likewise we could take meaning by type meaning correctly and say minus equals one and now meaning should be back to 42. we can do the same with the other operators also so I can say meaning and then times equals 10 and then if we check the value of meaning we get 420. so now let's look at meaning and let's say divides by and equals now what do you think will happen if we go ahead and divide this by 10. what will be the result well let's go ahead and look after we do that we need to check the value and it's 42.0 so that might be unexpected we have a decimal now when we divide but we could have used the floor Division and not received that response now this won't change meaning notice we're not using an assignment operator here we're just rounding meaning and we'll see what the response is well it's 42 but now if we check meaning it still has the decimal point so we could say meaning equals round meaning and now that would remove the decimal point so if we check it here it's now just 42. one other thing you can use the plus operator for and that is to concatenate two different strings so if I took my first name in a string Dave and I'll put a space after it and put another double quote then I can use the plus symbol and I can put my last name oops I accidentally hit return or enter too soon so let me try that again Dave space double quotes plus now double quote gray make sure I hit the double quote again and not the enter key now we get one string returned that is concatenated the two previous strings of my first name and my last name and now I want to look at comparison operators but before I do that let's get rid of our previous history here and we can do this in the terminal by going to the three dots and choosing clear terminal and then it just clears out the full terminal for us as well so now let's look at comparison operators and so if we want to check to see if one number is equal to another let's say the number 42 is it equal to 41 let's find out when we press enter and we get a false response so let's see if 42 is equal to 42. notice we're using the double equals so it's not the assignment operator here we're checking to say is this equal and when I press enter then we get true notice we're getting false and true on these responses that is called Boolean data and notice how the false and true are both capitalized at the very first letter of the word so now if we check to say 42 is not equal to 42 well that's false so if we said something like 43 is not equal to 42 we would get true back likewise we have greater than and less than operators so 10 is greater than 5 that is true 10 is less than 5 that is false we also have greater than and equal to operators so 10 is greater than or equal to 10 that is true 10 is less than or equal to 10. well that's also true because it's still equal to 10. and so now working with these comparison operators we've introduced Boolean data the true and the false so let me create some variables here I'll just set a variable named x equal to true then I'll set a variable y equal to false and I'll set a variable Z equal to true now we can use some Boolean operators with these variables so the first Boolean operator we'll look at is the word not it is a keyword and so X is true but if we say not X and we press enter we get the opposite false so if we said not y we get true again the opposite another Boolean operator is and and this would look at two conditions for example X and Y now let's look at what happens it's going to evaluate the first value and it only looks at the second value if the first value is true so what do you think we'll get as a response we get false because the first one is true so it looked at the second one likewise if we said Y and X now the first value is false and it stops evaluating right there so and needs both values to a essentially be true that's what we're checking for so if either one is false that's where it stops now just the opposite is the Boolean operator or so let's say X or Y and now it's only going to look at the second if the first is false but X is true so the response we get is true but if we say y or X Y is false so the response we get is true again because it looks at the second value because the first was false so you can kind of remember it that way and and or are the Opposites they would kind of give opposite results but or is just checking to see if one or the other is essentially true and and if we use that in a conditional statement which you'll see an example of here in just a minute and would actually be us looking for both values to be true is what we would be hoping for if x is true and Y is true then do something else so for example we could say x and z now they're both true and we get true back because the first was true so it returned the value of Z actually because then the second was true and then we could also have z and y and what would happen here it's going to be false again because Z was true so it went ahead and looked at the second value now let's check again with the ores y or Z what are we going to get here we get true because y was false now if we said Z or Y we get true again but it stopped when Z was true it never evaluated y now I understand that can be a little bit confusing so it's good to play around with these and check those Boolean operator comparisons yourself until you get the hang of how they work so for now let's quit the rebel we'll type quit with parentheses and after that let's close the terminal window and we're going to create a new file here in Visual Studio code so I'm going to press Ctrl and n and that brings up a new file remember you could also use the new file icon over here and now I'm just going to start typing and then we'll save the file afterwards so I'm going to take the variable meaning and assign it the value of 42. now I can do control s to save the file or I can go to the file menu and choose save as which would allow me to name the file as well I'll just do control s now I'm going to name this meaning dot py for pi or for Python and I want to make sure that I have the python file type here as the save as type as well so when I choose save now it is a python file now in our small meaning program here I also want it to start with an empty line so I'm going to print an empty string to start out with now we were using comparison operators and you often see those in logical if statements so let's create our first if statement I'll say if meaning is greater than 10 and now I have a colon so now I indent and notice when I pressed enter Visual Studio code already knew I needed to be indented and the indentations do mean something in Python and so now I'm going to print I'll just say right on so if meaning is greater than 10 this would be the output after this line now I do not want an indentation and visual studio code doesn't really know if I want to do something else here or not after meaning would be greater than 10. so here I need to backspace just to go back to where I do not want to be indented now I'll type the word else so this is essentially if meaning is not greater than 10 we're going to do something else and I'm going to print here and I'll say not today so we have our first if else statement and it's going to check the value of meaning we're using a comparison operator here so once we save that now if you remember how to run the code we can just click the play button here in the past I've used the drop down and chose run python file which also works but we can do it a little simpler than that just by clicking this button so let's do that and it runs the code oh it did not find an alias maybe we need to choose python run python file first and after we do that one time I think this play button is going to work yes it works the next time so if you need to do that if you get that error that you saw I had go ahead and choose run python file the first time after that the play button works just fine and we get right on every time and that's because I don't need this bash window here either we're just using the python one but but this is because meaning is 42 which is greater than 10. so let's change the value of meaning to eight and I'll save the file again and now I'll click the play button run and it says not today I'll drag this back up so we can see just a little bit more run it again and you can see the command that is issued when I click the play button now if you remember this is a quick review how we can run this ourselves from the terminal window we can just type pi to run our python code and then type the name of the file dot Pi because we're in this I'm in this lesson zero three directory and that's the name of this up here whatever folder you have would be the name there and then we can see the file so just pi and then meaning dot pi and we'll get the same result but you see the long version here when you click the play button here and so we get not today because meaning is only equal to the number great I'm going to close the terminal window for just a little bit more room and we need to look at one more operator today and that's the ternary operator if else statements are nice but look this took four lines we could do all of this on one line if we wanted to so let's talk about something else we can do we learned about comments in the last lesson I'm going to highlight all of this code in Visual Studio code and I do that by clicking and dragging once I do that I'm going to press Ctrl and Slash and it just commented out all those lines of code that I have highlighted so they're still there and I want to leave these in here to give you the example of the if else statement but now let's use the ternary operator to accomplish the same thing in one line of code and so I'll put another comment here and I'll spell this out this is a ternary operator in Python we accomplished this a little bit different than if you're used to JavaScript or some other language so the first thing I'm going to type is what I want to be the output if the statement is true so I'm going to type print right on and then after that I'm going to actually put the conditional statement what we're checking for so I'll say if meaning is greater than 10. and then after that I need the word else still and then I can put what the output will be if it is false and I'll print not today that is our ternary statement and it uses the ternary operator it looks a little different especially than I often work in JavaScript for example it looks a little different than the way I would do this in JavaScript but let's go ahead and run the code again just by clicking the play button and we get not today it works just fine let's put the number back to 42. and let's run it again and now we get right on our ternary statement is working as expected so we've covered the most common python operators today but some other python operators will also be introduced in the future and those include the identity operator the membership operator and even bitwise operators we are ready for Lesson Four and I have Visual Studio code open you can see I have a folder to the left that is named Lesson Four and that's what you'll find in the course resources now let's create a new file in this folder I'll click the little plus icon up here for a new file this is a good time to talk about naming conventions for files with python we use all lower case so I'm going to type data and then if we need a space we do not use dashes or hyphens if you will we use underscores and then we continue to type in lowercase so I'm naming the file data underscore types dot pi and then press enter and there is the file that we'll work with now that we have the file you'll see the play button up here that we'll use to run our code and the associated menu that can show with that so let's begin by typing inside the file and I'm going to just put a comment here that says string data type it's the first data type that we're going to cover and I'm going to talk about the literal assignment of value so I'll type literal assignment here in another comment and I'm going to type a variable named first and I'm going to assign the string Dave this is literal assignment so I literally assigned this value Dave that is a string value to the variable first now I'm also going to create a variable named last and I'll put my last name in there these are both string values now we can check this in Python if we use a print statement and then we'll use the type function and I'll pass in first so that is the variable first that holds the string value Dave and we'll see that when we check it so I'm going to press Ctrl s to save the file you could also do that from the file menu and then find save here you can see it's control s after that I'll come up here to the little menu by our play button and choose run python file now it went ahead and opened the terminal window for me when I did that and you can see the out output says class string this Str stands for string okay after that I can close the terminal and it will reopen it when we run the file again there's another way that we can check for this value so I'll once again type print then I'm going to say type pass in first let's see if it is equal to and that is 2 equal and then Str for a string and besides that let's do one other one that we can also check now I'm going to do shift alt and the down arrow that will just copy this down and then I'm going to change what's inside of the print there is an is instance function that we can use and with this I'll pass in the variable first and then we're going to say it is an instance of what and in this case we're checking for string so now we'll see the output of all three of these print statements once again Ctrl s to save and then I'll just click the play button to run the code and I'll need to pull this up maybe to see all of the output and I'll scroll just a little bit there we go so we see string that we previously had here and then true true so the output of the following two statements is type first equal to string and the output is true and then is the first variable an instance of string with this is instance function and that is also true okay now that we have looked at literal assignment let's look at another way we can assign a value and that's with a Constructor function so I'll make a comment for that now I'm going to Define pizza and this variable is going to hold a string that says pepperoni but I'm going to use the string Constructor function so it's Str and then parentheses and inside of this I'm going to pass in the string pepperoni now after this I'll copy all three of these and I will paste below so I copied with Ctrl C after I highlighted this and I paste with control V the letter V is in Victoria okay then I need to change this word first to Pizza so I highlight the first one and then Ctrl D to select the second and the third instance of first now I can just start typing pizza and it will change all three so now we're going to check the output for pizza as well and I can highlight these also and press Ctrl and the Slash and it will comment these out so we only see the output for our pizza now after I save once again with Ctrl s now clicking the play button and we should get some output that we once again see in the terminal and I'm going to just leave that terminal as a little bit larger so we can always see that there we go so it is class string and true and true once again so now we checked pizza here and it said class string and then this said true where we checked the type if it was equal to string and then this said true where we checked if pizza was an instance of string so now we know two different ways to assign string data to variables and we can do this with other data as well so we have literal assignment and Constructor functions that can assign data now I'm going to comment this out as well again highlighting this and pressing Ctrl and the slash will comment these out now when you find these in the course resources you can do the same thing to uncomment so you could highlight the lines you want to uncomment and press control and the Slash and they'll once again be uncommented so you can toggle between the two by doing that now let's discuss concatenation and that means adding two strings together to form a larger string and that's what we will do so we will type concatenation here and after this let me Define full name as a variable and I'll use my values from above so I'm going to set full name equal to first and then I can use the plus operator and then I'm going to put an empty string here with one empty space and then plus again and type last and this concatenated my first name with the space in between to my last name so now we could print full name there we go and save once again press the play button you can see my full name here inside of the terminal now we can also add something to the end of full name if we want to so I will say full name and now I can use plus equals and this is going to take the value of full name and add to it and I'll just put an exclamation mark here at the end and one once again print full name and if I run the code with the play button we should see my name now with an exclamation mark here in the terminal you can also take a number and change it to a string and this is called casting so here I'll say casting a number to a string and let me assign a variable name decade with the value and I'll use the string Constructor here and I'm going to pass in 1980 so I had a number 1980 the value and I am now casting it to a string with the string Constructor after this we'll go ahead and check this value so I'll say print and type and decade and then after that let's go ahead and just print this out to see what it looks like after it has been casted as well and now let's check those values and you can see that yes that type is a string and there's the value but it's a string here it is not a number and that is 1980. and now this is important if I wanted to concatenate that value inside of a sentence I would need to cast that number to a string as we previously have here so now let me create a statement so this is a variable name statement and I'll just say I like rock music from the now I'm going to concatenate that value so the plus operator and then I'll just pass in that variable decade another plus operator and then the letter S and a period at the end so now let's print our statement and save with control s and run our code and we can see we have the statement I like rock music from the 1980s but what if we wanted a statement with multiple lines we can do that as well so I'll scroll up for some more room and underneath this I will just leave another comment that says multiple lines and now we'll take a multi-line I'll just call this multi-line for the variable and we want to start with three quotation marks either double or single will work so I'll put three quotation marks and notice vs code wants to help me so it already automatically added the closing three after this I'm going to press return and leave a few lines between the opening and closing quotation marks again three at the beginning and three at the end here I'll say hey how are you with a question mark now let's add some spaces with the space bar press return again and again and then another statement I was just checking in and then another space or two or three and then return once again and now I'll tab over five or six times and say all good question mark and then notice we have a blank line after as well let's save that with control s and now after we do that let's look at our statement in the output when we print multi-line save once again and run now we have this big statement that is on multiple lines and of course it has white space before and after some of the things as well we'll come back to that white space in just a little bit now let's talk about escaping special characters also because sometimes we have special characters inside of our code we just started this multi-line statement with single quotes and what if we were to use single quotes around a sentence we created so here I'll leave a comment escaping special characters and now I'm going to create a sentence variable and I'm going to set this equal to a value that is inside of single quotes there we go single quotation marks and the word I'm so this would have a single quote in the word and notice vs code doesn't like this we need to escape this single quote if we want it to be in our statement because right now BS code just thinks the value ends right here with the letter i it would not include the letter M so let's put a slash here and it's a backward slash and that escapes that single quote so now it knows that it should be part of this phrase so now we can use I'm in our sentence and I'll say back at work exclamation mark and then I want a tab after back at work instead of a space we can indicate that with another backward slash in a lowercase T notice how vs code leaves this as red so that's a special character so now we have a tab in our sentence and I'll just put the word hey with an exclamation mark again and now another backward slash and a lowercase n that indicates a new line that is the new line character so that will make everything else that follows it be on another line let's put two of those just so we can see what really happens there then I'm going to use use the word where's so it once again has a single quote that I need to escape then the letter s then this then I want at slash located and I want to put a slash between at and located but as we know already we're using slashes here for special characters so we also need to be able to escape that slash and so we do that by adding a second slash but only one will appear in our sentence and then I'll put a question mark at the end and let's go ahead and print the sentence out and see what we get Ctrl s to save and we run our code and here we have our full sentence I'm back at work Hey where's this at located once again it put in the tab it put in the line breaks and we were able to use the single quotes even though we had wrapped our full sentence inside of single quotes I'm going to scroll up for some more room and then I'm going to leave another comment because we're going to begin working with string Methods now methods are functions that are called on the string class and that's not too important right now but we do want to see what these methods will do for us so let's start out just by looking at the value that we once again have in the variable first but after that I'm going to put another print line and say first dot lower and we'll see what it does to the value that is in the first variable and we'll also note that it won't actually change the value in the first variable it will just return another value and then instead of typing that all again I'm going to use shift alt and the down arrow and do that twice and I'm going to change lower in this second one to Upper see what happens there and then I'm just going to remove lower from this last one so we can once again see the value of first and note that it did not change Ctrl s to save and click the play button and now here's our value of first which is my first name Dave and then after we called the lower method that we see here on line 49 we then had the lowercase value of my name and then first Dot Upper and we had the all uppercase value of my name then we once again just checked the value that was in the first variable and it is still left untouched as it was let's look at some more string Methods and instead of using my first name here in the first variable let's use that multi-line variable that we created so we'll now say print and then inside of this print I'm going to use multi-line and I'm going to use the title method at the end of this now this method will turn everything to proper case and capitalize using the first letter of every word in that multi-line phrase but I'm also going to print another version of multi-line so we should see it twice and in this version I'm going to use the replace method I'm going to replace the word good with the word okay and we should see the difference there and then finally I'm just going to print multi-line so we can see that the original value did not change so I will save that click play and of course we can't see all of that at once I'm going to make this terminal window take up the full screen for a moment we'll see three versions of this so here was the version that has the proper case where we called the title method so it says hey how are you I was just checking in all good the second version used the replace method and we changed good to OK and then finally we printed the original version that you can see did not use proper case with the title method and still contains the word good I'll go ahead and close out this terminal window for a moment and we talked about all of that white space that is in our multi-line variable so let's work with that now I'm going to call Print once again and I'm going to call the length function which is just l e in and I'm going to pass multi-line into this so we can see what the original length of our multi-line string is so it will count every character after that we're going to change the multi-line variable and I'm going to use the plus equals to add to the end of it let's just add a lot of extra white space after that let's go ahead and once again change the multi-line variable and I'm going to add some space to the beginning of it and we'll do that in a different way instead of the plus equals I'll use the equal symbol I'll add some space and then at the end I'll concatenate the value that we have in multi-line currently and then after that let's once again check the length so we'll check the length function with Len and then we'll pass in multi-line so we're checking the original length we're adding to the end and the beginning and then we're checking that length again and if you want to you could even check in between where you'd get a value that only has it added to the end and not at the beginning so now let's run this and see the values that we get so we start out with 126 and after we add all of that extra white space at the beginning and at the end of the variable it's 184 characters now of course this white space is undesirable but I'm adding it as an example so now let's look at some string Methods that will remove that white space if you had some values that you needed to remove white space from so I'll say print once again and now we'll say multi-line dot strip and that should remove the white space if we wanted to remove it but this will of course print out the output it's not checking the length if we don't add length and we won't really be able to see that because you can't see white space so let's go ahead and just check the length here Len and we need to wrap that in parentheses and now I'm going to do something else I'll do shift alt in the down arrow twice there are two other methods we can check so let's check if we only remove the white space from the left side and that is with L strip let's also check if we only remove the white space from the right side and that is our strip so if we check all three of those then we'll see different values so let's run this code with the play button and we can see the last three here if we removed well all of the white space it took it down to 123 and remember our original it had 126 up here before we added the white space so this actually removes some extra unneeded characters as well and then when we only remove the white space from the left side we still had 165 characters when we only removed it from the right side then we had 142 and I think I'm saying that in the correct order yes we removed the right side last and there are many more string Methods and I'm going to leave a link in the course resources where you could go to the documentation and find all of the available string Methods that you can experiment with right now let's just use a few more string Methods to build something just so we can apply this in a small way for now let's build a menu I'm going to set a title variable equal to menu notice it's all lowercase value and we can call string Methods directly on the value itself it doesn't have to be called on a variable name as I have been showing you so here I'm going to say menu Dot Upper and call a string method directly there and that will be stored in the title variable after that I'm going to print the title and I'm going to call the center method I'll pass in 20 characters and I'm going to pass in a value that is an equal sign let's see what this does if we just return this much and I'm also going to leave a empty line here so we do not actually see everything that we've had above pressed right up against our menu so Ctrl s to save and now I'll run the code with the play button and you can see what we've got so we call the center method and it centered our word menu that was set to all uppercase and it used that character I passed into the center method to fill out the rest of the space so that's a very interesting method to call now let's call another one that is equally interesting so after this I'll say print and I'm going to use the string coffee and after this I'm going to use l just which means left justify and I'm going to give this 16 characters I'm going to have it fill out the remaining space after coffee with periods and then I'm going to concatenate inside of our print statement and I'm going to say one dollar but I want it to be a string so the dollar sign and the number one and I'm going to call the right justify method on it I'm going to say four characters there is nothing that I want to fill out the rest of the space with so I'm just going to pass in one argument here or one value I should say to this right justify method so after I do that and save let's see what we get in our terminal once again when we click run now our menu has coffee and you can see it filled out the space that we gave it for 16 characters and then we have our dollar that is right Justified over here let's go ahead and complete our menu I'm going to scroll up and once again as I've explained I'm going to use shift alt and the down arrow to copy this down twice and now let's just change our values so I'll double click copy and change it to muffin and in the last line I'll change it to cheesecake and then here let's just change our values to two dollars and let's go with four dollars Ctrl s to save and we run our code and we have a nice little Coffee House menu let's close the terminal and let's look at just a few more things with strings and one thing to discuss is string index values so I'm going to say string index values here in a comment and just to keep our menu separate I'll once again print empty string here okay after the string index values comment let's look at string index values I'll come back to that first variable that we have and if we just want the value that is at index one do you think that will be the D in my name it would seem to be if we say we want the number one value right the very first value well that might not be what that indicates let's go ahead and press play you can see it actually Returns the second letter and that's because indexes start at zero so if we wanted the first letter we would pass in a 0 right here let's copy this down with shift alt and the down arrow and let's see what minus 1 gives us so if we save now and run our code we have the E which is the last letter in my first name so anytime we want the last value in the string we can reference the minus one index and that could be very useful if you didn't know how many letters were in the string you were working with but you needed to get that last value you can also use a range of values so here instead of just one or minus 1 you can start with the index say at the first position well it's actually the second position but at the one position and then we can say we want to end at the last position but this might not deliver what you think either when you provide a range let's go ahead and run this you see we just get the AV so the value you give at the end of the range will not be part of the output so you need to consider that when you create the range and if you want to go all the way to the end you just provide a range without providing the last value at all like this and now we should get the a through the end of my first name run this yes we get Ave when we don't provide that final value and now when we've previously checked what data type we had some of those checks were returning true and that is Boolean data let's look at a couple of methods that also return Boolean data and I'll just say some methods return Boolean data and if you're wondering what Boolean means it just means we're working with true or false data so if we print here and say first starts with now I could say does the value in the first variable does it start with the string D well that should be true because my name starts with a capital D let's copy this down so we can check two things at once now we can say does first ends with and now we'll check the letter Z so let's see what result we get oh it does not have two s's and notice Visual Studio code will help you with that how it this in my theme at least it turned purple here and if you're not using the same theme it may turn a different color but overall if I mistype something then it doesn't look right it doesn't have that color that starts with does but if I remove the S there you can see it identifies the method likewise and I'll just remove this for a second when we're working here in Visual Studio code you can just type the period and suddenly a list of all of these different methods can show up including the one I want which is ends with and you can search for them that way as well so now I'll just put in the letter Z again save and we'll run the code and of course we get true that yes first starts with the letter D at Capital D but false it does not end with the letter Z so now since we've brought up Boolean data let's quickly discuss that and I'll just leave another comment here that says Boolean data type and now after this I'm going to set my value equal to true now notice the true has a capital T if I remove that and just put true Visual Studio code tells us something is wrong here it needs to be proper case with a capital T or faults will not work either it needs to be capital F for false so either way you do it just needs to be proper case whether you choose true or false now after this I'll set another variable just the letter X I'll set it equal to Bool and I'll pass in false now this is the Constructor function once again so you can set this data type in either way and once again we can print say type and check the type of X and we could also say print and say is instance that we see right there and then we could pass in my value say is it a boole value we should get true for both of those let's go ahead and run the code and well we didn't get true it just said what type it was actually we didn't check that against a value like rule so yes we get the output here what it is then yes true for the second one but just important to remember that Boolean means you are working with true or false data let's move on to the numeric data types and there is definitely more than one so we'll start here and I'll just say numeric data types and the first type we'll work with is integer and we have seen this in previous lessons I'm going to set price equal to 100 then I'll set best price and I'm going to set this equal to the Constructor function and pass in 80. so you can set an integer in either way and just like we did in the past as a matter of fact I could just copy these lines Ctrl C and then down here Ctrl V to paste I could change X to price and we should see that it Returns the type integer and then here I could change this to best price and we'll compare it not to Bool but to an integer type and we'll see what we get for the output and yes it is a type integer and yes it's true that it is an instance of integer after that let's do some more with numbers and we'll look at the float type float types have decimals so a grade point average GPA set that equal to 3.28 that would be a float type and that is a literal assignment just like we did with price up here but we could also use a Constructor but it almost seems pointless because you still type the flow so I'll just say y equals float 1.14 and of course this is a float data as well we just had to type a little bit more so here we could say print we'll check the type GPA and it should return float and of course we could do is instance as well if we wanted to but let's see what we get yes it is the type float now there is one more numeric type to quickly mention it is not a type we will use in these basic lessons but I should bring it up it's the complex type and it's often used in electrical engineering it uses a j-notation so here we'd say comp value equals five plus three J I know that looks a little strange especially if you're not into engineering we can print type and we'll check the type for our comp value but now a complex value has a couple of property values we can check so let's go ahead and do that just so you see how we can say comp value dot real we can also say comp underscore value dot image which stands for Imaginary this is based on a real number system and it has a real number value and an imaginary number value once again if you're not into engineering it may not make a whole lot of sense but python has so many applications it's pretty awesome that this is built in so let's go ahead and run this see what we get back yes it's a complex type and you can see when we return those individual property values they are float values but they are part of the complex data type okay I'm not going to go over all the different mathematical operations that you can do we have previously covered several of those in the past lessons so no need to rehash that we went over those especially with operators in the last lesson but there are some built-in functions for numbers so let me just highlight those with a comment this way built in functions for numbers and let's print one of those out let's print the absolute value of the GPA that we previously created and remember that was a float type I think we said 3.28 so let's see what the absolute value of that GPA value would be it is 3.28 so no change there but once again this is checking the absolute value now let's see if we did something else with that that we could check we could say print and we could say round pass in the GPA there and then let's go ahead and do one other let's print round and say GPA and we can specify the decimal so the difference here would be this would round to the nearest integer this would round to the nearest decimal place that we specify so we have two decimal points here with our absolute value and you know what I should check this as well by saying print and since that didn't change before we could say GPA multiplied by minus one so you would expect to have a negative 3.28 but the absolute value will probably not be negative so now we can check all of this let's run and yes we got 3.28 twice without the negative although that would have been expected now the round rounded down to the nearest integer which was 3 but then when we specified the decimal point it rounded up from 3.28 to 3.3 so those are just a couple of built-in functions that you can use with numbers without importing a module but there are some modules that provide many good mathematic helpers and one of those is simply the math module now if I type import math right here and when I save the file it's going to move this to the top of the file which is nice and that's because I have that python extension installed that we'd previously talked about Visual Studio code just wants to help us format this what you should typically do is type your Imports if you're bringing in a module which we'll get into more further in this series but you would type your Imports at the top of the file I'm going to type it here to just give the example of how it will be moved to the top now after that I want to use this math module just to get the value of pi so I'm going to say math dot pi and once again we can use dot notation to check all of the different things available in this module Force I just want pi right there okay when I control s to save notice that import statement was moved it should be at the top and it is so vs code moved it right up here to the top above our first actual code if I was typing this at the top where I would normally put it is at the absolute top of the file okay after that let's scroll back down to where we were and we should just run our code once we're back here to check the value of pi so we'll do that and there is pi from the math module let's do a few more things with the math module because we've imported it so let's use it I'll shift alt and the down arrow three more times and let's go ahead and use the square root function that we can use let's pass in like 64 and see what the square root of that is let's also use the seal function and here let's pass in our GPA and see what seal does and then let's use I want to go ahead and highlight that let's use floor and pass in GPA as well so we're going to see Pi once again then we'll see the square root of 64 then the ceiling of our GPA value and the floor of our GPA value so control s to save run the code so after Pi then we went ahead and found out the square root of 64 is 8 and that is a float value that was returned but then when we checked the ceiling value of our GPA which was 3.28 it's now 4 so that rounded up to the nearest integer likewise math floor rounded down to the nearest integer and one more note earlier we cast a number to a string but we could also let's say here casting a string to a number we could also cast a string to a number so for example if I had zip code which is my variable and inside of it I had this ZIP code which is a string I could check that value or turn that string into a numeric value using the integer Constructor function pass in zip code then I'll check the type of the zip value so now that I have that control s and run the code and yes it is an integer after we have cast that string to an integer with the Constructor now a quick note you can and I'll scroll just for some more room again you can have an error if you attempt to cast incorrect data so for example if I said ZIP underscore value equals and I said integer and then I passed in New York which I believe this is a zip code for New York but we pass in the actual words New York to our integer Constructor python isn't going to like this so let's take a quick look at the error you can see it says invalid literal and it doesn't like what we did it really highlights it there so let's close out of that I'll comment this out but I'm going to leave it in the code for you in the course resources just so you can see this reference that this will be an error I've got vs code open to a new folder let's create a new file in this folder and let's name this file RPS dot Pi stands for rock paper scissors which is the game we will build today as we learn about user input and control flow so to accept user input from the command line we first need to assign that input to a variable that we're going to use so we'll just call this value and I'll set this equal to input and then we can put a message to the user and that's exactly what the user will see so instead of typing message to the user let's say something like please enter a value and then the user it will wait for the user I should say to enter a value and then after they do the code will proceed to run so after we do this let's go ahead and just do something simple like print value so it will print back to the console of course what the user has entered so let's save this much and now with that saved I also want to change something from the previous tutorial when I open the terminal with control em backtick we can see it down here at the bottom let's move it over to the right and we can do that by going to the view menu and going to appearance and then we can go to panel position and then choose right and now it has moved the terminal here to the right I'm also going to hide the file tree as we don't really need to see it with just one file and I can do that by pressing the control button and the letter b as in boy and now we've hidden that so we have some room to code here and we'll still be able to work with the input over here so we've saved our file RPS dot Pi we're going to go ahead and run that by choosing run python file and then it says please enter a value so I'll just enter my name Dave and then it printed to the console Dave so very simple but that's what we get and of course we could also put a colon here to make it look a little bit better and how about a new line character as we learned how to escape those characters that are special and the slash in is a new line character so if we save now let's just run that again now we have please enter a value with a colon and we're ready to enter that on the next line instead of immediately after it as we did up here so now I could just say something like hey and then of course it printed that same value right after I entered it on the line above so now let's start making our game and to do that we'll just start over I'll delete what we have there and I'm going to start with an empty line which will just help separate a new game from an old one at the command line so we've printed an empty string essentially there for a blank line after that let's call this player choice because the player gets to choose rock paper or scissors we'll set this to an input and then then inside of the input I could say enter let's give three dots and then let's give the new line character and after we start a new line we could say 1 4 Rock and then we could have a comma then let's put another new line let's say 2 or paper comma and then another well let's say or first and then a little space we'll say then another new line and then 3 or scissors and then we'll put a colon and let's put two new lines now notice how this just extended and kept on the same line here so we have to scroll let's go ahead and press alt Z to wrap this down to lines it doesn't mean that I pressed return it just puts it on a second line as you can see line two now takes up two lines in the editor when I pressed alt Z so that's what we're going to display to the user when we ask them to enter their choice and we want them to enter one two or three so now we can start applying control flow to our program and control flow is how the code flows it's how the user kind of goes through our code in a way so it's kind of like a waterfall if you picture it like that and it's performed step by step in a Serial Direction Just top down for now and you could also call that procedural so we're doing one procedure at a time now you have already been introduced to some if statements some logical operators and we can apply those so we can say if the user enters this then do this and then else if the user enters something else do something else so if we look at a simple simple example of that we can say if 1 is greater than 2 which doesn't even apply to what the user is entering this is just a very simple example remember in Python the indents means something so when I press return BS code already knows to apply that indent here and if it's not doing that for you that means it doesn't recognize that you have a python file and you need to install the python extension that I explain way back in lesson one in this series but here this just says if one is greater than 2 and of course it's not then we would say print do something so this is just an example of an if statement this doesn't apply to our game but this is a code block so it executes this code block if one is greater than two and of course that would never be true so let's apply something that makes a little bit more sense to our game here and so we have our player choice so we could say if player choice is less than one and then we can put in the pipe symbol which means or then we'll say player choice is greater than three that means they have given a number but it's not the number that we want not in the range we want at least one through three so now we have something we could act upon and we want to tell the user they need to enter one two or three so we could print this statement like print to say You must enter one two or three but the problem we have with the print statement is the program is still going to execute and continue after this so really we need to learn how to exit the program here if you remember from the previous tutorial we imported the math module and there are things we can Import in Python that will help us we need to do that at this time because we need to use the system X so I'm going to import at the top of the file and I'll just type import sys and then I'm going to give an extra blank line there just for some separation and now so instead of this print we can exit and still provide a message to the user but I need to use sys dot exit and that will exit the program but we'll also output this message to the user okay we have another problem we haven't addressed here yet and this is that all user input is a string so when the user inputs that it will be a string we really can't use a string here and that would cause an error so let's go ahead and cast this to an integer so we can use our logical operators to check if it's less than one or greater than 3. so we'll call this player instead of player choice and we'll cast player choice to an integer as we previously learned about data types so now we just need to replace player choice below I'll highlight one player choice press Ctrl D to highlight the second one and then just Ctrl V to go ahead and pass that in and now we can check player to see if it's less than one or greater than 3 because player is an integer and not a string now as we also learned in the last lesson a user could enter something unexpected like a word like New York or whatever like that and then we could have an error here too but we'll learn how to handle those in the future for now let's assume the user has good intentions can read the instructions to say enter one two or three and will at least enter a number if not one of the correct numbers now after that selection we're going to have another control flow statement that is larger to choose who wins the game but before we can choose we need something to compare to so the computer will call the computer python needs to go ahead and make its own choice too and we want that choice to be random fairly unpredictable and we can do that by importing a random module so let's do that we'll say import random at the top and after that we will come down below and we will go ahead and assign the computer choice so let's call this computer Choice we'll set this equal to random dot Choice I'm going to pass in a string that has all three selections one two three so computer choice will also be a string but it's going to randomly choose one of the characters from this string using random dot choice so after that we'll cast that to an integer as well and say computer equals int and we'll pass in our computer Choice variable now let's just enter a few print statements to at least get what we have so far before we go any further with the game so let's print another blank line and we can do that with an empty string and I'm going to scroll just so we don't go off the screen there and say print the next line and I'll say you chose and then let's put in our plus symbol to concatenate the player choice remember that is the string above so we can just use player choice there we don't need this to be an integer we actually need it to be a string when we use it in string output at after that I'm going to use shift alt in the down arrow in vs code to copy that line down but now I'm going to change U to Python and then we'll say python chose and here we'll put the computer choice and now we've stated what the computer chose as well as what we chose or the user and then we'll just once again print another blank line just so we get a little room so let's save all of that and now over here in the terminal let's type clear I'm using the python terminal here we see so I'll type clear and that should clear that out so now we have some room again I'll go ahead and click the play button and it says enter one for rock two for paper or three for scissors let's enter two press enter and it says you chose to and python chose three so it's working as expected right now but it's not telling us who won so now we need a larger control flow statement to determine who wins so let's just start by building a simple one and we can change the logic as we go to make it make more sense and apply to the game but just to look at how a larger if statement could work we could say if the player and then we'll say double equal sign here equals one so if the player choice is one then we could print you win for the user now of course that doesn't apply to the logic of the game this is just an example but what if it's not one at this time so then we could say else and here we could just say print and then we would say python wins but of course this won't work for our entire game but at least it shows how an if else works we can also add more to this statement so let's go ahead and do that now and apply the full game logic and so if player chooses one that would be Rock then we would say also and the computer choice equals three so we chose rock as a player and the computer chose scissors so rock beats scissors and then actually the user would win so let's go ahead and copy this down I'll highlight both lines I'm going to press shift alt and the down arrow now it gives us another line but we can't have two if statements back to back we need to say else if here and in Python we do that with L if so e l i f so now we can say if player chooses 2 and then the computer chooses one that means the player chooses paper and the computer chooses Rock once again the player would win so you win is the appropriate output finally let's highlight this one more time and do shift alt and the down arrow so we can have multiple else ifs this L if statement we can only have one else we can only have one if in between between we can put as many l ifs as we need and here I'm going to say if the player chooses 3 and the computer chooses two so now the player would choose scissors and the computer would choose paper once again the player would win but there's other cases of course there is the choice that any other choice there would be or python wins but what if they both choose the same thing so we have one more L if to put and let's go ahead and instead of copying that down I'll just type it here L if and now this would be if the player value is equal to the computer value then we're going to have print Thai game now we've covered each option so we've covered the three options that would let the player win and we've covered the tie and anything remaining anything else allows python to win let's go ahead and save our python file one more time and we'll press play to run our code so it says enter one for rock two for paper three for scissors I'm going to enter two once again and it says you chose two python chose three python wins so python shows scissors and I chose paper let's run it again and see if we can win this time I'll choose one for rock and it says python also chose one we have a tie game you could continue to test this to ensure your code is working as expected let's do a couple of more things that could make our game just a little more appealing even though it's a simple game at the command line one is to use some emojis in here in our print statements now I'm on Windows and I can press the Windows key and the period here in vs code and I get an emoji menu and I want to use celebrate I believe is the name of it so I'm just going to type the word celebrate and as I see it starts to narrow down here to the Emojis and I just want the little celebration Emoji so that is the you win and I'm going to copy that in the space and paste it into each of the you win statements now for a tie game we would want something different so let's go ahead again I'm going to press Windows key plus the period and here I want like a wow face yes wow Thai game so we have a space there and now python wins we need to give python a snake of course so once again Windows key period I'm going to type snake and narrow it down to python give a space we save the file let's run it one more time and see what we get and I'll choose one again for rock and we tied and we have the wow Emoji let's do it again and try to see if somebody can win one here three for scissors oh python chose one rock and rock beat scissors so python wins so do you notice what I'm doing at the end of the game I'm translating here I said you chose three python chose one so I had to translate scissors and rock for the numbers what if we could get it to say you chose scissors and python chose Rock so we could improve our game just a little more to improve this I'm going to introduce you to python enums so I'm scrolling back to the top and we need to import enums but it looks just a little different because we don't want the entire module we just want enums so we're going to say from enum which is all lowercase import enum starting with a capital there so notice the difference and now I'm going to use the class syntax because that's what we would use with enums but they're different than other python classes and we will cover classes in the future but I'm going to type class and I'm going to name this RPS for rock paper scissors and pass in an enum here and put the colon after it so that may look a little strange but just know it for now and then in the future we'll learn more about classes after that I'm going to use all caps here which is the tradition as we name constant variables constant data that does not change so I'm going to set Rock equal to 1. on the next line I'm going to set paper equal to 2 and on the last line I'm going to set scissors equal to 3. so the Syntax for constant data is all caps as the tradition and this data is not going to change so we have no plans of reassigning the rock variable a different value and so now when we use our enum we can pass in these numeric values and I'll show you what I mean just by putting it here at the top of the program for now so let's say print I need lowercase now print and then I would want to use my enum so I would say RPS and then I could pass in the value that we have and notice our value down here was player so if I had a value in player I would pass in player but here let me just pass in the number two save our code for now and I'll go ahead and press play and we'll see what gets output at the top it says RPS paper so by inputting the number two we got RPS dot paper return but it did return the paper value of course it still wants to play the game we did not exit the game after that so let's go ahead and choose the number two press enter a and we won that's great but let's look at some more ways we can get data from our RPS enum here so I'm going to go ahead and press shift alt and the down arrow three times and we can look at this in different ways so we could also be printing RPS dot Rock and after that we could also say RPS and use bracket notation and then pass in rock as a string and finally we could say RPS dot Rock and then dot value in lowercase now after this just so the game does not play once again I'm going to use our sys exit just to exit for now and notice how vs code then made all of this a lighter color because it knows the rest of this code will not execute after I put the exit statement here this is just temporary so we can check the different ways that we can get values out of our enum so if I save this let's run our python code again and you can see the first time we had RPS paper and that's what we had before when we passed in the two the second time we got RPS Rock when we said print RPS Rock the third time we got RPS Rock again when we use bracket notation and the fourth time when we check the actual value of Rock that's when we got the number back so if we want to get the number or whatever value is over here it should be from typing RPS dot whatever the enum name is and then we should get the number that is associated with it here by typing dot value so the different ways you can get that what we're going to do as I mentioned before is pass in the player value right there and of course the computer value as well so let's go ahead and delete these and finish completing the game so we want to use these in our string outputs for the game so let's go ahead and look at the you chose and player choice now here we needed to pass in a string before and that's what player choice and computer Choice both are before we casted those into integers but now we're actually going to use our enum and the integer so let's do that all instead of player choice here I'm going to cast to a string and I'm going to pass in RPS and I'm going to pass in the player value and then we could do the same here with the computer choice remove it and say string and then we could say computer and then we could oh I left off the RPS let's go ahead and say RPS and then of course we need computer and now we should get our RPS Rock RPS paper RPS scissors let's go ahead and play the game once and see what we get but running the game says enter one two or three let's enter two and it says you chose rps.paper python chose rps.paper Thai game so that looks good except that RPS dot is kind of strange for a user that's not a great user experience I'm going to go ahead and type clear here once again let's go ahead and remove that RPS and we can do that with one of the methods that we learned about in our last lesson so here I'm going to use dot replace and this is a string method and we're going to replace the RPS Dot and then we'll put a comma and the replacement is just an empty string now let's do the same here so I'm just going to copy this control C add it to the end of our string there and Ctrl s to save now let's run our code one more time and see what we get and we've got one two or three I'm going to choose three we enter you chose scissors python shows scissors tie game we can't end on a tie game let's run this code one more time I'm going to enter one another tie game let's run one more time three python wins well I didn't win but I didn't want to end on a tie so now you've built your first game you've learned about user input and control flow with if else if and else statements and we also added in one more data type that you learned about and those were enums hey before we get started on today's lesson about lists and tuples I want to go back and make one correction in the previous lesson I did make an annotation there I've already changed the GitHub source code but if you missed that annotation or haven't looked at the source code I just want to change this for you on line 18 where we check the player with an if statement I wasn't thinking and I used the bitwise or we should have just used the actual word or right here this will make all the difference as far as how this if statement works for you we're learning about lists and tuples today and you can see I have an empty folder named lesson six over here in the top left we're going to create a new file and let's name this file lists dot pi and then before we type any code inside of our python file let's go ahead and move the terminal which I can open with control in the back tick let's move it to the right if you don't have it over on the right side so I'm going to choose View and then appearance scroll scroll down to panel position and choose right and now our terminal is over here our python files here and then I'm going to press Ctrl B to go ahead and hide the file tree that was over here now lists are one of four collection data types in Python and what they do is hold multiple values and then we can reference those values with a common name so for example I could say users then I could set this equal to a list and inside the list I could put Dave and maybe John and how about Sarah so now we have a list of users so three values in one list and we just refer to it as the name users but of course it's not limited to just string data type or any one data type so I could just call a list here data set this equal to a list that has say my name number 42 and Boolean data like true and that's also a valid list or it can even be empty so I'll just call this empty list and I'll set it equal to an empty list and that is also a valid list so now let's say you're working with one of these lists but you don't know what's inside it and you want to check to see if a value is inside of it so let's do that I'm going to use a print statement here so we can see the output and I'll just say Dave which is a value that's in two of our lists and I can say in users and let's see what we get in the console after we control s to save our file then we can go up here by our play button and choose run python file and let's see what we get it says true over here so yes Dave is in users so let's switch this to data Ctrl s to save again and I'll click the play button and we've got true again so now let's see if Dave is in the empty list Ctrl s to save click play and that output is false so now let's say we want to get a specific item from a list and we know what position it is in and we have to remember that lists start with a zero index so Dave would be at the zero position so here I could say users and then I can use a bracket and put 0. now this should print Dave to our output terminal over here so once again click play and we've got faults because we had that above and now we have Dave as well and now I'm going to copy this down by clicking on line 9 where you see my print statement and you shift alt and the down arrow to just copy that line of code and now instead of using the position of the value we want if we want to know the last value in our list we could also use a negative one so I will save that and run and let's see what we get yep we've got zero which is the last value in our list so likewise we could use a negative 2 and now let's run this code again and we've got John so it does accept negative numbers also now if we want to know the position of a specific value we can use a method so I'm going to say print and I'll say users once again and then dot index and let's find out the index of Sarah inside of the user's list so now that I have passed the string Sarah to the index we get position 2 returned here in our output and now what if we want a range of values maybe we want the first and second value we can also do that so I'll start with print once again so we can see the output and I'll say users and now with bracket notation let's start at zero and let's go to the second position but no this will not include the value at the second position so save and run the code and we get a list returned that has only Dave and John from the zero and the first position in our list and now I'm going to copy this code down again with shift alt and the down arrow and let's say we wanted everything from the first position to the end of the list no matter how many entries were inside of our list well then we just wouldn't provide an ending value but we would start at the first position so now I'll say troll s to save the file again and run this and notice we get John and Sarah so by providing the first position here in the first slot of the range it does include John however when we provided the second position as the last slot in the range it did not include Sarah and now as you might guess this could also accept negative numbers so let me provide a full range here like negative 3 to negative 1 and let's see what we get so I'll save this run the code and we got Dave and John again so that is the same as saying 0 to 2 because it did not include Sarah because she's at the negative one position but it did start at the negative 3 position which is the equivalent in our list to zero I'm going to scroll up for a little more room and we should note we can use the length function which is Len and then use parentheses and pass in a list like users or we could pass in data that we created above and this will return the length of our list so I'll control s to save run our code again and you can see we've got three here because we have three items in the list so note that doesn't start counting at zero like the index of our list that has 0 1 and 2 when we have three items it actually Returns the length which is three because we have three items in the list and now let's say we have an existing list like users and we want to add more items to our list and we can do that with the append method so I'm going to say users dot append and I'm going to add Elsa to our users list and then I just need to print users so we can see the end result Ctrl s to save run the code and now our list of users has Dave John Sarah and Elsa in the list and what if we have another list that has users and we want to add those to our previously existing users list I will show you a couple of ways to do that one is to take our list users and say plus equals and then add the other list so I'll create another list here and I'll put in Json inside of this list so a list with just one item and then we'll once again need to print users to see the output and then we'll run the file and now our users list has Dave John Sarah Elsa and Jason so we added those two lists together if you will because this is a list although it only has one item and we had a previous list named users now the other way to do this is with the extend method so we could say users dot extend and I could pass in another list so I could say I've got a list with Robert and let's put somebody else in here so after Robert let's just pick another name say Jimmy and now we're adding this list to our users list so once again I'll need to print users to see the end result we'll run the code and now we've got a lot of people in our list because we've got Dave John Sarah Elsa Jason Robert and Jimmy all in our users list and now something to note about this first method here make sure if you use this that it is indeed a list but because if you were to do this without the brackets let me go ahead and delete these and then we'll run our code let's see what happens in the output notice it entered every individual letter as a list item from Jason's name so that's not what you want you want to make sure you have brackets here if you're using the plus equals because if not it considers every letter and item to be added to that list now here I created new lists to add to our users list when I used extend or when I used the plus equals above but we could also just pass in a pre-existing list so let me do that now with users.extend and I'm just going to pass in our data list now we'll print users once again and I'll run the code and let's see what we get now our previous list had Dave 42 and true and that's all been added to our users list that may not be what we want but of course it does work that way so you can just pass in a list name because we're referring to that full list up here as data and that also works we really don't want this mixed data in here though with 42 and true it's a valid list there's no problem with it but it doesn't make sense as users so I'm just going to highlight both of these press control and the slash to comment out both lines at once something to note about all of the ways we added to our list it added the items at the end of the list and so we see all the new items here at the very end of each list but we can pick our spot I'm going to scroll up for a little more room so we can add to our file and I will type something like users dot insert because we're going to insert into our our list and this is the insert method I want to insert at the very first position so I'll say 0 that's the index position and I'm going to put Bob's name in our users list so I will print users once again and we'll see if Bob is added to the beginning of our list when we run the code and yes we see Bob now at the beginning of the list we can also use bracket notation so I'll say users and after that bracket notation and I want to insert maybe more than one value at the second position slot I don't want to replace any of the values that are in our list I just want to insert two extra values so I've picked the second position and notice how I say it's not only going to begin but it's going to end right there so I'm not replacing any of the other values and now let's have a note list and I'll put in Eddie and Alex and we'll print users again so we can see that output save the file run the code and we should see Eddie now in the second position Alex in the third position but we didn't lose our previous values here where we had Dave John and Sarah inside of here's the first position second position Sarah in the third Now Dave is still in the first position but now John has been moved from the second position to the fourth position and Sarah is still there as well so this insert just made room for Eddie and Alex and we once again picked our spot but now let's look at how we can replace values so here I'll say users and we'll use bracket notation again and we'll start at the first position and we'll end at the third position now let's set this equal to another list and here we'll put in Robert and let's put it well we have a Jimmy already let's put in jpj that should work and we'll print users again and let's see what happens to the last version of our list compared to the one before it so now Robert is in the first position and jpj is in the second position so we replaced Dave and Eddie what was in the first and second positions it stopped at the third position but notice it did not replace what was in the third position or who was in the third position and that was Alex so it works much the same way as we return values how we specified this range in here and this is also referred to as a slice so we're referring to a slice but here we were very specific saying start and end at that same position so it did not replace any of the other values but this actually did replace two values in our previous list now if we can add data to a list we should be able to remove it as well so let's go over how we do that I'll scroll for some more room and the first thing we'll do is look at the remove method so I can say users Dot move and I could specify the user that I want to remove from my list I want to remove Bob so let's check the list afterwards again with a print statement run and we'll check our list and now Robert is the first position here in the index position of zero previously it was Bob so Bob is no longer in our list now we can also pop off the last user from the list or the last item from any list and we do that with the pop method but I also want to point out that the pop method will return that value even though it removes it from the list so here I'm just going to say print users dot off and we'll call that pop method and then let's run the code and we'll see that it actually returns Jimmy Jimmy was the last value in our list but now if we look at our list again and I'm just going to control C to copy and Ctrl V to paste this down here look at the list value afterwards so we have Jimmy here but Jimmy is no longer in our users list now we can also delete a specific user or a specific item from a list with the keyword Dell which stands for delete so I'll say users and now I can specify the user that I want to remove from the list let's once again just go to that first position in the list the zero index and so now this should delete Robert from the first position in our list and of course we won't know until we once again print the users list afterwards so I'll paste that down there let's run our code and let's check the list and yes jpj is now first in our list Robert is no longer first you can also use this delete keyword to delete a list completely so let's go back to that data list and I'll say Del for delete and then data and now let's check this by trying to print the data list and I'm expecting to get an error let's see what happens we run our code and yes python doesn't like that it says data is not defined so we deleted it entirely even though it's defined up higher in our file by the time we get to this print statement it is not defined so I'm going to comment this out and instead of deleting it and causing an error like that I'm going to use the clear method so I could say data dot clear once we call that clear method it will empty our list but the list will still exist so now when we run this it returns an empty list here on line 52. now that we've added removed inserted and modified lists maybe we want to go ahead and sort those lists as well so let's scroll roll for a little more room and underneath our last clear statement and print statement let's add users dot sort and after that we'll once again print users and let's look at what happens to our list of users so now it is alphabetical we've got Alex Elsa jpj Jason John Robert and Sarah but notice something else they all start with capitals so what if we put something in here as lowercase so let's do that I'm going to do it before we sort so I'll just put it right above here and I'll say at users and let's put it in the whoops not the curly brace we need the bracket let's start at the first position and end at the second so we're replacing Elsa with whatever we insert here and I'm going to insert Dave once again but make Dave all lowercase and so now let's check out our code and oh I forgot to put it in Brackets this is what I warned you about notice it inserted the letters individually and it organized them but they're all at the end and that's the point that I want to get to about this because when it's lowercase it comes after the uppercase so I'll save this and run it again and now we can see Dave is at the very end of the list so what we want is Dave inserted alphabetically here as well and we can do that we just need to change what we're doing and by the way we replaced Alex with the insert because Alex was in the first position John is still in here so Alex was replaced by the lowercase Dave okay so since we have determined that lowercase comes after all of the uppercase we need to pass something to the sort that will help Dave get inserted in the correct order actually Dave is inserted at that first position and then it is sorted so we're just going to do another sort after the first one here so I'll copy both of those put it underneath but we need to pass in an option here to the source so we're going to say key equals Str which stands for string dot lower so once we do that and we go ahead and run our code again we can see that it is now in an alphabetical order and Dave comes first just because it is a d the letter D comes in the alphabet before E so really what we needed to do was pass in this key equals string dot lower to include the lower case in the correct alphabetical order note these are all strings also so if we were sorting two different data types it really wouldn't work as expected it should be all the same data type you couldn't call this on a data type that wasn't string even so you need to make sure you have the same type of data when you're sorting it so now speaking of that let's look at some numbers I'm going to create another list called nums and inside of it I'll put 4 40 32 78 1 and 5. just some random numbers really and after that we'll say nums dot reverse now this is different than sorting it actually flips the array and I want to look at this because I don't want you to confuse the reverse method with reverse when we pass it into our sort function so nums.reverse and we will print nums and you'll see that the array or not the array the list this looks just like what I call an array in JavaScript but it's a list in Python so our list is now in the reverse order of what it was over here in our code beginning with 4 and ending with 5 it now begins with five and ends with four so we already know how to sort something in the ascending order with numbers which would be just to use the sort method like we did on users so it would start with one and work its way up to 78 but now let's sort in Reverse with our nums array and to do that I need to say nums dot sort and I'm going to pass in Reverse equals true and after that let's print nums once again and we'll see that it's different than it was with our reverse method that just flipped the list around so now when we run the code we actually get it descending instead of ascending so it's 78.42 5 4 and finally the number one something we need to note about all the different sort approaches we have used here is that they modify the existing list so notice when I print users after I have sorted I'm just printing the list so it has definitely changed it doesn't keep the same order that it previously had and the same with any of these others I'm just printing nums after as well so what if we want to keep the original list the way it was but yet sort the list just for an individual purpose well we can do that there's a couple of ways one is to use the global approach here the global sorted function so I'm needing to print now because it's not going to give me a second line that I could just print nums for example with because it's not going to change if I print nums after so I'll do that as well but I'm going to call the sorted function and I'm going to call it on the nums list and then I can just pass in my option right here so reverse equals true as well I'm going to comment this out so we didn't modify it before so when we did use nums we modified it here and we'll see that print I'm going to actually print the result of the global sorted function here and we pass in nums and then pass in our reverse option right there so now let's run our code we should see really the same thing we returned from this except our original array is not modified so if I were to print nums once again after this statement it should still look like it starts with 5 and ends with 4. so let's try that print nums here and run the code again and yes so here is our sorted array but here is the I said array again I'm going to occasionally mess that up because I'm talking about lists but it looks just like an array in JavaScript here is our list and this is the same order we had before we sorted it so this does not modify the original it just returns that sorted list for that one time and that's using the global sorted function now another approach we could take is to make a copy of the original list and then sort that copy so we would still have our original list I'm going to scroll just a little and I'll show you three different ways to make a copy one I'll call this nums copy and we'll set this equal to our list Noms dot copy and that will create a copy we could also say my nums and we'll set this equal to The Constructor here for a list and now we'll just pass in nums and this creates a copy of our original list Noms and the third way we could do this and I'm just randomly naming these things here so I have my copy now we'll set this equal to nums and we'll specify an index range here but really we're not going to specify the beginning or the end so it's just going to slice the full list and store it in my copy so it's once again a copy all three of these are actual copies of the original so now let me go ahead and copy our print nums here and then I'll paste it here and then I'm going to use shift alt and the down arrow three times so I have four print statements the first one is going to be the nums copy and the second one is going to be my nums and the third one should be my copy and after I pay ooh that's not right let's paste that in and now let's go ahead and print all of these lists and let's see what we get so they all kind of look the same here after we printed those and it should be the last four actually but they're not all the same and that's because these three are copies so let's go ahead and sort any one of these here so let's just call sort on the third one and we'll see that our original nums still does not change oh and I tried to print the sort statement what I should do is sort right before and then I should just try to print my copy so there we go let's remove this so mycopy.sort and then print my copy and that's why we had none there instead so let's do this now there we go so here is the sorted my copy list but here is the original nums list just a couple more things before we're finished with lists one is to go ahead and say that we can check the type of lists just like we did any other data type and that is say with type and then we just pass in our list so I'll pass in nums and now when we run this we will see that it is a class list type here so this is our data type that we received from the type function after that we can also we should also note that we can create a list much like we did up appear by passing in a list or a list structure to the list Constructor and that's how we created the copy of my nums but if I wanted to create a new list and let's just call this my list I could use that list Constructor and then inside I would just create this list and so I'll say something like one and we'll put in Neil and then let's put in a true and after that we should be able to print my list as well now notice earlier we didn't really use that Constructor and we were still able to keep the list or create the list but it should be noted that you can create a list this way as well so let's save that run the code one more time and here is the list we created with the Constructor and that covers lists for today but the next data collection type we'll look at is tuples so let's start learning about those tuples are very much like lists except the data inside the 2 tuples will not change and the order the data is in will not change so let's create a tuple and we can do that with the Constructor so we'll type Tuple and parentheses and then we need parentheses again inside of this and I'll just put in some random values as well much like I had for the data list above I guess and now we have created a tuple with the Constructor we could also create it without the Constructor so here I can say another Tuple and just set this equal to one set of parentheses and I'll put in some random numbers this is also a tuple and we can verify that so let's go ahead and print one of these I'll say my Tuple so we just see what it looks like when it prints out then let's print the type function again or the result of the type function when we pass in my Tuple then I'm going to press shift alt and the down arrow and then I'll put another Tuple in here as well just so we can verify both of these are tuples and here we'll run the code so we see here is the output of the Tuple it has parentheses instead of brackets and then you can see both of the tuples we created when we checked the type do indeed say Tuple now most of what we've already learned about lists also applies to tuples but we have to keep in mind that tuples cannot be changed however if we need to do something with a tuple we can get creative and copy it so let's look at how we do that first of all I'll create a variable here called new list I'm going to set it equal to the list Constructor and then I'm going to pass in my Tuple so this will create a new list out of my Tuple and then I'm going to say new list and I'll append a new value and I'll just add the value Neil after that now let's go ahead and create a new Tuple and we'll set this equal to the Tuple Constructor and we'll pass in the new list so now when I print new Tuple will have a new Tuple with the value Neil added the original Tuple my Tuple will not have changed but we'll have a new Tuple that did add the value that we needed to add to that so now let's go ahead and run the code and we see our new Tuple here that has Neil added to it when we assign values to a tuple as we do with another Tuple up here that is called packing the Tuple so likewise we can unpack a tuple and we can unpack it into new variable names so I don't have any specific name picked out here I'll just call the first one one the next one two and let's call the last one here hey but I'm going to start it with an asterisk and you'll see why so I'll set this equal to another Tuple but we are unpacking you can see we're putting values into these variable names so now I'm going to print each variable name so I'll print one print two and I'll also print hey and let's see what each one of these holes so when we run our code variable one holds the number one variable two holds the number four and hey holds the remaining values and notice they're unpacked into a list but it doesn't have to be the last one either so we could remove the asterisk from hey and instead put it in front of our variable 2 and now let's go ahead and save and run this code again and you'll notice now we get the value 1 inside of the first variable and the value 8 is inside of hey but everything in between goes to the variable 2 and it's a list so it has the values inside of a list a final note about lists and tuples in vs code and that is we can check what methods are available on a list or a tuple just using dot notation so I'll say print and I'll pull in the data list that I had earlier and type a DOT a period and then we see a list of all the different methods that we can call on our list that is called Data so that is one way to check what methods are available so let's put in the name of our Tuple so we had another Tuple and I'll once again have to delete the period type it again you can see that a tuple only has two methods count or index so let's call count and we need to put the parentheses after it to call it into action and it needs something passed to it one parameter and what or one argument if you will and what I'm going to pass is our another Tuple holds numbers if we look up here we put in the number one four two and eight I'm going to put in the number two two more times and now let's go ahead and pass in two to count and see what we get back so when I run the code we get three so it's actually counting how many occurrences of the number two are inside are another Tuple I've got Visual Studio code open and I've got a new folder over here in the file tree for lesson seven let's create a new file let's call this dictionaries then after that we'll end it with a dot py dot pi and then let's open a terminal window with control in the back tick and you can see mine opens here at the bottom but I'm going to choose View and then go to appearance go to panel position and choose right so it's over here on the right finally I'm going to press Ctrl B to hide the file tree so we have our code here on the left taking up all of that part of the screen and on the right is where we have our terminal window today we're talking about python dictionaries so I'll just put dictionaries here at the top and really dictionaries are used to store data values that are in key value Pairs and you'll see what I mean and just like when I accidentally called python lists arrays a few times python dictionaries look a lot like JavaScript objects and so I may accidentally refer to them as objects when I'm talking but if I do it's unintentional because we're talking about python dictionaries so let's look at an example I'll set ban and equal to a dictionary and they have curly braces and here's the key I'll say vocals and then I put a colon and after that I put the value so I'll say plant now I'll put another key and here I'll say guitar and then I'll put the value and I'll say page so that is a python dictionary and of course you could have more key value pairs it's not limited to two you could make a large one if you want to as well and it can be different data types it doesn't just have to be a string as the value now here I typed out this dictionary let me create a second dictionary that has the same values but I'm going to use the Constructor function for a dictionary so I'll call this band 2. I'll set this equal to the Constructor function which is d i c t then use parentheses and then I'll say vocals equals then I'll put in plant after that a comma and I can say guitar equals and I'll put in page now we'll be able to see that both of these create essentially the same structure for a dictionary here so I'll print band and then I'm going to use shift alt and the down arrow to copy that line down and then just print band two well I've typed in three a couple of times Band 2 is what I want there we go control s to save we'll run our code here and oh I got an error python was not found let's first run it using run python file the first time there we go after that we should be able to click play so we've got the same structure here here is our first dictionary band and just below it is band 2. they look the same you can create dictionaries in either way we can also check the type so I'll say print use type I'll pass it in band now I'm going to use shift alt and the down arrow one more time and here instead of type I'm I'm going to use the length function once again because we can also check the length of a dictionary so now when I run this we see the type as well and we see the length so it's saying it has two key value pairs inside of the dictionary I'm going to scroll for just a little room and I'll put another comment because I want to talk about how we access items in a dictionary there's a couple of ways to do it I'm going to use a print statement so we can see the output but we refer to the dictionary such as band and then we can use brackets and then we can name the key and the output will be the value the other way we can do this and I'm going to copy this down again with shift alt and the down arrow but is to use band dot get and that is a method that we can call on dictionaries and then we pass in the key once again so I'll pass in the key guitar here that's going to return the value that is paired with guitar so control s to save run our code and you can see we get plant from our first print line and we get page from our second and those are the values that are aligned with those keys in our band dictionary now what if we want to list all the keys so let me put in another comment I'll just say list all keys here I would say print and then band and then Dot keys and then I'll save and we'll run the code and let's see what we get so here we get a list of dictionary keys so we get vocals and guitar likewise we might want to list all values so I'll say list all values here in the comment then print and as you might guess it's banned dot values and we can run that code and now you can see we get a list of the dictionary values plant and Page we can also return the key value pairs as tuples and so here I'll say list of key value pairs as tuples and now I'm going to say print and then I'll just say band dot items and let's run this code again and you'll see what I mean when we get the output over here it's the dictionary items now inside of this list each item is a tuple so you see vocals plant and then you see another Tuple that says guitar page now just because these are wrapping down and it looks a little strange I'm going to see if I can drag this window over a little and it might make our console a little easier to read because I'm not going to usually need to type past about this width okay so our dictionary items wrapped down but the keys and values for example did not so this is just a little easier to read here now one more thing we might need to do is verify if a key exists in a dictionary so that's what I'll put here verify a key exists and now we'll say print and we can just see if guitar is in band now let me do another one so I'll shift alt the down arrow again and instead of guitar I'll look for triangle maybe I should have looked for cowbell let's run this let's see what we get so first guitar in band is true but triangle in band is false let's scroll for some more room again and we'll look at how we can change values in the dictionary so I'll put change values here in my comment and after this I'm going to say band and then I'm going to specify the vocals key so I'm using brackets and then the key once again I'll set this equal to Coverdale now that would set the key value pair to vocals Coverdale instead of vocals plant so the value for the key vocals has changed once I do that now something else you can do is use band and call the update method but now we need to pass in curly braces and we need to give the key as well now we could update vocals or guitar here but we can also create a new key value pair so that's what I'm going to do I'll make this base and then I'll pass in the value jpj and then if we check our band afterwards you should see we have changed vocals to Coverdale and we should have added a new key value pair as well that says bass and jpj so let's run this code and see what we get here is our dictionary now it has vocals Coverdale guitar Page bass jpj now what about removing items so I'll comment that as well remove items so we'll print and then I'm going to look at band dot pop now the reason I'm printing is because pop will return a value it will return what we remove from the dictionary so here I'm going to say base and so we'll see what gets returned or what gets output here from the print by doing band.pop base and so after that I need to go ahead and print band one more time and let's run this and you can see we don't get a tuple or the full key value pair pop does return the value though of what was removed because then we print band afterwards and we see it no longer has base jpj in the dictionary that key value pair has been removed but pop only Returns the value now I'm going to add a new value like we learned before so I'll say band use bracket pairs here and add drums I'm going to set this equal to bottom and after I do that I'll go ahead and print the band again just so we can see that the new value has been added but now we'll also print and then we'll say band dot pop item if I spell item correctly what pop item does is it removes the last thing that was added the last key value pair that was added to the dictionary but what we will see is this is going to return a tuple so I'll print band here as well so what we last had was the removal here from base the jpj and then it once again had our dictionary down to two key value pairs so we'll see this twice afterwards as well save and run the code now let's look at what we get here so we added bottom and then we print band and that's what we should see here is a dictionary that has vocals guitar and drums and the value for drums is bottom then we used the pop item method and so it removed what was last added the full key value pair and it returns it as a tuple and that's what we see here so then when we finally printed band here the last time our dictionary is once again back to just vocals and guitar R now this deals with removing items from a dictionary what if we want to delete or clear items so once again a comment here and I'll put delete and clear and then if we want to delete an item first I need to add that item again let me just copy this from above here on line 41 we're going to add key value pair of drums and bottom back to our band and then after that let's go ahead and delete with the keyword Dell and I'll say band and say drums and you can see Visual Studio code wants to help me it knows what's in the dictionary so that's very useful don't always have to type that out so now we're deleting that from the dictionary and I can print band once again so we will once again see that it has been removed what we could do though and remember we created another band up here at the top we've also got band 2. so what we could do is empty out a dictionary completely by using Band 2 as our dictionary and then saying clear the clear method and then I'll print and two which should be an empty dictionary so we should just see the curly braces and after that I'm going to delete band 2. delete the entire dictionary and we do that with the delete keyword also but we don't specify any specific key we just name the dictionary and it completely deletes it so I can save and run this and we won't see everything that we just had there we'll see the print once again of the band dictionary after it just has vocals and guitar well also I guess it's this line right here we'll also see the empty Band 2 dictionary and that's why we just see the curly braces there is no output after we delete the Band 2 dictionary it has just been deleted from our application now let's scroll up and talk about copying dictionaries so here I'm going to leave a comment and say copy dictionaries after this I need to talk about the way not to copy dictionaries first so let's say Band 2 I'm going to create a new Band 2 because I just deleted it above if I set this equal to band that doesn't really create a copy it creates a reference and so I want to put this here creates a reference and what that means is they're both referring to the same place in memory or the same dictionary so after you create Band 2 and you add or remove something to it it's going to also add or remove the same thing to band so this is why we don't want to do this because they were actually refer to the same thing view it as a place a storage place and both of these variable names are referring to the same thing so what I'm going to do here is say print and I'm going to say bad copy because you really don't want to do this and I'll give the example of what it actually does so here I'm going to say print Band 2 and then I'm going to use shift alt in the down arrow and we'll also print band but after we do that let's go ahead come down an extra line and say Band 2 and then we'll put in Drums so we'll add drums to Band 2 and I'll set drums equal to Dave this time after we do that let's just print band once again because we didn't do anything to band right so you wouldn't expect it to change let's go ahead and run the code and see what we get so we can see Band 2 is the first one we print right after it says bad copy and then band one and they look the same but then we add drums to Band 2 with the value of Dave but we just print band well that last print of band already has drums and Dave in it so this is what you do not want to do so I'm going to comment these things out I'll just highlight all of those and press Ctrl and the Slash and it will add comments to all of those lines but I did want to show you that because that's not the way you want to create a copy so how do you want to create a copy well let's go ahead and say Band 2 equals band dot copy and we can call that copy method and now they will not have the same reference so I can say Band 2 as a matter of fact I can just copy these lines Ctrl C speaking of copy and then we'll go ahead and paste them in with control V and then I'll print band here and after that I might as well print Band 2 as well so you can see that they're different so we're just adding drums to Band 2 again after we use the copy method now let's run this code and what happens is we have and here the first one and then we have Band 2 on the next line and only Band 2 as drums with the value of Dave but both were printed after we added drums to man 2. so to be consistent I guess I should add the line here good copy and I'll leave the commented lines inside of the course code as well so if you're getting this course from GitHub at the course resources link you'll be able to see this this is what you do not want to do and that's why I said bad copy this is what we want here with good copy now there is another way to make a copy and that is using the Constructor function so let me comment that as well I'll put or use the dictionary instructor function so we can make a copy this way also so I'll say Band 3 equals then I'll use the Constructor function and I'll pass in band so this makes a copy that is not a reference as well so I'm going to print good copy here as well and after that I'll print and three and we'll go ahead and run the code again and you can see we didn't add anything to Band 3 but you can see it made a copy and this is a good copy so that's another way to do it okay one more thing to discuss about dictionaries and it can seem a little complicated when you first learn about it but I think you'll get the hang of it after you experiment with a little bit and that is nested dictionaries this means that the value for a key value pair can be another dictionary so let's look at this and I'll create a dictionary called member one and I'll set this equal to of course curly braces then I'll have name and let's say plant here and then I'll have instrument and here I'll put vocals now I'm going to just highlight all of this and do shift alt in the down arrow I'll turn this into member two so a second dictionary here I'll make this name page and I'll make this instrument guitar okay now let's create a third dictionary and let's call this band and in this dictionary we'll have a key called member one and we'll put Member One the dictionary we created above has the value and let's do the same here member two and let's put number two the dictionary we created above as the value so you can see band is going to have nested dictionaries here so Member One is the key but the value will be a dictionary so let's go ahead and print this see what it looks like inside of our terminal when we run the code so here's our dictionary band and well I started one line ahead there we go here is our dictionary band it's got Member One for a key but the value is another dictionary remember two for a key but the value is another dictionary now if we want to get a specific value here we have to go one level deeper so we'll print and then we would say band and let's go ahead and use our brackets and you can see BS code wants to help us once again so I'm going to say member one and then from that I'm going to use brackets again and now it's not helping us so much notice we had name or instrument and I don't see those readily available here so I'm just going to type name because we want to get number one so there we're going one level deep and then we want to get name so that's the second level deep we'll save this and run the code and you can see the output here is plant that's because we were able to drill down into our nested dictionary to get that value by adding another bracket and you need to do that every time you'd have a level could you have another level deeper and so on yes you could okay a final note on dictionaries before we move on to working with sets and I'll Scroll once again I'll just type in band as our typical dictionary here remember in vs code you can use dot notation so type a DOT after your dictionary and all of the different methods will pop up so you can experiment with these we covered quite a few of these today but not necessarily all of them but vs code will help you see what methods exist or a dictionary or a list or whatever data collection type you are using okay now let's move on to sets I'll just type sets here now sets are the fourth and final data collection type type that we are going to cover so now let's look at creating a set I'll say nums equals I'm using curly braces again but it's not a key value pair I'm just going to say one two three four and that is creating a set we can also create a set with the Constructor function so I'll say nums two I'll set this equal to set now we have parentheses but now we need double parentheses I'll say one two three four so we've created two different sets that way I'll print nums and then I'll go ahead and do shift alt and the down arrow and I'll print ums two I'll do this one more time and inside of here I'm going to say type nums and finally one more copy down with shift alt and the down arrow and instead of type I'm going to check the length because we can do all of those things again with a set so now when I run the code we have got our first set we created we've got our second set we created with the Constructor function we can see what data type we have and we see the length there are four elements in our set now scrolling up we'll look at one of the top advantages of a set of data and that is no duplicates are allowed so I'll just type this here no duplicates allowed and then I'm going to say nums once again equals and I'll create a set here but it'll be a little different data than above notice I put in two number twos okay after this I'll go ahead and print nums what do you think we'll get for output once I put both of these in but we know a set doesn't allow any duplicate let's take a look I'll run the code and the out output is a set that does not have a duplicate at all it didn't create an error because I put one in it just ignored the duplicate and that's what happens when you try to put something else in a set so we should also note that a True Value true is a dupe I'll say of one and false is a dupe of zero now I'm scrolling over so I'm going to press alt Z so the code or the comment line wraps down to the next line see how 111 is a little bit deeper here compared to the other line so it's all still one line it's just wrapping down now I'm going to create a nums set once again and inside of this set I'm going to say one true two false three four zero so now let's think about what we might get returned and we'll analyze this after we actually check our output here so I'm going to print nums once again and now nums has some duplicate data remember one and true are considered to be duplicates false and zero are considered to be duplicates any guesses as to what will the output be let's take a look and we get false one two three four so number one was in here first and so it ignored the duplicate true alts was in here first so it ignored the duplicate zero then notice it's in order also so false comes before the numbers which is also zero so if we had zero it would essentially be in order as well worth noting but notice it did remove the duplicates when we were working with Boolean data that true and false because one is considered true usually in programming and zero is usually considered false as well so those are considered duplicates in a set you can also check if a value is in a set and we can do that with the in keyword once again so I'll say print 2 in nums and if we run this code we get back true yes because 2 is in our nums set we see it right here as well so that is true so you can check to see if any value is inside the set but I'll put an extra note here but you cannot refer to an element in the set within index position as we had with lists or a key as we did with dictionary so you can't refer to any specific value based on a position like that and there's also no key to refer to but you can check to see if the value is in the set scrolling up again for room let's talk about adding a new value to a set so here we'll say add a new element to a set and we can do that with nums dot add and then I'll just pass the number eight and we'll print nums once again and we'll check our set so let's run the code and now here's our set once again but it also has the number eight in there after that you can add I guess I need a space between these let me put a little extra line there you can add elements from one set to another and to do that let me create another set just called more nums set this equal to a set that has five six and seven in there then after we do that say nums our original set dot update and then we'll pass in more nums and I'm not sure why I put a space there we don't need that space and remember see that error there spaces and tabs are indents are important in Python so an extra space like that could cause problems but here we are using the update method or nums and we're passing in the more nums set as well so we're adding elements from more nums to the nums set so we'll print out nums run our code and you can see now our numset also has five six and seven added to it I'll add an extra comment here as well underneath and this comment is you can use update with lists tuples and dictionaries too and what I mean by that is you don't have to pass in another set here you could pass in a list to update or a tuple or a dictionary as well update will still work now with update we took all the values inside of the more nums set and we added them to the nums set but what if we want to merge two different sets and then create a new set from those two so let me comment that here merge two sets to create a new set and now I'll have to create the sets first I'll say one and let me put this equal to a set that has one two three and then let me create another one and I'll just copy down here I'll rename this two but I want to change the values also I don't want duplicates right now so it's five six and seven and after we've created both of those let's say my new set is going to equal 1 and then I'm going to use the union method and I'm going to pass in 2. so here we're merging these one and two to create a new set so I want to print oops print my new set and we should see the merger of those two but that didn't change the original set one or the original set two let's look at a couple of more useful methods when we're working with two sets so I'm going to copy lines 131 through 133 with control C and I'll just paste here below again but instead of merging two sets to create a new set here we're going to keep only the duplicates from the two different sets now right now I don't have any duplicates so let me change the values here in two so we have some overlap so 2 and 3 would be duplicates in both of these sets now and now that I've done that we'll say one dot intersection update and here we'll pass in two now let's print one this didn't create a new set so what happens is it actually changes the first set here that we call intersection update on one to only include duplicates so we should expect to get a set that only has two and three back so when we run our code that's what we've got here is two and three now kind of the opposite of that so I'm going to go ahead and copy this down again three lines that start everything and instead of keeping only the duplicates we're going to keep everything except the duplicates so here's one and two as well so two and three the numbers two and three are the duplicates so we're not going to keep those so now we're going to expect return a set that has one and four only we're going to do that with a different method here's one and then it's called symmetric difference update here we'll pass in the second set notice it's still happening or being applied to the first set that we call the method on as well so we're going to print one I'll save that and we run our code and you can see the set that we get here is the output just contains one and four so it was the opposite of the intersection update so that just about covers it for sets once again a reminder that you can use your set and then use dot notation to pull up all the different available methods and there's some here that we didn't cover today so you could experiment with these as well and look those up in the documentation of course is linked in the course resources I've got Visual Studio code open you can see I have a new folder for lesson 8 over here in the file tree let's create a new file and let's call this Loops dot PI from there let's go ahead and press control on the back tick to open a terminal window and then let's go to view and from there we'll go to appearance come down to panel position and choose right so our terminal Windows here at the right and then I'm going to press Ctrl B to hide the file tree so we can see our code here on the left in Visual Studio code and we can see the output and everything we run at the terminal here in the right so when we talk about loops in Python we can talk about two different types of Loops there's a while loop and a for Loop let's look at while Loops first and a while loop will execute a block of code while a condition is true so let's create a basic while loop let me first set a value equal to one and from here I can say while value is less than 10 and then we put a colon and now we have a block of code inside of our while loop notice we're indented so I'm going to print the value and now we must increment the value to go ahead and make it greater than 10 at some point or if not or at least equal to 10 the way we have this current Loop set because if not we will have an endless loop or an infinite Loop that could crash our computer it would use up all the memory and it would just go on forever and we don't want that to happen so let's go ahead and say Value Plus equal one so now this is going to increment every time it goes through the loop and it will eventually be equal to 10 or greater and the loop will stop so let's save our code and from here we'll use the drop and we'll choose run python file and you can see over here now we get one two three four five six seven eight nine it doesn't get to 10 because this says while less than 10. so if we wanted to print the number 10 we would say while value less than or equal to 10 now we can run this code again by clicking the play button and we get 1 through 10. so we have iterated through this Loop 10 times so it goes through the loop 10 Times Printing each number now we can stop a loop in another way besides making this condition true and that is using a break statement so after this print value let me go ahead and say if value equals five so I'm putting an if statement in our Loop then I'm just typing the word break and that break statement There Will Stop the Loop when value is equal to 5. so let's run the code again and you can see we go one two three four five because we print first so we print the value of five before we get to the if statement and then the loop stops now I want to keep this example in here for you so I'm just going to highlight all of this Ctrl C to copy and then control and the slash to comment that Loop out and below it I'm going to paste with Ctrl V and now I'm going to show an example of the continue keyword so instead of break I'm going to say continue this will stop this current Loop where it's at and go to the next Loop but we have to be careful here once again we have to think about where we're incrementing the value if we continue here and skip to the next then we're not incrementing that loop again and that's important that we continue to increment that loop at this point it would be equal to 5 and it would just continue to be equal to 5. so that's not what we want we better increment our value before this if statement and let's go ahead and print the value after the if statement and so I'm just using control X to cut those and then Ctrl V to paste those so cut instead of copy with control X and then Ctrl V to paste those values but you can see I've rearranged what happens in the loop but now this will skip to the next iteration when it equals five so let's see what happens when we run our code you can see it starts at 2 because we don't print until we're down here so we've got 2 through 11 and that's because we're adding one immediately once we get inside of the loop but notice we didn't print the number five and that's because we used continue here so it never gets to the print statement it just goes to the next iteration of the loop now we can also add an else to our while loop so I'm going to to come down a line bring the else over to the left where it's not indented and then have a print here as well so when do you think this else will occur it should occur when the loop has completed but not note this not if we use the break keyword if we break the loop the else will not execute so only if the loop actually completes as it should and this condition is no longer true then the else will occur so here I'm going to say value oh I need quotes value is now equal to now let's concat here with the plus symbol and then just put in our value so I'll save this code and run it and let's see what we get oh I tried to print an integer I should have known better we need to use the string Constructor here and make this value a string because it's currently an integer and now we can run the code again and it will work so we have value is now equal to 11. okay I'm going to highlight and press ctrlash to comment out that loop as well and let's move on to for Loops so let's make a basic for Loop a for Loop iterates over a sequence and the sequence can be contents of a collection data type that we've gone over like lists tuples dictionaries or sets or it can even be the individual characters of a string so I'm going to make a list first called names and inside this list I'll have Dave and Sarah and let's put in John as well so we've got three names in our list and now we can use a for Loop to iterate over this list so I'm going to say 4X in names and then inside the loop we'll just print X now note I'm using X here but I could say for name in names I could use any word or letter just some type of character is essentially what I'm doing to represent each value in the list as it iterates through the for Loop so we'll save and run our code you can see we get Dave Sarah and John all printed here in our output in the terminal so now I'm going to scroll up just a little bit and let's create another for loop as I said you can go through each character in a string so what if I said 4X in Mississippi that is a long word that most of us here at least in the United States learn how to spell in school and we memorize m-i-s-s-i-s-s-i-p-p-i because it's a long one and after this we'll run the code and we should see each individual letter on its own line because we printed one letter of the word Mississippi each time the loop iterated okay I'm going to comment these two out but I'm going to leave our names list above and then let's go back to this names list and let's iterate through once again so I'll say 4X in names and then inside the loop I'm going to say if x equals Sarah oh yeah I need my colon there then I'm going to use the keyword break once again but I'm going to print X so what do you think the output of this Loop will be let's find out I'll run the code and it's just Dave so when x equals Sarah the loop stops with the break keyword and notice the print statement was after the break so it only printed Dave before it actually stopped the loop and stopped printing so now I'm going to copy this once again highlight Ctrl C to copy and come down Ctrl V to paste and I will highlight this and control slash to comment it all out but I'm going to switch the break keyword to continue here now let's think about what the output will be what do you think will happen at this point remember continue stops the current iteration and just goes to the next one in the loop so let's run our code and you can see we get Dave and John and that's because when x equals Sarah it continues and it skips this print statement and it just goes to the next iteration of the loop which prints John okay scrolling for some more room again I will comment this Loop out and from here we're going to look at ranges because we can have a for Loop that iterates through a range so I'm going to say 4X in range and then I need to provide a number I almost forgot to do that let's just put the number 4 here and after that we'll say print X so now we're going to go through a range of numbers but notice what the starting number is when I run our code it's zero just like the index in a list so 0 1 2 3 even though we said we want a range of four numbers it starts at zero however I'm going to copy this down by highlighting both and then shift alt and the down arrow would also work to copy down and from there I'm going to say start at two and then have a range of four or stop at four essentially so it won't necessarily be four numbers we're still saying when to stop now we're also saying when to start and just to avoid any confusion I will comment this out let's save and run the code and see what we get we get the numbers two and three because we started at 2 and we said stop at four and just like above when we said four it didn't use the number four it actually stopped there so we started at zero and we got four numbers but what if we had put in say five for example let me change this and now we say a range of five numbers we run it should be zero two four so you see how that works let me switch this back to two and four so it's going to include the number that you start on but it's not going to include the number that you stop on now there's one more thing we can do with ranges so I'll once again shift alt in the down arrow to copy this down and I'll comment out the loop above it but the thing we can do with a range that we haven't accomplished yet is actually telling it how to increment instead of ones which is the default here you saw that it went through by 0 1 2 3 4 Etc we can actually tell it to say okay start at zero go through the number 100 or up to the number 100 but increment by fives instead of by ones so now when we run our Loop we count from zero all the way up to 95 remember it will not include the number we stop at so if we actually wanted the number 5 to be the beginning number we could start at the number five and we would want to make sure our number was higher than 100 if we wanted to include the number 100 so now when we run our code it starts at 5 and it ends at the number 100 because it increments by fives now just like we discovered with a while loop we can also have an else statement with a for Loop so I'm going to add an else here at the end and at the very end I'll just print and I'll say glad that's over now I need an apostrophe s so I need to escape the apostrophe and that's with that slash and then I'll say that's over save and so now our Loop should run and at the very end we get glad that's over okay just to visualize our names list once again I'm going to copy it and just bring it back down here to where we can see it and after that I'm going to create another list and I'm going to call this list actions and inside the list I'm going to have codes and I'm going to have eats and I'm going to have sleeps and the reason I want two lists here is because we're going to look at using a nested Loop so we're going to Loop through two different lists and I'll just bring those to the top now let's look at how we could do this so the first thing we want to have is 4 and I'll use name in names so for each name we're going to do something now the next Loop is going to be inside this first for Loop so for Dave then we're going to Loop through all of the actions so I'll say for Action in actions and now I want to print and I'll say name plus and then I'll give a space here another plus and then action and then one more plus to concat a period at the very end of the statement so what do you think the output of this nested Loop situation will be what I should get is Dave codes Dave eats Dave sleeps and then we'll get the same for Sarah and the same for John let's see if we get what we expect that is what we get so we get three statements about Dave then three statements about Sarah and then three statements about John and that's because name is in the outer loop so it goes through the name and then it Loops for every action for that specific name before it moves on to the next name so let's go ahead and copy this down I'll highlight it all shift alt in the down arrow and then I'll put a space between and let me comment out this Loop and let's go ahead and switch this around so here I want for I press Ctrl D to highlight both names and I can type action and here I'm going to highlight action and press Ctrl D and I'll put in name so now I've got the action on the outside and the name on the inside so let's think about what we expect to get now we should get Dave codes and Sarah codes than John codes because the actions are on the outside so it's going to apply code to each of the names before it moves on to the next action so let's go ahead and run this and confirm our expectations and that is what we get Dave code Sarah codes John codes then we get Dave eats Sarah eats John eats so whatever is on the outside is what happens and it Loops through for whatever is on the inside so play around with this if it's hard to understand because nested Loops can be a little hard to wrap your head around at first but after you get the hang of it I think they will make sense and of course a natural question would be can you even have more nested Loops inside yes you could and of course you need to understand how two loops work together before you start adding more Loops in there but go ahead and experiment and it will help you understand how nested loops work okay now I'd like to take a little time today to apply just a little bit of what we've learned about loops to improve our rock paper scissors game from lesson five so let's go ahead and open the file tree again now in your file tree oh press Ctrl B to do that in your file tree maybe you've got all of your different lessons in one folder where you've still got the RPS dot Pi file if you have that great if not you might want to open it up and use it for the rest of this lesson I'm going to create a new file over here once again named RPS but I'll put the number two after it so this is the second version of our rock paper scissors game also over here in the terminal I'm going to type clear just to clear all of that out for now now I'll hide the file tree again because we want all of this room and I'm pasting in our original code from lesson five and this is our rock paper scissors game but we want to add a loop to our game so we can play again and again without having to restart the code so to do this underneath our enum here I'm going to add an extra line or two and then I'm going to Define a variable saying play again and I'm going to set this just equal to true so a while loop doesn't have to have an equal sign we can just say while play again and this means while play again is true if play again is ever false then the while loop will stop but note indentation is important in Python so after I start a while loop here I need to select everything else and I mean everything so I'm starting to highlight here and then I scroll down hold down the shift key and click so it highlights everything and press the tab key so we need that indentation to say yes all of this code is inside the loop and I can see I still have a typo here I have play gain instead of play again and I want play again for my variables so let's go ahead and make sure that the type is the same here so play again is the variable and while it is true we're going to Loop through our code I don't need those Extra Spaces here but we do have to consider how to stop our Loop because right now play again will always be true so we would have an endless loop let's scroll down to the bottom of our code where after we have determined who the winner is and we can add just a little more and remember to indent so it's part of the loop here I'm going to say play again is going to equal input so we're going to get some more input from the user and here I'm going to say slash in because I want a new line instead of printing a blank line oh I need quotes first and then slash in and then I'm going to say play again with a question mark go ahead and put a space and another slash in so the next part appears on another line and I'll say y or yes or then another slash in for a new line then I'll say Q to quit not quite but quit and then two lines so slash n slash n I'm also going to press alt Z so this wraps down and we can see all of the code at once and now we just need a logical if statement to handle this so after we get our play again input we'll say if play again dot lower which will take the Y if the user does not enter a capital Y it would make it lower case or if they do enter a capital Y I should say it'll make it lower case so either way we only need to check a lower case after we use our lower method here so if play again dot lower equals y then we know we want to play again so we can just continue our Loop and go to the next iteration but else let's go ahead and print a kind of thank you message for plane so let's print and inside of this I'm going to press my Windows key in a period you may be on a Mac or Linux that has a different way of getting emojis but that's how I do it here then I'm going to start to type celebrate so I can bring up a little celebration emoji and I'm going to put it in here several times there we go I can remove the hands that was a mistake or if you want the hands that's fine too I also want to put another slash in in front of this so I have another line break before it starts after that I'm going to print one more line and in this line I'll say thank you for playing an exclamation mark and then another new line character and after that we could end our Loop in a couple of different ways one we could say play again equals false that should end the loop but also we could use a break either one would work so just so you know if you were thinking break nothing wrong with that I can leave break here commented but I don't think I will because play again equals false would work so let's just do that in mental note break would work if that's how you wanted to end the loop as well after that let's go ahead and put a message at the very end of the program so we'll use that CIS exit again as we did above in the program I'll just say buy I'm going to use one more Emoji here and I want my wave Emoji a little hand so a goodbye message there so now we've pretty much put our whole game in a loop and we can continue playing it over and over again one thing you might notice I used these slash ends instead of some of these empty lines here so we could consider refactoring our code to remove any of these let's see how many we have we can highlight what we have here and then I can control F it looks like we have three of them in our code so let's remove this first one and when we remove that then we want to make sure to put in a slash in when our string begins okay let's go to the next one it's right here before the player choice statement so we'll put a slash in there and then we can remove that one and then we have one after as well so if it's always after this the place to put it would be at the end of the statement above and then we can remove it as well and now we've also refactored our code to be just a little bit more efficient and we'll close that out Ctrl s to save and let's play our game and see if it all works as expected so now we can choose I'll say one for rock and we won and it asks us play again y for yes or Q for quit what we really know they don't have to put Q for quit anything that's not a y will actually quit the game so for example I could put in an A and check yes thank you for playing buy so let's run the code again this time I'll choose Rock once again and we add a tie game I'm going to choose y so I can continue playing and I'll just put in a lowercase Y and we continue playing rock and python one now put in an uppercase Y and enter yes we're still playing so now I'm going to say 2 for paper tie game so lowercase Y and let's choose one for rock python one again so now I'm ready to quit so let's just press q and yep that works too thank you for playing goodbye once again our game's not perfect yet but we have improved it so this shows you how to apply some of the things we've learned as we continue and we'll apply much more with some small projects and keep improving this game too as we go I've got Visual Studio code open and a new lesson 9 folder open over here in the file tree let's create a new file and let's call this file functions.pi functions are reusable blocks of code and when we call a function it runs the block of code inside the function so let's create a simple function I'll start with the def keyword which means we're defining the function then we'll use hello to name our function and we'll use parentheses so our function is named hello and after the colon we'll press enter and notice vs code brings us down to the next line and already indents so this is where our block of code inside the function starts so now we can print and we'll say hello world with an exclamation mark now that is our function but it is defined here it is not being called yet so if we're to run our code right now we won't see any output we won't see this print statement happen so I can run it and we don't get any output over here so what we need to do is call the function so we do that then in our code wherever we need to use the function by just calling the name of the function with the parentheses after it so now when I save this and it scrolled back up but there we go there's our definition of the function and here is the call to the function now we'll just run the code and we get Hello World here as output in our terminal I'm going to go ahead and leave this open but I'll press Ctrl B to hide the file tree is we don't really need to see the file tree right now now let's talk about naming functions they need to be all lower case and if they have more than one word we can separate the words with an underscore so let's do that and rename this function hello world and now you can see Visual Studio code is telling us that there is not a hello function so we need to go ahead and add the underscore World here and now we'll call the function by name once again using hello world so we get the same output but that's how we want to name these no capital letters no hyphens or dashes we need to use underscores if we want to separate a word and we need to use all lower case now sometimes functions need to receive data and we can use placeholders for that data and those placeholders are called parameters so let's go ahead and create a simple function that receives a couple of parameters so I'll say def once again the keyword Def and then I'll call this sum it's going to receive num1 and num2 we'll put the colon here and now we start the block of code inside the function and we're going to print num1 Plus num2 so once again a very simple function now remember that this function is not being called yet so if we were to run our code right now we would not see the output of this we need to call the function now these placeholders are parameters when we call the function and we pass in the actual data we're passing in arguments so if I say sum and I pass in 2 and then 3 now we're going to pass in the arguments 2 and 3 and they will use the definition of this function so they're represented here by num1 and num2 a distinction between parameters in the definition and arguments that you would pass in is the parameters never change however arguments can change with every function call so let's switch this to 1 and let's say 7 or this could even be 100 and then we could leave that as three so all of these function calls are reusing this code that we defined for our function sum notice the parameters never change they're just placeholders so that is the difference between a parameter and an argument the argument is the actual data when the function is called so now let's go ahead and save this code and we'll run our code and we'll get the output here so we have the sum of all of those numbers underneath of our hello world and note this was also a good demonstration of how our function is reusable so we have a reusable function that we can use anywhere we need it now and we used it three times here with different arguments now our function isn't really too useful if it just prints this value to the console we might want to return that value and use it in our program so let's look at how we can do that and I'm just going to change this function so we'll remove these but of course you know how to call the function now and instead of a print here we'll remove the print and the parentheses I'm going to use the keyword return so our function actually Returns the value the total of the two parameters that are here so that whichever arguments we pass in if we pass in 2 and 3 it should return 5. so let's do that now by saying a new variable total equals the sum of two and three and then we can print the total just to verify that yes total now holds that value so now let's run our code again and that's what we get is 5 right here now right now our sum function is a very basic function and we are just assuming that two numbers will be passed in but we can't always make those assumptions when we are writing programs so let's verify that we're actually receiving numbers because if we passed in strings right now they could be concatenated together because it would just push the two strings together and that would also work and that's not what we want our sum function to do for example so let's go ahead and check some of our input here our parameters that are being passed in well the arguments are the values but the parameters is what we'll check in the definition so here we'll say if and then let's check the type of num1 and we'll say is not int and then we could also say or type of num2 is not int so here's our if statement we put a colon at the end and now we want to have a return keyword here but notice we're not returning anything this is just called an early return so we're exiting the function it will never execute line 11 here in our code we'll never return the sum of num1 and num2 because they are not integers now I can press alt Z to wrap this code down or I can close this so we can see the full line here so now let's see what happens if I change one of our arguments to something that is not an integer I'll just pass in a string with the letter A so I'll save the code and once again run the python file and now our function returned none that is a special value in Python it's not true or false it's just none so that's also something to be aware of if you ever see that however that's what is returned from the function So currently our total value is none so now we're ensuring to get a result from our sum function that two integers do need to be passed in but what happens if nothing is passed in we'll probably get an error so let's confirm this when I remove the arguments from the function call and once again run the function and yes we received an error it says sum is missing two required positional arguments num1 and num2 so our check here our if statement doesn't really help if somebody forgets to pass in those arguments but there's something else we can do we can give default values for these parameters in case they are not passed in so now let's just provide one default parameter value and I'll just make num2 equal to 3. so now I can just pass in one number say the number one and I I can call the function and num2 will automatically have the value of 3. so if I do this and run the python code we get 4 for the output of course this doesn't help if somebody forgets to pass in the first value so one thing we could do is say num1 has a default value of 0 and num2 has a default value of zero so now if no numbers are passed in we should receive a total of zero and we do and if we pass in just one value say the number one we should get one in return however our function does accept two values so we can pass in a second argument and now it should add those two numbers together and we get three so I'll once again press alt Z to just wrap this code down to the next line so it doesn't extend off the screen here but what we have accomplished now with our function is we have default parameter values of 0 for num1 and num2 and we're also checking to make sure that the values passed into the function are integers and if they're not we just have an early return but possibly instead of that none value if we always want to have a number returned we could just return zero as well so now if we save our function and once again call it without any of the arguments being passed in and we run the function instead of none we get 0 that might be more useful if we're just using this in mathematical equations because 0 is something we can continue to use in the program and it wouldn't be some expected out unexpected output like the word none now just as a reminder of how to call this function I'm going to put a couple of numbers in here like 7 and 2. so this will be in the course resources and you'll see once again how to call the function with two arguments and we get the output of 9. okay now some functions may receive multiple arguments but when you're defining the function you won't know how many arguments are going to be passed into it so let's go ahead and look at a function that would be handling that type of parameter input so I'll use the def keyword once again and then we'll say multiple if I could spell multiple and underscore items that's what I'm calling this function and now it's going to receive an amount of parameters essentially arguments that we don't know these are often abbreviated as args even though in the definition they should be referred to as parameters what we want to do when we don't know how many we're going to receive is start with an asterisk and then I'll use the word args here to represent the arguments that will be passed in now inside of the function I'm going to print args so we can see what we get I'm also going to print the type of the args so we can also see what type those args are and how they're represented in the code block of the function because that would be important to know for you so now when I call the function I will say multiple items and I'll pass in Dave and John and let's pass in Sarah okay so now let's go ahead and run the code we're calling the function here on line 23 and we should get two lines of output we're printing the args and then what type they are here so let's run the code notice we get the args right here and it looks like a tuple and sure enough that's what type it is so if we have an unknown amount of arguments that will be passed into our function we can Define the parameters here we could use any word we want I'm just representing them as args which is fairly common but we want to start with one asterisk here and that will make the data inside the function a tuple and then of course we can work with it as we learned about tuples but notice these arguments that are passed in here we just have values and represented in the parameter area here inside the definition they don't have names like before we had number 1 and num2 and we could refer to them by name inside of the functions code block so what if we have a function that has again multiple unknown items that will be passed in when we're defining it but we want to use actually keyword arguments so I'll Define another function here and I'll just abbreviate this as mult and then I'll say named items and here we'll start with two asterisks and now you'll often see this word it's a weird word it's quarks which stands for keyword arguments once again you could use any word here but this is what you would typically see so that's why I'm using this and it stands for keyword arguments once again in the function definition it's representing the arguments and we actually refer to that in the definition as parameters so now inside this definition I'm going to print the quarks and then I'm also going to print the type of the quarks so now let's go ahead and call this and I'm going to use this same line of code here I'll just switch the function name so we have a different function call so instead of multiple items this will be our malt named items so underscore named underscore items there we go so now we're calling this function and we'll run the code and I got an error and that's because I forgot to actually name the items here so let's do this differently instead of Dave John and Sarah which won't make as much sense let's go first equals Dave and then last equals gray so now we have actually two named arguments and that's what I forgot to do when I called this I was in too much of a hurry so these will be represented in the function as first and last so let's go ahead and run our python code and so now of course here we have our Tuple output above that I left in but now we have a dictionary and that's what we got when we printed the quarks here so we have a dictionary with first and last and you can see it is type dictionary and then we could work with this data as a dictionary and we learned about dictionaries in a previous lesson as well I've got Visual Studio code open and a folder over here in the file tree for lesson 10. we're going to not only learn about recursion today but also review a few Concepts we've covered in previous lessons and once again refactor our rock paper scissors game so recursion happens in Python when a function calls itself so that would be a recursive function so let's get started today by creating a file in the file tree and we'll name this file recursion dot Pi okay now I'm going to add a function here that will be a recursive function so I'll start with the def keyword I'm going to call this function add underscore one it's going to have one parameter and that will be a number so I'll just represent that with num so when we call it with the argument we pass in it will be a number and then inside the function I'm going to say if num is greater than or equal to the number nine then we're going to return so this will end the function when the return keyword starts here so it will not go any further in the function then we'll say num plus one but after that I want to create a new variable called total and have it be equal to num plus one so this will only be created if the number is less than nine and now I'm going to print the total and then after all of this again this only happens if the number is less than nine I'm going to once again return and I'm going to call the add one function and pass in the total value so this is the recursive call to the function it calls itself here on line 9. now notice we're returning that and we're passing in the new Total so it will continue to call itself until it is greater than or equal to 9 essentially and that's when it will just return the number plus 1 here so now of course this is just the definition the file is not calling the function yet so we need to call the function to see how it works let's do that with add underscore one and let's pass in the number zero so I'll save the file with control s and I noticed it scrolled up on me so I'm going to add a couple of lines so now when I save it will not scroll up there we go and now drop here and choose run python file and notice we get the numbers one through nine and you may be thinking why didn't we get the number 10 because we passed in 9 to the function and that is when it went here but notice there is no print statement here inside the if so we're not printing the number 10. the only way we might be able to do that would be to return a value from our function here so we could say my new Total is equal to add 1 and pass in zero and then when the complete recursive calls are all finished then we will print my new Total and now here on line 15 is where the number 10 would be printed so let's run our code again we can see we now get the number 10 but just one through nine are printed here with line 9 and the number 10 is printed here at line 15. and this makes it important to note this return keyword because if we forget and leave that out with our recursive call everything will go ahead and continue but we will not get a value returned to my new Total so let's go ahead and save this and I'll show what happens we run the code again and now instead of the number 10 we get none because we were not returning this recursive call so we want to make sure we do that and by the way none is a special value in Python it's not true or false it's just none but let's go ahead and put the return keyword back in here so we can get a value out of our recursive function so now when I save and run the code we once again have the a number 10. now it's worth noting that you could use a loop to achieve this same result and that would be a good practice exercise for you go ahead and try to create a loop instead of a recursive call and you could do that inside of a function that would have the same output that we have here however recursion is a mathematical concept and sometimes it's just necessary and overall I think it's important that you can recognize recursion as a beginner so if you are reading someone else's code and you see that the function calls itself you'll know that that is recursion now before we move on to refactor our rock paper scissors game one more time I want to create another file in the file tree and let's just call this file example dot Pi because I want to review a couple of things we have covered in the past to add a little more clarity here so we're going to talk about while loops and how they evaluate the true or false condition just a little so I'm going to set value here equal to to true and then after that I'm going to say while value and we can use double equal signs to say true but most of the time you will just see while value and it implies that while value is true or while value exists which is something we're going to talk about so now I'm going to print the value and then after this I'm going to set the value equal to false so this is what we would expect from this Loop it would print true one time and then the value is changed to false and then when it comes up here for the second iteration when it wants to go back through the loop it will see that value is now false and the loop will exit so let's save this and see if that's what we get for our output yes we get true one time here in the output now it's also worth noting that we could set value equal to zero and it would evaluate as false 0 is considered false so we run the code again and we get true one time and it also exits but note what I said before about value so I said it doesn't really just have to evaluate to true it can be saying while value exists and that is because we could set value equal to a string like y say our user says they want to play Rock Paper Scissors again and so that input is y for yes and then it still exists so this will evaluate the same as true so now if I run the code we're going to get y one time instead of true because this evaluated as true if we set this to zero or false here we wouldn't even get the one print line that we are right now I'm going to make this into a slightly larger example now so I'll say count equals zero and we'll still have our while value here and then let me start out with count plus equals one so instantly we'll increment the count variable by one so now it is equal to one the first time through the loop after that instead of print value let's print the count and then after that let's have an if statement I'll say if the count is equal to 5 then we're going to break out of the loop but then we can also have an else and inside the else I'm going to set the value equal to 0 and then I'm going to use continue and I want to highlight this because I had a question about this and the question was when using the keyword continue is the loop still evaluated here at the top does it check the while value part and that answer is yes it's going to check the value every time to evaluate whether the loop should execute again or not so let's think about what this Loop does before we run the code and we're going to increment count by one and print the count so we'll have one as our output but so far says if count equals five well it doesn't it equals one so we'll go down to the else and then here we're setting a value equal to zero now that's what we're evaluating here on line four does value exist or is it true and when it has zero it does exist but it's not true zero is equal to false so that should end the loop so the continue will just bring it back up here for the evaluation it will be evaluated and it will say no we're not going through the loop again so all we should get is a print count of one let's go ahead and run our code and see if that's what we get that is what we get just the one so what we're learning here is that yes using the continue keyword does cause an evaluation before the loop executes again now I've got the rock paper scissors code pulled up from our previous lessons and we've refactored it a couple of times I've created did a new file named rps3 dot pi as this would be the third time so if you've got that from a previous lesson bring it up if not you can get this code from the course resources so I'll leave that in there however I'm going to refactor it now so the starter code for this the last time we refactored I believe was lesson 8 which is also in the course resources the code in this lesson lesson 10 will be the refactored code so you'll find the finish code in lesson 10. okay now moving on we have learned several things that it could improve our game at this point so one of those things is functions so let's make our game a function and we're going to include everything after the Imports here at the top so we'll use the def keyword and let's call this play underscore RPS and then we have a colon so everything else needs to be indented to be part of the function so I'm going to start selecting here on line seven now scroll all the way down to the bottom except for this system exit here so I'll press the shift key and click and it highlights everything and then I'm going to tab in so now it should make all of that code part of the function so now everything is in the function except that system exit that we have right here and we'll probably end up moving it in the function too but we don't have to for now now let's go ahead and add the function call here at the bottom that we're going to need so it was play underscore RPS and we would need to call that of course to execute the function to see our Gameplay at all so we'll save that much and we now have a function for our rock paper scissors game now the next thing we can do is actually remove the while loop and we can use recursion in our function instead so let's let's do that by deleting the play again equals true and the while play again that starts the while loop but after we delete these now everything is indented too far underneath here it thinks it's part of the class RPS that we created up here so we need to select everything from line 14 once again scroll down to the bottom here and I'll click shift or press shift and click and then we're going to press shift and the Tab Key to tab reverse and go back out just a little bit so now everything is once again part of the function and it doesn't consider it part of our RPS class here that we start the function with either so just verify that your indentation is correct and python will read that correctly now we need to make some changes as you might have noticed I have a red squiggly line here where the continue keyword is that was applying to a loop but let's start at the top and work our way down one thing we still haven't fixed in our game is the player choice value if the input from a user was something that would cause an error as we cast to an integer here on line 16 we're not handling that at this point but we can do that so let's put an if statement underneath the input here where we get our player choice value and let's say if player choice and then we'll say not in and let's create a simple list because we know we're only expecting a one two or three and all user input is string so here we have not in one two or three in our list so we're making sure the player choice is one of those but if it's not let's execute some code in the if block here so we'll say print and now we're just going to take this message that we have in the system exit below because we will be removing this let's put this in you must enter a one two or three and after that this is a good time to use a recursive function call so we will return and we'll say play underscore RPS and that's all we need so we're calling the function here again and it will go back to the top and it will once again ask for the input of a one two or three and with that completed we can delete the other if statement we had here pre previously now note I've already pressed alt Z so visual studio code will wrap my code down I expected both of these lines to look like this first one however it's doing something a little weird here I've noticed when I delete this spacing and bring it back to look like the other one and then I save and auto formats it back this way so just note that if you see this in your code it is just happening automatically by Visual Studio code and I'm not entirely sure why but it's essentially all one line just like this line above is now let's scroll down and fix the area where we have the continue problem here but we're going to start here on line 41 where we have play again because remember we're no longer evaluating play again for the loop at the top I'm going to start though with a print statement and I'm going to print and here is where I'm going to ask the play again statement so I'll just copy that paste it in there and finish that print statement and then of course we can remove that same phrase from the print statement here but I want to have this input in a while loop and again this is correcting the input right now if we get a y for yes then it will play again and any other input not just a cube but any other input will quit the game but we want to limit the accurate choices to just Y and Q so here I'm just going to say while true so we're just looking for a True Value to begin the loop once again and then we'll have our play again I guess I don't need that extra line I could just tab this in so then we'll have play again ask for the input I'll get rid of one of these extra new line characters at the end though and now let's evaluate play again so we'll say if play again dot lower then not in and let's create another list and we'll just have y and Q as the two items in our list and then inside the block for the if statement I'll just use the continue keyword so if it's not y or Q it's just going to start the loop again and ask for y or Q so we're just asking our users to please specifically enter y or q and then our else will just issue the break statement so if they do enter a y or Q the loop stops now here the if statement below was checking for a y and we still want that so the loop is stopped they've entered a y and now this is a good place to put our recursive call to the function once again so play RPS because they want to play again if not we're going to still print the thank you for plane but we no longer have to evaluate play again for a loop so let's just take our system exit line right here here Ctrl X to cut it and Ctrl V to paste it over that line on 55 that was setting the play again value and now rock paper scissors should be ready to play and it is a recursive function so let's give it a shot and see if everything works as we expect it to so I'll enter one for rock and hey we won that's great do I want to play again yes let's play again let me enter something else like an a now that would have caused possibly an error before but now it just goes back and says we need to enter a one two or three how about a five nope one two or three so I'll enter two and now python wins so why for yes to quit or I mean to continue playing or Q to quit and let's enter a four instead no it just asks us the same question again so we're in that Loop until we get a y or a q we did y once already let's enter a Q and we quit so our game is we're working as expected you've now applied a recursive function to the rock paper scissors game I've got vs code open you can see I have a lesson 11 folder open over here currently no files let's go ahead and create a new python file and we'll call this scope dot Pi there are different types of scope and the first one we want to learn about is the global scope so when I Define a variable like name and set it equal to Dave this is in the global scope because this will be available to everything in this file so if I save this and then I go ahead and print name of course it's available so let's add something else here to compare to the global scope so now I'll Define a function and I'll call this greeting and then greeting will accept a name parameter as well and now inside of this function I will print name now of course this parameter has the same name but it's not referring to the same thing this is a parameter for the function so it's going to print print whatever I pass in but let's go ahead and Define something else like well instead of name actually let me think about this differently let's first prove that we can print this name value because this is in the global scope but being in the global scope it's also available inside of this function but this function has a local scope so let's go ahead and do this first I'll save this and then of course we need to call our greeting function for it to run and let's put an extra space because it likes to scroll up when I save so we'll go ahead and save that and now I'm going to come over here to the drop down menu and choose run python file and we've got this here at the bottom and it prints Dave so it printed the value of name now we defined name in the global scope like I said the function has a local scope as well so we'll look at that but right now I want to move this over to the right so I'm going to go to view and from view I'm going to go to appearance and then from appearance I'm going to go to panel position and choose right instead of bottom so now we can see our output here on the right and I've got Dave as the output there when we first ran our code so now let me Define another variable but I'll Define it inside of the function so I'm going to say color equals blue but now if I try to print that outside of the function I'm going to try to print color look vs code gives it a squiggly Mark and if I Mouse over color it says color is not defined that's because color is in the local scope of the function and it's only available here if I want to print color inside of the function BS code is going to have no problem with that because it knows what color is inside of this local scope but out here outside of the function in the global scope it does not know what color is so let's go ahead and remove move this print color in the global scope because that would cause an error but if we run the function now we should see the value of color and the value of name so I'll run the code again and we get blue and Dave and that's because this function inside of its local scope can access the global scope and get the value of name and it also has access to its own local scope and it gets the value of color now let me go back to what I was going to do and I'll pass in a parameter here for the function and I could name it the same thing as name or I could name it something else like first name and it would be the parameter and so I'll do that just to eliminate some confusion so we'll print first name now so when we call this we would be calling it with a name like John and then of course we could still print name inside of here and the local scope of the function should still be able to access the value of name but it can also get a value from the parameter name so let's go ahead and do this first and we'll run the code and now we get blue Dave John but what if this had the same name so now I'm getting back to where I first started and now name is a parameter so I can remove one of these prints because we're just doubling that up and so this does not represent the value that's in the global scope name now represents the parameter that the function is receiving so now if we run the code we get blue and John because we passed in John so when dealing with variables I hope this eliminates any confusion where we can see there is a local scope inside of functions and yet there is a global scope that's available outside of functions and outside of anything else that the value may be in so if it's defined outside of anything else it's in the global scope which can be accessed inside of functions but if we Define it inside of a function where the local scope is it cannot be accessed outside of the functions now this not only applies to variable names but it also applies to functions so let me create another function and I will call this another and that's just because I couldn't think of anything else and inside of another we're going to go ahead and call our greeting function and here I'll pass in Dave so now we'll need to call another down here at the bottom so we'll put the another call at the very bottom of the file and now let's run this code again remember we're already running it here with John and then we're going to run it here and it doesn't need to receive a parameter it's just going to run greeting with Dave so now let's run the code and you can see we get blue John blue Dave so we can call one function inside of the local scope of another function and that's because this function greeting was defined in the global scope so it's available to be called inside of the local scope of another function so as you might guess we can also Define functions inside of other functions so let's go ahead and do that I will control X to remove greeting here and put it inside of another before we call it and now it doesn't like the definite edition of color being blue right here and it doesn't like the call to greeting because this is in the global scope and now the function is being defined inside of the local scope of another so we could only call this function inside of this another function but the reason it doesn't like the definition of blue is because these are not indented properly for the definition of greetings so let's just tab that over because remember these spaces in Python do matter so as we tab this over this indicates the local scope of greeting so what if we put color inside of the another scope and now it should still be accessible inside of greeting because this is the parent scope so what we have here is a nested function and the parent function is another it's defined in the global scope and then we're defining the color blue inside of the local scope of another and then we're defining the function greeting which makes the function greeting only available inside of the local scope of another so it's not available out here and even if we put it after our function definition here it's still going to have a problem because it's not defined in the global scope so let's remove that however I'll get rid of some of these spaces here too however inside of another we can call gradients so there is no problem here so let's go ahead and save this code and we'll run this code and see what we get and we get blue and Dave and that's because we defined the color here inside of the another local scope then we Define the function and greeting inside of the another local scope and then we called greeting and greeting prints the color and prints the name so understanding scope applies both to variables and to functions and you can have nested function definitions if you're wondering why you would actually have a nested function well that could be because you're only going to use the function inside of the other function and therefore it doesn't need to be defined outside of the function now if we did Define greeting outside of the function as we did earlier you saw that I could call greeting inside of another function still because it was in the global scope and then the other function another still has access to that gradient function so it's a decision at design time really where you define your function but if it's only going to be useful inside of this function you can just Define it inside of here because there's something called polluting the global scope and you really don't want to put anything in the global scope that you really don't have to because that can make things more confusing later on especially if you're working on a team with other developers so we try to keep the global scope as unpolluted or with as few things as possible and we try to put everything else inside of functions or later we'll learn about classes and objects and so on but that is important to understand about scope so we have a global scope and the local scope and it applies both to variables and to functions now one more thing we haven't looked at is what if we want to modify the assignment of a variable inside of a function but the variable was initially defined in the global scope so let's put a another variable out here and I'll just call this count and set it equal to one so this is a global variable and now if I try to Define count inside the function so I'll say count equal to 2 and then let's go ahead and print count right here inside of the parent function so we'll print count let's see what we get as far as the output goes so I'm going to go ahead and run the code and we get two that's because we really created another variable here we didn't reassign count that's because we can't reassign that that easily so we need to use the global keyword but notice if we do what happens is we have an error here we can't just do this all in one line so Global count so another way I could of course demonstrate this instead of saying count equals 2 is we're trying to take the previous value so let's say count plus equals one and now let's see what value we get and this should show that I'm not using the value from count because if I use this Global value then it would be equal to 2 correct let's see what we get and we do get an error says Unbound local error cannot access local variable count where it's not associated with a value that's because it doesn't currently have a value there so we can't really do that now of course we said we can go ahead and access the value of count if we're not trying to modify it there is no problem so if I run the code now we get one that's because it gets the value from the global variable but trying to modify this inside of the function when it's already defined here but we didn't give it a definition because this would be a new variable essentially if we were just trying to assign another number to it like one or previously I had two this is just creating another variable named count in the local scope and I know that can sound confusing but that's what it is doing so really what we need to do is use the global keyword and now we'll say Global count equals plus equals one so we're adding one to that but we can't do that all on the same line so then we need to go ahead and just say Global count on one line and then say count plus equals one now it's going to go ahead and be happy about that so now we'll run the code again and you can see we get 2 because it added 1 to the value of the global count but we had to use that keyword before we could modify the global value so I know that may be a little difficult to wrap your head around at first but what you need to understand is that if you just assign count inside of this another function's local scope you're essentially creating a new variable named count and you're assigning a value to it now if you try to modify count because it already exists so if we didn't have this Global here and we were just trying to modify that is when we got the error because yes it knows count exists and you're trying to modify it before or you've used the global keywords so now by using Global count and then modifying it everything was okay now in nested functions the same concept exists and especially if we're trying to modify a value that was defined in a parent function inside of a nested function like color equals blue well then there's another keyword we need to use and that is non-local so we'll say non-local color and that tells our greeting function that it's going to be using the color from the parent function and from there we can assign color equal to red and it should be okay but of course this looks just like reassignment so if we didn't have this we would essentially once again be creating a new color variable vs code helps us see this because we're not printing color like we are here inside of another so look at how this is now grayed out because it knows we're not using the value of this variable and this is a different variable at this point then color is inside of the greeting but once we uncomment our non-local color then vs code knows we're using this color variable and then we're just reassigning it here so I'll once again save and run the code just so we can see everything and we have two red and Dave okay let's close our output window for now and in the file tree let's go ahead and create a new file I'm going to call this rps4 dot Pi now I'm just going to pull in the rock paper scissors code from the previous lesson where we had a file named rps3 so if you have that you may want to open that up I'm just going to paste this in so we have that same code to work with so now at the very top of the file let's go ahead and create one Global variable and I'll call this game underscore count and set it equal to zero now in a future modification we will remove the global variable once again because I said it's important to not use Global variables where they're not needed and we will be able to remove this in a future iteration of this game but for now we're going to put a global variable here called game underscore count and set it equal to zero now let's scroll down to once we get past the decision tree here but before the play again in our code get a little bit of space and then we'll tab in to line it up and let's go ahead and say Global game underscore count so now we're telling the function we're going to work with and modify that game Count variable that's in the global scope inside of the local scope of the function and we'll set game count and then we'll say plus equals one so we're counting how many games we've played and then before we ask play again we can print and we'll start with a slash in for a new line and then we'll say game count give a colon and then of course we have our quote here and then we'll just say plus and we'll make sure this is a string now as we print this out or we would get an error so we will use our string here to convert this to a string Str and then we'll put the game count so this should output how many times we've played the game and even though we run the function again and again it won't lose the count because that counts not stored in the function it's stored in the global scope outside of the function now one other thing we could apply that we have learned today is a nested function so let's do that with this game winner decision here so I'm going to tab in and then say Def and I'll call this decide wide underscore winner as a function it's going to receive the player as a param and the computer as a param now inside of the function I'll need to tab all of this over so I'll highlight all of this and press tab then we're going to change this a little bit because instead of the print here I'm going to select print the first parentheses and then I'm going to go ahead and press Ctrl D to select the next the next the next and the next and I'm going to change this to the keyword return because it's a function so then likewise I'm going to select the last quotation and the closing parentheses Ctrl D again as I select all of those then just a right arrow to make sure I'm at the end and then backspace once and we've changed all of those at once and now we have a decide winner function that is going to return the appropriate response based on the decision but now we need to add a couple of more lines but because we haven't called this function now decide winner is our nested function that's inside of our function up here called play RPS so underneath decide winner now we're going to go ahead and say game result which is a new function is going to equal decide winner and we're going to pass in the values we have for player and computer so it's important to know with the parameters even though I named those parameters the same so I wouldn't have to rename all of these they could be named differently because here these hold values player and computer from above however here player and computer are params inside of the function they represent whatever value we pass into that function so we're calling decide winner and we're storing whatever is returned inside of game result so then we need to go ahead and print game underscore result to see that output okay with these changes in place let's go ahead and run our code by choosing run python file and now it's asking us to play the game I'm going to choose Rock and it says python wins our game count is one do we want to play again sure so why let's go ahead and choose paper and i1 so game count is two play again and you can see how the game count is working we'll choose three and hey we won again so game count is three so that's working as expected everything else is working just like it was before but we created a nested function inside of our game as well so I hope today's lesson has helped you understand a bit more more about global scope and then local scope as we see inside a function I've got vs code open and you can see I have a new empty folder named Lesson 12 and that's where you will find this lesson in the course resources let's create a new file named closure dot Pi c-o-c-l-o-s-u-r-e dot Pi p y so now we've got our new file and let's talk about closures for just a moment because closures are often a difficult concept for beginners to understand but I think I can provide a simple example in this lesson that will help you always remember what a closure is and it's important to understand scope first and that was covered in the previous lesson in this series so if you found this video but you haven't learned about scope yet I suggest going to the previous video in this playlist and learning about scope first let's define what closure is I'll just paste this definition in and it looks like I need to put another comment before the second line and I'll even press alt Z to wrap this down and it looks like I should just fit this on the second line as well so control X to cut Ctrl V to paste and there we go so let me scroll this back up there we go closure is a function of having access to the scope of its parents function after the parent function has returned that sounds complicated at first but if we break this down we're talking about a parent function so that means you should know we're going to have a nested function defined and we learned about those in the previous lesson with scope and then the nested function is going to have access to the scope of its parent function and of course let's go ahead and create an example so I'm going to come down one line and use the def keyword and then let's just call this parent underscore function and this will be our function it's going to receive one param to start out with and that will be a person and now we can Define the body of the function so let's say we have coins and this coins is equal to three then just the number three now let's define a nested function and here I'm going to use the def keyword again and call this play underscore game and now inside of our nested function we're going to use that coins variable from the parent function so we'll use non-local as we learned about in the scope lesson and say coins so we're going to use that and we'll set the coins equal to minus one it's essentially equal to itself minus 1. we learned about how to do that so we don't have to say coins equals coins minus one we can just put a negative and then the equal sign and it will accomplish the same thing so we're subtracting 1 from coins at this point essentially we had to put a coin in the game to play the game and now let's put say some logic here with an if statement so I'll say if coins is greater than one now we can go ahead and print something for our output so let's print and we'll start with a new line so that's a slash in let's give it a well no we don't need a space yet but we will so let's give it a plus here but but the person's name so we're just starting out on a new line with a person's name that's passed in now we'll have a space the word has and then another space and after that we'll put another plus and now remember to use coins it's not a string so we need to wrap it here in our Constructor for string and then we'll just pass in coins whatever that value is and it should be greater than one at this point and then we'll put Plus and now another space and we'll say coin space left so we're just making a statement here if we passed in my name and then it would call play game which it's not calling yet we're just defining play game at this point but if we got to this point here in our if statement it would say Dave has two coins left because I started with three so now let's put an else if here and our LF is essentially what an else if is in Python we'll say coins equals one and the reason we're doing this for one is because then we don't want to say coins left we just want to say coin left so let's copy this with Ctrl C paste it here as well and now let's just change this to coin left so now this would be Dave has one coin left because this will only happen if coins is equal to one and finally let's put an else here so this would be anything else and essentially if it was greater than 1 the first happened if it's equal to 1 the second happens so here our else would be zero or anything less than one essentially and now I'll just paste this again but I'm going to change the message so instead of has whatever coins left now I'm going to say is out of coins because at that point we shouldn't really be able to play the game anymore we would be out of coins now as just an example function we're not really tying a game to this we're just going to get this output printed to the console but after we're finished here defining our play game function then we need to come back to the parent function essentially and instead of returning any value we're going to return the play underscore game function notice we're not calling it into action by putting the parentheses after it we're just returning this nested function play game when we call the parent function so now that we've completed our parent function let's go ahead and use it and I'm going to say Tommy here for our first variable and as a parent function let's say his father gives him three coins to go to the arcade so here we'll just pass in Tommy's name because that's what the function needs to receive we're already defining the coins value inside the function here and then we're going to be able to call Tommy because Tommy is a function because we're returning the play game function here when we call the parent function and it has the value of Tommy for the person's name now notice we're not changing the value of person and that's why we don't have to use the non-local coins here like we did with coins essentially the non-local keyword with coins but we are changing the value of coins and that's why we must use the non-local keyword with coins but we don't have to use it with person because Tommy's value stays the same or whoever's name we pass in as a matter of fact let's say Tommy has a sister so we'll just copy this down I'm going to highlight Tommy change this to Jenny which would be his sister's name and let's say their Dad gives both of them three tokens to go to the arcade and play games with so every time we call one of them into action is when they're going to play a game so let's copy Tommy down he's going to play the game a couple of times and then we'll have Jenny play the game so let's save all of this now and notice we're calling our function Tommy twice and Jenny wants let's check the output I'm also going to press Ctrl B to hide the file tree for now just so we can have some extra room here when we see the output we'll go to our drop menu run the python file and it says Tommy has two coins left then Tommy has one coin left because he played twice then Jenny still has two coins left so I'm going to move this over to the right all also we'll go to view appearance and now we should be able to go to panel position and then I'll choose right so it's not at the bottom so we can see our code just a little better but when we did this we called Tommy twice and he used one coin so we had two left then he used another coin he had one left but Jenny was able to go ahead and play once and she still has two coins left so you can see how we're keeping different values in coins inside of the scope of the parent function that are play game function can go ahead and access the value of even when we change that value that's what a closure is and the closure is created when the parent function returns so when we return this then the closure is created and play game the nested function will always have access to the variable value that is in the parent function and it's not always three it can change that value as we're access assessing it and changing it right here so let's go back to our definition and see if it makes a little more sense so a closure is a function having access to the scope of its parent so play game as access to the scope of the parent function even after that parent function has returned and that's what's necessary here so the parent function Returns the play game function and then the play game function has access to the scope of that parent function every time we call play game and it's not always the same as we noted here Tommy and his sister have different values for how many coins they have left and if we called Tommy again he's going to run out of coins so let's save and run this code once again and now Tommy's out of coins Jenny still has two coins left so now just to change our example a little bit let's go ahead and comment out coins here and let's have our parent function receive a specific number of coins as well so as a second param we're going to pass in the coins so that way the parent can award the children different amounts of coins so now that we have changed that the coins is still inside of the scope of the parent function it's a param of the parent function at this point so I just wanted to show essentially how we could move coins up here as a param in the same concept still applies so now when we call these functions Tommy well he did okay but he didn't do all of his chores so he just gets three coins but let's say Jenny did all of her chores and she gets five coins for the arcade so let's save this let's go ahead and rerun our code and now Tommy has two coins one coin Jenny has four coins left after she uses one and Tommy is out of coins so the same applies to a param as if we had defined the variable inside of the parent function here so if you remember in our scope lesson I had said that it's really a good idea to avoid Global variables when possible and notice we didn't have to create a global variable here so really creating a nested function and using closure accessing a value from the parent function is one good way to avoid creating Global variables but when you need to access a variable from a parent still so this just creates another level so now let's look at an example with our rock paper scissors game that we have been adding to throughout these lessons so it was changed in the last lesson so I'm going to start with the code from the previous lesson of where we left off our rock paper scissors game so I'll open up the file tree and this will be the fifth version so I'm going to call this rps5 dot pi and I'm going to paste in the code from the last lesson where we had modified this but if you remember we created a global variable here called game count and we were counting the number number of games we play but now we should be able to change this to where we're not going to use a global variable and the first step is going to be to wrap our play RPS function inside of a parent function and we'll do that with the game Count here too so above this I'll just call this RPS instead of play RPS and now we have essentially wrapped this but we need to change our indentation because that's important in Python so I'm going to indent the game Count here and this will be inside of the scope of the RPS function and then let's select everything else so on my line 9 all the way down to the bottom here I'm going to press shift and click and then I'm just going to tab over but really I didn't need to tab this play RPS we can go ahead and change that because it's not going to be play RPS anymore notice when I backspaced it got this squiggly line from vs code because now play RPS is not in the Global scope where we can call it it's a nested function so we're going to be calling a function called RPS when we actually do call everything into action let's scroll back to the top because we need to make a few more changes besides the game Count now let's count how many games the player wins and how many games python wins so I'll also create a variable here called player wins set that equal to zero and one called python underscore wins and set that equal to zero now let's remove this extra line but what we're going to need to do is pull these variable values into the play RPS function because we will be modifying these by adding to this number we have of course starting with zero so we will increment as python wins or as the player wins and of course for each game with game count so what we need to do here is go ahead and use our non-local and then say player underscore wins and we could say non-local and say python underscore wins now we could do this with game Count here as well but if you remember we had this lower in our code so let's find that I'm going to use control F and then just type game underscore account to see where else it shows up in the code and we can see it's on line 52 so now that I'm here I can't use this Global keyword anymore because game count is not a global variable it's inside the scope of the parent function RPS so we're also going to use the non-local keyword here for game count as well now let's scroll back up and remember we already had a nested function and that's okay so now we have a nested function inside of a nested function it just creates another layer but when we do that and we need to access our player wins or our python wins variable inside of our decide winner function that is nested inside of our play our RPS function you might guess that we're also going to have to use the non-local keyword here to pass it down One More Level so we can modify these values inside of decide winner and then still access those values outside of decide winner when we need to so I'm going to say non-local player wins and non-local python underscore wins here as well so again a nested function inside of a nested function now if we win it says you win or the player wins we'll say player underscore wins and then we'll say plus equals one so we're incrementing by one now I'm just going to copy this because clearly the same output is here as well and it's also here now we don't really need to count the tie games so we won't put anything else there but in our else where python wins we can go ahead and paste one more time but we'll just change this now to python under score wins and now we're adding one if python wins to this variable so now that we've changed those we just need to Output the result also so let's scroll down just a little bit and here we find our output for game count and then of course we're using the string Constructor around game count because it's a number so we can output it this way I'm just going to shift alt and the down arrow to copy that down and now we'll count the player wins right here so I'll say player wins and let's change this to our player wins value so player underscore wins and now shift alt in the down arrow one more time we'll change player to python there and we'll change player to python here also and now you would think we are finished but there's one important thing that we have not done yet and that's create the return for our RPS which needs to return our play RPS so remember our parent function here RPS needs to return the play RPS function so now I'll scroll almost all the way to the bottom and at the very end of our function here this is where we'll need to go ahead and return the play RPS and there we go so return play underscore RPS remember without the parentheses we're not calling the function into action right there we're just returning the function so now let's define a new variable here called play and we'll set this equal to our RPS function and now play is going to hold the play RPS function so now we'll call that into action and now our game will start so let's go ahead and play our game I'll go to the drop menu and choose run python file is ready for rock paper or scissors I'll choose Rock and it says a tie game so why to play again I'll choose Rock again another tie so why to play again and another one and let's three ties in a row I cannot win right now literally let's see and hey we finally won on the fourth game notice we have player wins one but the game counts four I also notice we have a slash here with python wins so I may have something in the code that I didn't want let's go back and check that out and yes we didn't get our n in there or I accidentally deleted it that stands for new line so let's put that back in now let's run the code again and we're ready to quit or play again so I'll say play again with the Y and now we're ready for rock paper scissors I think I ran the code again when I actually didn't quit before and that's what happens so let's quit because it's running the old version of the code notice the slash is still there so we quit now let's go ahead and run that code again by pressing play up here and I'm going to choose Rock and python Wins Game count one player wins zero python wins one let's Play One More Time see if we can even it up and we want so game counts two player wins python wins you can see everything is counting as it should and we've implemented closure to keep track of these game counts and the wins without actually creating a global variable at all and you also learned how to use closure at two different levels there because we not only had one nested function then we had a nested function inside of the other nested function I've got vs code open you can see in the file tree I have a lesson 13 folder let's create a new file inside this folder called f underscore strings dot Pi now as we talk about F strings we're going to learn what we have been doing with strings and what we could do to format strings that might be better so what I want to do first is just paste in an example of something from the previous tutorial and we'll look at how this is put together so we have a variable that says person then we've got a variable of coins and you can see we concatenate everything in this string we're using four plus symbols to create one string it starts with the new line character as we see the slash n then we have the value of person and each time we insert a value we essentially have to wrap it in plus symbols to concatenate it to the rest of the values of the string where we see has right here inside of quotes and and then at the end we have coins left inside of quotes and now today we're going to learn a better way to do this but before we get to F strings let's cover some ways that used to be used to format strings that could still be used but F strings are potentially better however it's good to know the older ways because you may see those in cold code examples that were created previously so let's look at another example of this same string but we're going to use the percent s method of formatting the string so I'll start out with let's create a message first and then we'll just print the message so I'll say message equals then I'll start with a quote and we can put in our new line character and then we're going to put in a percent s and we don't really need the space but I want you to see the separation of these two as they're different characters so let me remove that space But the percent s marks where we're going to put the person value after that we'll say has and then percent s again to Mark where we're going to put the coins value and then we'll say coins left so that's a little easier to read so far but then we need to put another percent and then parentheses and at the end we'll put in person and coins now what this does is it inserts person where the first percent s is and inserts coin where the second is and you need to keep these in order if we flip them around it would Insert Coins first so after this let's just print the message and we'll save our file and I'll go to the drop menu here and choose run python file and you see we've got Dave has three coins left and again Dave has three coins left so two different ways of creating the same string we had been concatenating with the plus symbol but this appears to be just a little bit easier than what we've been doing but again this is an older way of doing this and there are newer ways so we'll continue to move forward and cover those first I want to move this to the right once again as you've seen me do before so go to the view menu in vs code appearance and then align panel and no panel position there we go and move that to the right so we'll just see our output over here I'm also going to press Ctrl and the letter B to hide the file tree so we can see more of our code here on the left and then eventually alt and the letter Z so anytime our code is longer and running off the screen still it will wrap down instead to this next line so now let's look at another newer method than using the percent s and that is to use the format method so I'm going to highlight our last example press Ctrl C to copy and then just underneath Ctrl V to paste this I'm going to change this string to use the format method approach and so now we're still going to start with the slash in for a new line but then we'll no longer have a percent s here instead we're going to put in the curly brace and I'll just delete that percent s so so now you see the slash in and then the opening and closing curly brace or brackets some people call them curly braces some call them curly brackets either way and then I put a space here just so you can see the separation once again because this is what we're talking about but I really don't want a space at the beginning so I'll remove it I just want you to see the separation of the new line character versus the opening and closing brackets once again we use the same thing here instead of the next percent s so we have these opening and closing curly brackets indicating where we're going to insert our values and then at the end here we won't use the percent either instead we'll use dot notation to chain onto the end of the string value we'll chain dot format which calls this method and then we'll pass in person and coins to the format method so let's save this and run our code once again and now we see the same output again so another way of achieving the same format of our string but now we're using the format method however there are some other things we can do with this format method so let me once again highlight both of these this time instead of Ctrl C I'll tell you another way to do this and that is to press shift alt and the down arrow and it will make a copy right underneath and then I'll just press enter one time to create that space now we're still going to use the format method but we can put in index numbers to say which position of the value is going in so I'm going to flip these around and I'm going to put 1 here instead of 0 and I'll put 0 here but that means I'll want to flip these values as well so it will start with a 0 and then it will end with the one so we'll want to put person here where the 1 is because it has the index of one and we'll put coins where the zero is because it has the index of zero so if we save run our code again we get the same output but now we can essentially not track the order of these if we want to flip those around and then insert the values by which number they are as far as the index inside of the format method we can do that remember the index starts with zero so we refer to coins as 0 and person as one but there's even more we can do with the format method so I'll scroll up just a little bit I'll highlight this example and once again shift alt and the down arrow to copy it down and now let's refer to these as the names that they have but we're going to have to do something else inside of the format method as well so here I'm going to put person and here I'm going to put coins but now we actually assign these values inside the format method here so I'm going to say coins equals coins and likewise person equals person so now we're setting the values of these parameters essentially or the format method and then it will pull them in here by name so let's save once again run our code and we get the same output again and I can see vs code brought this down to the next line and that's okay you could even have your closing brace on the last line if you want to and we have the opening one here this will still run the same okay before we move on from format let's look at one more example so I'm going to highlight all of this again shift alt and the down arrow move it down and I'll press enter about three times now because I need just a little more space I want to create a dictionary here so I'm going to say player is going to hold our dictionary there we start with curly braces for a dictionary I'm going to Define person inside of the dictionary and I'll just assign person my name Dave and then coins and then I'll give coins a value of three here but this is all inside of a dictionary now we can still refer to person and coins inside of our string but what I'm going to do here is put in and I can get rid of the extra returns here so formats all on the same line again but I can put in the dictionary and I just start it with two asterisks and then put in player and it's going to pull these values in from the dictionary based on what we have assigned the keys here as the person is a key and coins is a key for the values of Dave and three so let's once again run our code and we see the same output once again so a dictionary could actually shorten that up because then we just use two asterisks and the name of the dictionary which is player in this one to pass into the format method and then it pulls those out based on the key names so when we talk about these different ways of formatting strings we have to look at why have we moved on to newer methods I even format is an older method than the F string which is what we're going to learn next and that's what you want to use going forward but when we look back at this percent method let's talk about what works for it and it does work but what doesn't work is this can get complicated quickly so you see percent s everywhere you've got all these percent signs and imagine if you had more values to pass in what if you had 10 values this just gets longer and longer as you pass in the values now as you might guess the same with the format approach here as we pass things in except for the dictionary at least but as we pass things in in it was also getting longer and longer if we had more values to pass in but format gave us a little bit more control here with the index numbers or with the name references than we had with the percent method but we can shorten all of this up and it won't be so verbose if we use f strings so now that we're ready to move on to F strings let me scroll up for some more room and I'll put in a little break so you see it in the source code and know when we have moved on to fstrings and notice my Mandalorian reference this is the way so here we're going to have a message so we'll Define our message once again and then equals and we'll start with the letter F and lowercase is what I usually use and then let's go ahead and put in the new line character and then let's refer to our person which remember was defined above as well before we put it inside of a dictionary here we had actually defined person and coins here at the very top of the file so we're referring to that and after our person we can just say has then coins and that's referring to the coins definition at the top as well and coins left now that's a lot shorter isn't it we're just inserting the values of those variables but we're starting out with the letter F to indicate this is an F string so let's print message and save and now let's run our code once again and we once again see the same output not nearly as verbose we don't have to add anything at the end of the string or insert values into a method we just use the letter F at the beginning and then we insert the values we want inside of curly braces inside the string now I want to highlight the fact that we do not have to necessarily insert these predetermined variable values as well so let's copy this down once again and now instead of coins I'll leave person there but we could pass in an equation like 2 times 5 and this will work so if we run the code now we should see the difference and it says Dave has 10 coins down here at the bottom of our output and I'll copy this once again to show we can actually use methods inside of this as well so in this example I'm going to say person and then dot lower so if you remember our string Methods we learned this should make everything lowercase so Dave should be lowercase now in this new output than if I run us yes Dave is lowercase on the bottom line so you can see we can do things inside of these curly braces besides just passing in a value so let's look at one more example here and remember our player dictionary above where we have player with person and coins as the keys let's come down here and we'll use that so I'm going to copy this down with shift alt and the down arrow and now inside of our curly braces I'm going to do this just a little differently we'll refer to player our dictionary and then we'll use brackets and then we need to put the key inside of quotes so we'll use person now it's important to note that I'm using a double quote out here and then single quotes in here if I had single quotes out here this wouldn't work with single quotes we would get an error so if you wrap your string in double quotes then you can use single quotes inside so here we've got player person and and we could refer to player coins as well but I'll just leave the two point or two times five right there let's go ahead and run the code and once again we have Dave has 10 coins left so you see how we can insert different things inside of these curly braces and it still doesn't make our string much longer not much more verbose if you will which means adding more code we're trying to minimize code and F strings do a great job of that compared to the previous methods of inserting values into Strings now I also want to share that you can pass options into these F strings so I'll put another line here in our code with a comment just saying you can pass formatting options so you'll know what this is an example of let's start out with a variable that is equal to the number 10 and now we'll print an F string and so I'll start with f once again and then I'm going to use a new line character then I'm going to say 2.25 times and I'll insert the number value so times 10 in this case is and now we'll have a bracket here for the result and I'll say 2.25 times num but I want to put some formatting on this so I get a fixed decimal so I'm going to start with a colon and all formatting will start with this to indicate then you're going to say how to format it I'm going to say 0.2 to indicate I want 2 decimals and this F stands for fixed so now I'll go ahead and save this string and we'll run the code once again and we get 2.25 times 10 is 22.5 and remember we wanted two decimals so that's why we see the 0 at the end now this is just one of many examples of how to format and I'm going to show you where to find more of those here in just a minute as well but first I want to highlight that you can also put this in a loop so now let's copy this line down at least I'll just highlight that and shift alt in the down arrow and then I'll press enter a couple of times and I'm going to say 4 num in range and I want to go 1 through 11 so I get 10 numbers if you remember how we covered range now I need to indent this or we'll have that error because remember the indentations in Python are important so we're going to Loop through this so you should see this print several times let me go ahead and remove the new line character because this will allow each line to at least have an output there so it doesn't take up our full screen like this does I can go ahead and put a new line character here at the end of this one so at least we see the separation before our Loop starts so now let's go ahead and run this same code and see what we get and you can see we've got 10 different lines of output here for the numbers 1 through 10. if you remember the range here once we reach 11s when it stops it doesn't put 11 into this loop as well so we've got 2.25 times 1 is 2.25 and it goes all the way through 10 giving us the result of each one now let's look at one more example of this so I can copy this down but then I'm going to change the values so shift alt and the down arrow one more time and now in this one we're going to use the same range I'm going to switch some things around so I'm going to say num then I'm going to say divided by and then we'll have 2.25 is and then we'll go ahead and put what we're calculating here so I'm going to have num divided by and you know what let's change this number I want to do something that always gives us some type of decimal output so I'll just say like 4.52 so let's make it 4.52 here 4.52 there we go now not the letter M there we go so now we need our colon and we'll have a period and then I'm going to have the number 2 but instead of this fixed place I want to have a percent so it's going to put a percent output it's still going to have two decimal points though and that's what we're going to see for our output here I'll go ahead and save this and let's look at the output of this loop as well so now we have 1 divided by 4.52 is 22.12 percent essentially it is 1 would be 22.12 percent of 4.52 as you can see as we get closer to 4 it gets closer to 100 percent and as we go beyond four it's over a hundred percent eventually where 10 divided by 4.52 is over 200 percent so we're getting the output expected and that's kind of showing you how to Loop through and format a string and get those results as you go oh okay I'm on the W3 schools website and I'm on the python string format method which I said was one of the older methods but you can still use the formatting options that I was talking about even if you're using the older format method so this is where they have this current information and I'm going to of course include this link in the course resources and in the description of this video so I'll scroll down here and where I want you to see is down here when it says formatting types and it starts to show all of these examples and it shows what or it says what they do and it gives little try it buttons where it will launch a code play pin for you to try all of that out and you can see there are so many different ones here we used the percent one and before we use the fixed Point number format in my examples but there are many others that you can try out as well so I'll put this link inside of the course resources I'm back in vs code and you can see I've created a new file named rps6 which is our rock paper paper scissors game and I've pulled in the code from the previous lesson on closures and that was our rps5 version so right now I essentially have the ending code from the previous lesson that was in the rps5 dot Pi file so now we can apply some f strings to modify our rock paper scissors game and there's a few lines that actually need them so let's go take a look and we'll scroll down here to line 33 and you can see on line 33 and 34 we've got some longer strings and vs codes wrapping one kind of strangely as well let's first hide the file tree once again with Ctrl B we can see this a little bit better and let's modify the first one so we'll start with the letter F once again here and now we don't have to use the plus symbol to concatenate this string so let's highlight everything we have right here from the extra quote and the plus symbol and instead put a curly brace now we just need to find where the end of this string we're creating is and we're chaining the replace method and the title method so the end is really right here after title so let's put our curly brace there then let's delete the plus symbol and the extra quote as well and now it looks like we have made a full string here that's a little tidier by using an F string so now let's do the same thing and maybe vs code will like what we're doing better and will not wrap this down in a strange way so we'll start with the letter F here and we'll have python chose and then we'll highlight the quote and the plus symbol once again and instead we'll put a curly brace now let's get rid of this weird space vs code is added and now we'll be going to the end here so here's the replace and the title so at the end of the title we'll put another curly brace that looks better already now let's delete the plus symbol and the quote as well and now we have the period and then another new line character and that's all fine so let let's save and well vs code wrapped it down but I like where it wrapped things better because now after the parentheses for the print we just have this long F string so let's go ahead and move this closing parentheses down the next line as well and save and that formats quite a bit better and you can have that opening and closing parentheses on separate lines and then our F string is all on one line as well and now let's scroll down to line 63 and we have these different outputs here for the game Count player wins and python wins and you can see we're still concatenating a value so let's once again make these F strings I'll just start all three of those with the letter F now we can highlight the quote and the plus symbol delete those and start with the curly brace and really if I highlight one and press Ctrl D it will highlight the next as well I'll press backspace to change both at the same time and then add the opening curly brace to both at the same time as well so that's nice afterwards we need to put a bracket here in between these two parentheses so we could of course highlight both and then Ctrl D and Ctrl D now we've selected all three I'll arrow to the right to go to the end and then arrow to the left once and there I'm in the middle of all three and so then I'm going to add that closing cursor as well and after that we need to put a closing quote so now we have a full F string in each one of these print statements and we can save the file and now let's try our game out just to make sure everything is working as expected we'll choose run python file here and it's asking us to play we'll make a choice I chose Rock and everything looks like it works as expected even though we lost the game so let's play one more time we don't like to quit when we're losing and we still lost maybe again we'll keep going with Rock and Python's beating us every time but we finally won on the fourth game and everything works as expected so now you know how to use f strings and we've applied those to our rock paper scissors game I've got vs code open and you can see I have a new lesson 14 folder over here in the file tree let's create a new file and let's call this modules dot Pi now inside of our modules dot Pi we're going to actually import something first and we've done this previously so modules can be considered small code libraries that are based on related features and one example of this is the math module and it contains functions and constant values for use in mathematical equations so we can import math and that's a built-in module in Python so python comes with this module but you have to import it to use it and now let's go ahead and access something from math and if we want to do that we can just print and then say math and then I'll use dot notation and notice what happens all of these different things that are available in the math Module come up and I'm going to scroll through here just so you can see a lot of them but we're choosing a a constant and I'm going to choose Pi so we're just going to print Pi inside of our output window and I'm going to add a couple of extra lines just so that doesn't scroll up on me like that and then I'm going to go over here to our drop down and run the python file and notice we get the value of pi here in our output once again I'm going to go to view and appearance and then to panel position and move that to the right just so we can see our output over here today but now you know what I'm doing I'm either getting functions or constant values from the math module and of course we could bring in any type of data that could be in the module there may be a dictionary in there or a tuple or something else we can access now earlier in our series we also imported a couple of other modules that we're using in our rock paper scissors game one of those was CIS and another was random and now later in the code we were using some functions so one we used to exit the program and that was CIS dot exit and then we call that function and then another one we used was random and or random.choice actually I should say random dot choice and we pull that up and then it shows one of the characters of a string we provided like one two three so just a couple of functions that are available from other modules that we've already used now here we're importing the entire module and then we're using dot notation to pull a function or a value from that module but instead of that we can just pull out what we need and you have seen that once already in this series too because in our rock paper scissors game we're using enum and to do that we say from enum which is the module then we say import enum or we could do any of the other things that are available from that module but now we're only importing enum from the enum module and I know with the same name that's a little confusing but just for example if we didn't want to say math.pi instead of import math we could say from math so we would from math here and then we would just say import pi and then notice how vs code already realizes we're now using the wrong syntax then we would just refer to Pi as we want that output and we can run our code again and we still see the same value output here now something else we can do is create an alias so if we don't want to refer to a module by its name say random we could create an alias by just typing the word as after and then I could say RDM and then I could refer to RDM Dot and then still have all of these choices here so like the choice function that I was using before so how do we know what to use from a module well there's a few ways to find out what's inside of a module one of those ways and I'll just create an extra line here but is to use the dur function so I'm going to print here just so we can see the output and then I'll call the dur function and then inside of that which der I believe would be an abbreviation for directory if I'm not mistaken and then inside of that we can just pass whatever module we want to now I've got an alias for random so I'll just put that alias in here and this will work but notice the output when I go ahead and run the code after I save it it's got a list of everything in the module but boy is that kind of hard to read it's literally a list so list type data and then we've got everything in here and it's all jumbled together but we can make this more legible for us actually because we'd like to do is just put one of these on each line and then see everything inside of the module so let's just Loop through it so I'll say four item in dur and then pass our random module but I'm passing in the Alias of course that we created and now I'm not going to print the directory of random here instead I'm just going to print each item as we go through the loop so I'll save this and run the code again much easier to read now and we can see everything that is inside that module of course I already showed another way to do that and that is with DOT notation so I just type the module name or the Alias of that module and then I use dot notation so I type a period and vs code helps us out so we can see all of these different things that are available inside of this module but neither one of these ways actually tell you what any of these constants or different data types or functions are inside of the module so for that let's go to the docs quickly I'm in the python documentation now as you can see here at the top it says documentation for python 3.11.3 we're at the python module index now if you're watching this in the future and python has gone to a newer version that's okay you should still be able to find this python module index and here is an alphabetical list of all the different modules that are available and then if you go into of the module so let's find one we were using like enum here I'll click this and it takes you to a page that shows all of the details for that module and it details everything and describes everything inside of the module so this is a great reference and of course I'll link this in the course resources for you to go with this lesson okay now we're back in vs code and we're going to look at a custom module that I created notice it's named Kansas dot Pi so like any other python file it ends in dot pi and then inside of the file we've got some values here so I've set the capital the bird the flower and the song for Kansas and that's the state that I'm from so you could create one of these files or modules if you will for where you're from if you want to just as an example to go along with what I'm doing but we've got a few values here and then we've got a function that says random fun fact and you can see inside of this random fun fact function I have a list that has four fun facts about Kansas and then notice I'm also importing something from another module because you can do that inside of modules that you create as well just like other python files so from random I'm importing the choice function so then down here I'm creating the index value using the choice function and choosing between 0 because remember our list would start with an index of zero so zero through three so it's going to choose one of those and this is a string so then when we use the index we need to convert it to an integer here and we're doing that with the Constructor and then we're just referencing which index it is inside of fun fact and we print that so this might surprise you but there's really nothing special inside of a module we've got data and we can have functions as well and you can use other modules inside of a module that you create and so that's what we have here let's go back to our modules file now inside of this file we can import our Kansas module or if you created one for wherever you live that's fine too so we've imported Kansas now let's use what we get from the module so I want to print the Kansas capital and notice with DOT notation I see the other things available in the module as well I'm going to choose Capital so I should print out that value now remember our function already prints so I don't need to call Print here so I'll just say Kansas and then random fun fact and we'll just call that function and it already prints if we go back you'll see at the bottom here it returns a print and we don't really need that return there even I don't think I had that before so let's just go ahead and remove the return it should still be fine without it and I think that's what I showed you before so here we'll go ahead and save and now let's run our code and see what we get from bringing in the Kansas capital and the random fun fact so here at the bottom the Kansas capital is Topeka and then we have our random fun fact Wichita is the largest city in the state but many would guess that that is Kansas City that's also true much of Kansas City is actually in Missouri okay so we're using our new custom module now and now we need to talk about one special value that every module has and that is the name value and it is surrounded by two underscores but both before the word name and after so let's look at that and we can print the name of the module that we're running so let's print and then let's just say two underscores name and two more underscores now do you think this will be modules it possibly could be but maybe it won't be let's go ahead and see what we get when we run our code again and notice the name is Main and Main also has two underscores both before and after the name main that is because this is the module we're running so we if we print the name name of the Kansas module for example we could say Kansas Dot and if we scroll through here we should find name there it is so that's available to our custom module I'll save let's run this notice the name of the Kansas module is Kansas and that's because we're importing that module so it gets the file name just like we have here Kansas dot Pi so the name is Kansas but the file that we're running modules.pi its current name is Main and that indicates that that's the file that is being ran now this can be very useful so for example I'm going to go back to the Kansas module and at the very end of the file here I'm going to put an if statement and I'm going to say if two underscores name two underscores equals and then I'm going to put in quotes main with the underscores then inside of that we're going to go ahead and run our random fun fact function so now this function is only going to run that's only going to be called into action if this is the main file oh and I only put one equal sign there we actually need 2 as we compare we're not assigning we're comparing here so that needs the two equals so if name equals Main and you'll see this in many modules because this way they'll only run this code after this if statement if they are the main file in other words this file is being called into action so let's go ahead and run our Kansas file now and see what we get we have a fun fact from Kansas Kansas is considered flat but it does have a mountain I believe we saw that one before so this file will run this function if it is the main file so that can be very useful when you create modules now if we come back to our modules here and we go ahead and run this modules dot pi we won't see anything different than what we had before we don't see the fun fact function running twice as a matter of fact I could comment out the fun fact function and now we shouldn't see it run at all if we do that and we don't we just have Topeka and then the two different name values Here Maine and Kansas that we printed at the bottom but it's important to do that if you want to have something called inside of your module because if we don't do that it will run every time so if I comment out the if statement here then we'll have to of course change our indentation just bring this back to the front now when we import the Kansas module this will run so we should see a fun fact executed twice because we're also doing it inside of our modules file let's go ahead and double check that I'll run the code and while we're not seeing the result here because of this long list but if we're to scroll up there's actually another random fun fact at the very top of the list and here we see it Wichita is the largest city in the state so we see that before we even print pie let me go ahead and comment these out again I'll select all of those and do control with the Slash and it will comment those out and now it won't be so far between when we see our output here we'll run the code again and notice we've got a considerable portion of Kansas city is in Missouri and oh I commented out the other Kansas information too I meant to just do the loop let me try that again I'll uncomment by doing the same thing select what you want and then control in the Slash and I uncommented both of those let's save and run the code again okay now now we actually have two fun facts running even though we're only calling it once in this file and that's because this first fun fact runs right now when Kansas is imported the Kansas module that's because we don't have this if statement another important thing is if you leave this over here it could actually to be included in the import list let's see if it is I'm not so sure if it is or not but let's check say Kansas and then we'll Dot and we have random fun fact here let's see if another one is included it's not by vs code at least knows not to do that however maybe not all tools with python do so one thing to consider is you don't want this included in what's available to import as well if another python tool were to allow that so it's much better to put this if name equals Main and then of course we need to indent this back with tab there we go and now we'll only get the fun fact that we intend to run inside of our modules file and this will not run unless Kansas is the main file so let's go ahead and run our code one more time just to prove that and yes the first thing we get is the pi value and that's up here and then we get the capital then we get the fun fact and the two names okay now that we've covered the name value let's close the terminal window let's create a new file over here and we'll call this rps7.pi now we're just going to start with the code that we finished with in the last lesson on closures which was rps6 for our rock paper scissors game so I'm just pasting this in and this is the exact code you should have finished with in the previous Lesson Four rock paper scissors now we just want to make a couple of changes here to make our RPS 7 dot Pi a module so let's go ahead and scroll to the very bottom and once we get to the bottom here of our file what we're going to do is I'm going to rename this play and I'm going to name it Rock underscore paper underscore scissors and we're setting that equal to the RPS function and that's because we're using a closure that we learned about in the last lesson now the nice thing when we make this a module is the rock paper scissors function that we want to call will be available to import now underneath this let's go ahead and delete this let's put our if statement so if two underscores name two underscores equals with two equals then two underscores main two underscores inside of this if statement we'll go ahead and call our rock paper scissors function so this will only execute if our rps7 DOT Pi is the main file so if we go ahead and run this code rock paper scissors would execute but when we import the file it will not automatically run it will allow us to call the rock paper scissors function where we want to so now inside of our modules dot Pi let's go ahead and import this and I'm going to say from rps7 and I'm going to import rock paper scissors now of course we could just import rps7 and then we would have to refer to this as rps7 dot rock paper scissors but here is our rock paper scissors function and it's ready to be used so we will call it right here at the bottom of our modules file and now after we see these different values print out the game should start so let's go ahead and run our modules file and yes we're ready for a game of rock paper scissors let's go ahead and play and python one so I'll go ahead and quit this time instead of playing until I win but now you know more about modules we've got built-in modules in python or you can create custom modules as well I've got vs code open I have an open folder over here named lesson 15 and we're going to create a new file and let's call this file hello underscore person dot pi to accept arguments from the command line that is values that we will pass in to the programs that we call we need to use a module so we will import ARG parse and that is part of the Python standard Library when we previously discussed python modules I gave a link to the python module index and we can see the ARG parse module right here it says command line option and argument parsing Library I also want to call your attention to the python standard library page and this shows kind of the different modules instead of in the index that we had on the other page it shows them kind of in feature areas here so different things you can look at a different way to find the same thing so if I search the page with Ctrl f for ARG parse we can once again find it under generic operating systems services so just another way to find the modules that you would be looking for back in vs code let's go ahead and Define a parser and we'll set this equal to ARG parse and then dot then we'll say argument parser and from there we'll use parentheses and we're only going to pass in some of the basic settings that we can for this argument parser but if you look back at that module page for our parcel you will see many other settings as well here it will just say description equals and then we'll say provides a personal greeting whoa I'm not spelling good today there we go provides a personal greeting so we have set the basic description for our argument parser now let's say parser dot add argument and there we'll go ahead and pass a few different values first we're going to put in a value that you could use at the command line as a flag so just Dash in this will be short for name so we'll also say you could also provide Dash Dash name which is just a long version of the same thing so you could use either one of these at the command line and I'll show you how then there's another setting here we'll call metavar and we set that equal to name as well now this is just the display name if you get a message that refers back to this argument now we're going to say this is required so here we just set that equal to true and then we can also provide a help message and here let's just say the name of the person to greet and that should be all we need to add this argument to our parser now let's say args equals parser dot parse underscore args and that is a method on parser so we just call that and now we should get those different arguments so when we want to print a message at this point let me Define the message and I'll use an F string so we'll have F and a quotation and I'll say hello and then inside of this we'll say args dot name now where is name coming from let me put an exclamation mark behind this but where is name coming from what you see this value right here that says name now that's pretty much what it's going to refer to however if you want to assign something different we could say dest and set that equal to let's say first name then you would no longer use name here you would use first name for example so either way I usually use dust off and we just refer back to name so let me go ahead and remove that and we'll see how that works as well I'll quickly click yes here but underneath our last one we actually need to go ahead and print our message also so there is a basic example of using the arc parser now let's go ahead and use this in a terminal window I'm going to press Ctrl in the back tick to open our terminal window that I've already got over here on the right Ctrl B to hide the file tree so we can see a little bit more of our code and then alt Z to wrap any code down that was extending out of the window so now it wraps down to a second line now we can't use the play button like we used to to call this file because we need to pass an argument so we're just going to type right here in the terminal and I'll type Pi because I'm on Windows but if you're on Mac or Linux you're probably going to need to type python 3. I'll type pi and then I want the file name which is hello underscore person dot Pi but if I press enter right now I'm going to get an error let's go ahead and do it to see what happens and it says we have an error it shows the usage here and of course the dash H is for help then we have the dash in and it's referring to a name and then it says the error the following arguments are required that's because we required this argument over here so let's try this once again or let's even see what the help does so let's go ahead and pull this up again and then just do Dash H for help and let's see what we get now we get our provides a personal greeting so that's the description we passed in up here and it shows the options and of course Dash H for help and dash in for name the name of the person to greet so let's once again pull that up and now instead of Dash H I'll say dash n and I'll pass in my name as a string just Dave and we get back hello Dave now that's what's expected let's once again close our terminal window for the time being and now let's create a function just above everything we have even the import which I know is something you haven't seen me do before for but let's do it this time and let's say deaf hello and we're going to pass in not only a name but also a language that I'll abbreviate as Lang now inside this function I'm going to define a dictionary called greetings inside the dictionary I'm going to use English and I'll match that to the value of hello that needs to be a string also after that let me copy these lines down with shift alt and the down arrow twice and I'm going to change these so the second one is going to be Spanish and that will be ola and then the third will be German and that will be close instead of hello as we say in English it's Hollow with an A okay after those three let's go ahead and Define our message once again message equals an F string and inside of this string it's going to start with the value that we get from the dictionary so greetings and then we're going to refer to whatever we get in that Lang param that is up here and then after that we want a space and then we're going to use the name param value the parameter so as we pass these values in remember they're called arguments but when we Define a function these are parameters or as I often say params okay now we're going to have a print once again for that message so that's what our hello function is going to do it's going to determine the language we're going to have a name and we're going to say hello in the requested language now someone could import this function from this file if they wanted to and if you remember what we learned about modules we can go ahead and put our if name equals main here to then only run the code underneath if this file is actually the file being ran and it's not having the hello function imported from somewhere so we'll say if two underscores name two more underscores and we'll say equals and we need two equal signs as well then we'll have two underscores Main and two more underscores and then our colon now everything is going to need to be tabbed over so I'll highlight everything and tab over once and now remember we have a second argument so let's add another argument to our parser underneath so we'll say parser.add argument and now here we're going to call this one L instead of dash n so we'll have Dash L will also have dash dash Lang and then we'll have a metavar and just to point out that they're not the same here I'll put the full word language instead of Lang but we're still going to refer to Lang when we get the value after that on the next line I'm once again going to say required equals true and then we can pass choices so we can have specific choices here and if these choices are not correct then an error will occur once again so here we'll make sure that the values we want are passed either English or Spanish or German are the choices and then after those choices let's go ahead and put in a help value as well and here we'll say the language of the greeting and that's that's good enough just the language of the greeting okay now that we've defined that we need to change what we're doing below we still want to get the args from the parser with parse args but then here we're not just going to print this we're going to call our hello function so we'll say hello and we'll pass in the args.name and then we'll also pass in the args dot Lang so quickly to review before we use this code we just created our hello function above and then if this is the file that's called into action then we'll use the ARG par so that's why the import is down here it's not needed up here at all and then we'll go ahead and use this and we pass the two arguments to the parser and then we call the hello function with those values let's once again press control on the back tick to open a terminal I can clear this out by typing clear as well just so we start at the top and now let's go ahead and say Pi or once again if you're on Mac or Linux Python 3 then we'll have hello underscore person dot Pi now all of the same errors will apply so if we don't pass a name we would get an error and likewise if we don't pass a language we would get an error but even if we pass an incorrect language like French for example we should get an error let's check that out and yes we do have an error it says invalid Choice French we should choose from English Spanish or German so let's go ahead and choose one of those I'll enter in German and press enter and we have hello Dave and I can see I forgot to put an exclamation mark inside of that function greeting so let's go ahead and put that back seems like we have to have an exclamation mark with a happy greeting right so after German let's put in Spanish now to test this out and we have Ola Dave with the exclamation mark let's once again close the terminal here in vs code and let's show the file tree Again by clicking the explore icon over here and now as we have in previous lessons let's create a new file let's call this file rps8 dot Pi because we're going to pull in the code from our previous example of rock paper scissors and that file was called rps7 in the previous lesson so let's just paste in the code from rps7 that we had and we did learn how to make a module with our rock paper scissors game but now we're going to go ahead and pass in a command line argument to the game so we can personalize the game but before we do that and I do want to thank Ahmad and those that comment on the videos but especially thanks to a mod for catching this one because in a previous lesson the one on F strings we created three F strings inside of our rock paper scissors game and as he note noted we no longer need to use the string Constructor here in lines 63 through 65 because you can just pass game Count into this F string and it will go ahead and show it without using that string Constructor so it will just make it a string as you create that F string so we can go ahead and select all three instances of the Str and that parentheses and I did that with Ctrl D after I selected the first one then I'll press backspace then of course we need to get rid of the closing parentheses on those and this will still work without that string Constructor now that said and I'll save those changes I do want to highlight that online 33 and 35 you still need the string Constructor here and that's because we're applying it to that enum value and then we're calling a string method so we really need a string there specifically and it's not being converted before that happens so you need to go ahead and leave that string Constructor on these two lines but on 63 through 65 here when we have the game Count player wins and python wins thank you Ahmad for pointing that out because I did miss that it didn't cause an error there was no problem other than it's just not needed so we might as well remove it so now let's scroll to the bottom of the file where we're calling rock paper scissors here and we're going to change this just a little bit I'm going to start by pulling this rock paper scissors definition here where we set it equal to RPS to create our closure I'm just going to control X to cut that and go ahead and put it right above the call to the function here and then let's go back to our hello person because this code that we use with ARG parse is kind of boilerplate and that means we're not changing much of this right here we want to get a name to go ahead and pass to our game and personalize that so let's just copy all of this the import ARG parse all the way down down to where we set the args equal to parser.parse RS and Ctrl C to copy and then let's bring it over to our rock paper scissors game and this is going to go before we Define rock paper scissors there so right after the if name equals main I will paste this in now we're not using the language argument so then I can go ahead and remove that piece of it now let's change our description just a little bit so here we'll say provides a personalized so there will just change that word to personalized game experience and now here instead of the name of the person to greet we'll say the name of the person playing the game playing the game and ALT Z once again to wrap any code down that wants to extend off the screen now I'm going to remove an extra line here and then all we need to do is pass our args.name to RPS and now we're finished with this part but now we're passing the name value to our rock paper scissors game but our game is not handling that yet let's start by going to the top of the file where the function begins and now we know it's going to receive a param so I'll say name and let's put a default value just in case this would be used somewhere that it doesn't receive that name so we don't have an error if that happens and we'll just make the default value player one after that we need to go ahead and put in another non-local here and pass name because it's coming from above from RPS as it goes into the play RPS function now let's scroll down and see where else we can use it and one place would be here where we ask the player to enter any of the numbers for rock paper scissors let's make this an F string and then we'll go ahead and put name in front here so I'll say name and a comma and then we could just make that a lowercase e and then underneath here we could also make this an F string and use that value so we could say whoops not that let's go ahead quote and then we need a curly brace and name and then let's put a comma and then there we'll just put a lowercase y For You must enter as well and you know what let's be a little nicer here let's put please in both of these so we'll say please enter and instead of you must enter we'll say once again please and I need to get rid of that t there go so it would be like Dave please enter one two or three scrolling down just a little bit further we have another line here where it says you so let's change that we already have an F string so now I'll just go ahead and remove that capital Y and we'll put in name once again I'll put in a comma and a lowercase U so Dave you chose and then it would give that value now we have our nested decide winner function so once again we need a non-local for that name value if we're going to use it inside of this function and we definitely are so instead of just you win now we could have an F string so this once again needs to be an F here and then we can put in our name value so name comma you win and now let's just copy this because it's also used on a couple of other lines so Ctrl C there and then we'll highlight this Ctrl D to select the next one that's identical and then Ctrl V to paste and we have that same F string for all of the winning messages let's scroll just a little bit more and here on 56 where we have python wins well that works but we could personalize that a little bit more once again we need to make that an F string if we do and I hope I haven't missed any of those slash in and then let's say sorry comma and put in name once again we could put in a couple of dots so sorry Dave and then we could even put in an emoji so let's find a sad emoji here and I just typed the Windows key plus period on Windows to bring up this Emoji menu so I have a little sad face with the message that python won instead of me okay after that one let's look a little bit further and yes we can provide another one here on line 67 I'm sorry on line 66 where we say player it doesn't need to say player now it could have a personalized name so let's put in name and after that we need an apostrophe s now we can use that apostrophe because on the outside we have double quotes So that single quote doesn't cause an issue and how about we do the same for the play again message so we'll put an F here to make this an F string and instead of play again question mark we'll have play again comma and then we'll put in that personalized name so it's going going to ask play again Dave for example and let's see if there's any other instances as we scroll down and yes we've got thank you for playing which is fine we could personalize that but let's personalize the buy message instead so we can say buy and then just put name in one more time so now we've personalized our entire game now I know I went over that a little bit quickly but we covered Concepts we had before from the F strings to the non-local definitions where we pulled that value into the other functions that were nested okay let's hide the file tree with control B and then I'll press Ctrl and the backtick to open our terminal up again I'll type clear just to clear everything out and now let's go ahead and start our rps8 file once again we can't use the play button like we used to at the top because we need to pass in these arguments so I'm going to say pi and you might need to say Python 3 just depending on your operating system then I'll go ahead and say rps8 dot pi and I'm going to pass my name with the dash in as Dave and let's see what we get it says Dave please enter and so I'm going to choose Rock and we got a tie game but we can see Dave's wins are zero and that says play again Dave so I did personalize that fairly well let's see if we get something else let me choose a number that is not one two or three like five Dave please enter one two or three so it's also being polite and working as expected another Thai game let's go ahead and play till someone wins and we've got three tie games let's go ahead and play again and now we won and it says Dave you win so that's exactly what we wanted for this game so now you know how to pass command line arguments and we've personalized our rock paper scissors game I've got vs code open and you can see I have a folder for Lesson 16 and I already have all three files in it for Lesson 16 and that's because today is a student challenge today's lesson is different we're focusing on applying what we've learned instead of learning something new and we will attempt to complete a two-part student challenge so I've got the terminal hiding my code so you don't see the code that's in these three files for now part one will be creating a new game called guess my number and this will require you to take what you've learned from building the rock paper scissors game in previous lessons and apply it to a new problem so let's look at how this game works first so I'm going to launch guest number the file that you see over here on the left side from the terminal and I'm in Windows so I type Pi if you're in Mac or Linux you should be typing probably python3 and then I'm going to type the file name guess underscore number dot Pi now it's going to accept a name as we learn to pass in a command line argument and receive that with the ARG parse module so I have dash n for name and I'll just pass in my name Dave when I press enter it should launch the game and it says Dave guess which number I'm thinking of one two or three I'm going to guess one and we can see the result it says Dave you chose one I was thinking about the number one so Dave you win game count one Dave's wins one and my winning percentage is one hundred percent then it asks if I want to play again or not so I'll say yes I'll choose two and it looks like I didn't get the number right once again the game was thinking about the number one but I chose two so it says sorry Dave better luck next time now it updates the game count my win number is still the same because I didn't win and it updated my winning percentage now it's only 50 percent compared to one hundred percent before now of course we can quit this game as well so let's go ahead and play one more time though just to see what happens if I choose a number that's not one two or three it just says Dave please enter one two or three so then it starts over and that's what we would expect to do so let's go ahead and pick another number and I didn't win again so now my winning percentage is 33.33 I'll go ahead and choose Q to quit and then we get the thank you for playing and goodbye Dave so a lot like our rock paper scissors game but not quite so you can take what you learned from that and now create this new game Guess My Number now after completing the first part of the challenge which is creating the Guess My Number game then we're going to move to the second part of the challenge which is to build an arcade that will allow you to choose between rock paper scissors and guess my number and this is going to require you to take what you've learned about modules in previous lessons and apply it to a new problem so let's look at how the arcade works so we launch it much the same way I'll say pi and then arcade dot pi and from there I'm going to pass in a name at the command line as well and once we launch the arcade it says Dave welcome to the arcade please choose a game and I can choose one for rock paper scissors or two for guess my number or press X to exit the arcade so I'm going to choose one for rock paper scissors and you can see the game launches now so I'll choose one for rock and python one but I'll go ahead and quit and when I quit the game it says Dave welcome back to the arcade menu please choose a game so we're not going to exit the game entirely or the arcade from our rock paper scissors game or from the Guess My Number game we're going to exit it when we're back at the arcade menu so now I'll choose guess my number and we'll see if it works the same way so I'll guess a number and I did not win but I'll go ahead and quit now it says Dave welcome back to the arcade menu now if I don't choose one two or X here I'll press 5 again it's going to just start over and say Dave please enter one two or three and I guess I need to change that to 1 2 or X actually so I need to update my code just a little bit go ahead and do that in yours as well because the options here are 1 into or the letter X so now I'll just press X to leave the arcade and it says see you next time by Dave so you've got the idea here for the arcade and how it should work you should be able to launch either game from it or exit the arcade and when you launch those other games when you quit those games you should go back to the arcade so that's a different Challenge and you're of course applying modules and other things you've learned along the way to conquer this challenge as well so now you should be ready to pause the video and attempt to build the Guess My Number game part one of the challenge so when you finish building the Guess My Number game come back to this video and I'll show you my code for the game so I'll see you then okay we're back and ready to review the code for the Guess My Number game so I'm in the guess underscore number dot Pi file that I created I'm importing a couple of modules just like we did in the rock paper scissors game I've imported CIS and random notice I don't need an e num now like we did it in rock paper scissors now I create this parent function because we're still going to need a closure to keep track of the game count and player wins so I have this parent function called guess number and then inside after I set the game count and player wins to zero I initialize those values essentially then we have our next function which is play Guess number here of course we need those values we're going to get the name from a param by the way which also has a default of player one if nothing else and we're pulling in the non-local name and then non-local local player wins right now not game Count yet but we will later and then much like rock paper scissors we have an input with the player choice and much like rock paper scissors if they don't choose the correct thing we go ahead and use recursion to launch this play guest number once again so we call it and it starts over from the top then we have the computer Choice decision here and it's just a random choice between 1 1 and 3 we did that in rock paper scissors as well now we go ahead and print saying personalizing the message as well and the saying you chose and give the player choice now the player choice up here was a string and that's fine to put in here we didn't need a number at this point and then of course we say I was thinking about and put the computer Choice here it is also a string and if it wasn't we're still using these F strings so it would make the conversion without us using those class initializers as we previously did when we were concatenating strings but down below we go ahead and do make those numbers they were both previously strings and player choice and computer choice now their numbers in player and computer and we're going to use those as well so here we're looking at decide winner this function and we have player and computer we need to once again bring in the name and player wins and now we're going to compare player and computer and it if they are equal because that means we've guessed the number correctly we go ahead and increase we increment player ones with our plus player wins with our plus equals and then we return the phrase here saying you win if not we say sorry better luck next time so that's returned and then we hold the value that's returned from this function in-game result as we pass in player and computer the two params that it receives now these are argument values being passed in and we print the game result now here is where we need the game count and this is just like we did in rock paper scissors as well so we increment the game Count then we're going to Output the game Count we're going to Output the number of player wins now this is new we have an F string here saying your winning percentage now inside of the F string we can calculate that winning percentage by dividing player wins by the game count and now we're formatting the the output of that calculation as well and we went over some of that formatting when we learned about F strings so we have a colon here then a DOT two which means we want two decimals and the percent sign so we're going to display that as a percent and then we ask if they want to play again just like rock paper scissors and we handle that the same way whether they want to play again or maybe they don't want to play again and of course they have to enter in the correct number or it just Loops back through then if play again we're going to use recursion once again and launch the play Guess number function once again but if not then we're going to go ahead and print the thank you for playing here's something that's just a little different because we want the guest number file to be able to run on its own and if that's the case then that means name will equal main so if that's the case we're going to use the system exit and exit out of the game when they choose to quit but if not say it's launched from that arcade file then we just want an empty return here which will go ahead and exit out of this function and that would take it back to the parent function that it will be in the arcade file so we do need to have a conditional here based on what whether the file is launched by itself where name equals main or if this file is actually a child which would be running from the arcade so then we just have an empty return and then of course at the end of this function we're returning play Guess number so we can create the closure that we learned about so that is what is happening there now we're here saying if name is equal to main we're going to go ahead and parse those arguments passed at the command line which should be a name and then when we get down here we go ahead and finish creating that closure because we set guess my number equal to the guess number function that receives the name from the arguments and then we call the Guess My Number function and that once again goes back to our lesson on closures so a little simpler than rock paper scissors much of it is the same and we were able to remove a few things as well I hope you did good on this challenge now with the Guess My Number game complete you are ready to take on part two of the student challenge where you build an arcade menu that allows you to choose between rock paper scissors or guess my number so pause the video and come back when you're ready to see my solution we are back and ready to review the code for the arcade menu so at the top of this file we're once again going to import the sys module then from the RPS file which we have rock paper scissors in we're going to go ahead and import RPS and from the guest number file we're going to go ahead and import the guest number function Now quickly I want to just go to the RPS file because the same thing that we did in the guest number file the only thing I changed in rock paper scissors from previous lessons is when we exit the file so once again if name equals main then we use the sys.exit and that's because we called the rock paper scissors function directly from this file if not if it's called from the arcade file for example we're going to say else here and just return and have an empty return so we go back to working with the code in the arcade file so just highlighting that in the RPS file the same as guest number and that's the only change to rock paper scissors from any previous lesson okay in the arcade file now after the Imports it's structured much the same as we have defined other functions essentially so we're starting here with play game and then we have name equals player one as well just as a default just in case now the first thing I do we don't have a closure here but we are defining this welcome back variable as false it's a Boolean value and that's because I want to give a welcome back to the arcade menu when we come back from either one of the games say we played rock paper scissors we quit and we come back so here we only do that if welcome back is equal to true now notice we started a while loop right here so I say while true so it will be a loop that just contains continues if it is always equal to true if we don't exit the loop in some other way so if we come back to the arcade we're still going to be in this Loop and we'll get that welcome back message if welcome back equals true now notice I'm not setting welcome back equal to True until after we check the player choice because if they make the wrong choice say the number five instead of 1 2 or X as we have for choices here then it's going to relaunch this function now we wouldn't want to give a welcome back to the arcade menu message every time that they chose a wrong number so I wait to set that welcome back equal to True here now this is much like we had in both games where we have the input and we check that input and we give a message if the input is not what we directed the user to input after that we have a conditional if else if and then an else here so if player choices one they have chosen rock paper scissors now we have the name value being passed in here as a parameter so down here we use that and we create that closure remember we imported RPS so now we set rock paper scissors equal to RPS with the name being passed in and then we call rock paper scissors and that is that closure that we created there so it could keep track of the game count and the wins for Python and the user but if player choice is two then we do the same thing for Guess My Number it also uses a closure so we set guess my number equal to guest number where we're passing in the name value and then we call the Guess My Number function now the else so essentially here we're checking to make sure it's 1 2 or X but down here we don't need to at this point so we know if it's not 1 2 it's going to be X so now we just say see you next time and we use the system to exit the arcade that's the full arcade function it's not that big now we do have the if if name equals main so if we launch the arcade from the arcade file this is where we use the ARG parse to get the name and then down here we have our welcome to the arcade message that's only going to happen the one time right after it's launched and then we just launch Play game and pass in the args.name which launches our play game function from up here so I hope you did well on both of these challenges if not hey it's no big deal we're learning so you might have picked up a thing or two that you hadn't encountered before although we did go over this information sometimes it takes some time to learn how to apply it all and I think learning how to apply what you have learned is very important and you're only going to do that by trying to create some of your own things as well so now that you have this code for an arcade and you can call any game you want think of a couple other games you would like to create what are some other simple games you might create that you could add to this arcade so keep learning and I'll see you next time I've got vs code open a new folder for lesson 17 and let's create a new file and let's name it Lambda dot Pi okay we have two topics today and we're going to start with Lambda functions a Lambda function is a single expression that returns a value so let's look at a simple example and we start with the keyword Lambda so Lam and then you see BDA and I'll just press Tab and there it is and visual studio code highlights it because it's a keyword and now we're going to pass a param so I'll say num then I'll put a colon and I'm going to say num times num so this function would square a number so if we pass 2 it would be two times two and this is a single expression that will return that value but notice we're not using the return keyword but it will return the value now we can't call this function into action by name because it's Anonymous and sometimes Lambda functions are referred to as Anonymous functions but we can assign a Lambda to a variable so now I'll just take a variable name over here and I'll say squared equals and now it's going to store that function in the variable name squared so let's go ahead and use the function as an example and I'm going to need to print the output so I'll say print and then say squared and I'll pass in 2 like the example I gave now let's go ahead and choose drop this drop down here and I'm going to run the python file and we'll see over here on the right we get the number 4 as the output now just to understand the concept let's make another one but I'm going to press Ctrl B to hide the file tray so we can see all of our code here and we can still have our terminal over here on the right we could even type clear to get some extra space and clear that out so now our second Lambda so let's go oh and notice this added the def keyword here as I type squared there and it added the return key so visual studio code formatted that Lambda for me and I didn't catch that until now but let's go ahead and do the control Z to undo these changes now now before I saved it this is what I had so squared equals Lambda with a num and that's the keyword Lambda and then we're returning num times num so that is an expression but then once I saved it into squared it went ahead and changed it so once again when I save it changes it to this def squared and it made it a one line function essentially so BS code is going to do some of that auto formatting and that's okay but it's actually the same thing so now let's go ahead and create another one and I'll call this add to and it's going to be equal to a Lambda once again that has a num and then we'll say num Plus our plus I need the plus symbol instead of the multiplication num plus two and then we will print what it puts out and we'll say add to and let's pass in something like 12. now when I save it's probably going to reformat this in Visual Studio code again so I'll save and yes we can see it was reformatted let's run the code and we get 14 over here which would be 12 plus 2. now even though Visual Studio code is changing this formatting when I save it's important to know how to write a Lambda as I'm writing it with that keyword Lambda so we're going to look at some more examples and in the future you'll see why that's important when we get to the second topic Which is higher order functions but first let's create one more because I want to show that a Lambda can accept more than one parameter so I might have a function and I won't set it equal to a variable here I'll just write the function so I'll say Lambda and then I'll say A and B so two params here and then this would be a sum function so we just say a plus b so you can see what this would do this is an expression a function expression which is a Lambda function that accepts params A and B and then it Returns the sum of those two now if we set this equal to sum of course then we'll get that reformatting from Visual Studio code again but I'm going to go ahead and use sum here so I'll say print and I'll say sum and we'll pass in 2 and 2. of course when we save it reformats it and you can see it written in a more traditional function way here let's go ahead and run the code and we get 4 once again and with that being the same as our first function that was squared I want to show that's different so let's go ahead and just pass in two other numbers like 10 and 8 save rerun the code and now you can see we get 18 because it's 10 plus 8. and before moving on just so I can have this in the source code for you I want to put the Lambda functions in comments even though Visual Studio code reformatted when we we save so let's put a comment here and how we would write this with a Lambda so I'll say Lambda and then we had a num param and then we would say num times num without that keyword of return there and without the keyword def as well so just our function expression which is a Lambda so that was our squared function now let's move on to the add to function and we'll write another comment here which was Lambda and then we'll say num and then it has num plus two and then I'll go ahead and just copy this down and paste under sum as well so we can write a Lambda there and that has a and b so we had a and b and then it was a plus b here just so you know what the lambdas look like and you can refer to that in the course resources now let's scroll up for some room and I think you have a good idea of what lambdas are about and how to create them I'm going to add a line of comments here just so we know we're moving on to our next section so the next logical question after you've learned about lambdas is when would I use one well they're most often used inside of another function really when you just need a quick function that you don't want to save for later so let's look at how this works and it also makes lambdas very powerful when you do this so I'm going to define a standard function here and I'm going to call it funk Builder which stands for function Builder and it's going to receive one param which is X now inside this function I'm going to return a Lambda function so I'll say Lambda and then this is going to be num once again and then we'll say num plus X now let's look at how we can use this function to build other function so I'll say add 10 equals Unk Builder and I'm going to pass in 10 and then below that I'll say add 20 spell 20 there we go equals Funk Builder and I'll pass in 20. now what we have here is the x that we're passing in currently so we're passing in 10 as X and then this Lambda with add 10 is going to add 10 and then the same for add 20 because X would be equal to 20 but notice the rest isn't defined yet and we're returning a function now you've seen this before when we used closures we return to function and then we called it later so we haven't called add 10 or add 20 into action yet so let's go ahead and do that now and we'll need to do it in a print to see the output so I'll say add 10 and I'll pass in the number 7. now I'll copy this down we'll shift alt and the down arrow and I'll change that 10 to a 20 and we can add 7 to that as well too so we'll know the difference let's go ahead and save and see if we get any formatting that's different but no Visual Studio code left our Lambda the way it was inside of a function so that's good let's go ahead and run the code and now we can see we get 17 and 27. so we're using a Lambda as a function Builder essentially here in this first function so the Lambda is being returned and then the Lambda is actually called when we call add 10 and add 20. so in our example here the Lambda receives 7 as the num parameter and it received 10 the first time as the X param in the funk Builder function so now we're ready to move on to higher order functions so I'll put another dividing line in here with our comments and then let's go ahead and discuss this what is a higher order function well it's a function that takes one or more functions as arguments or a function that returns a function as its result so yes by that definition up here we just created a higher order function as well because it returned a function as its result that's our func Builder here and now we're going to look at some higher order functions that actually accept functions as parameters when we pass those in so I guess once again when we Define the function we Define it to accept a function as a param and then when we actually pass in the function that function is an argument and I should also highlight the fact that yes when we learned about closures we were returning a function just like Funk Builder so we also used a higher order function there but this is where I really like to start to talk about them and that's when we start passing functions into functions and that really brings up the discussion of higher order functions for me now these are predefined functions that are built into python so we'll just use this function we won't have to Define it and of course first then we'll be passing in a function as an argument so let's start by looking at our squared Lambda again so I'm just going to type this out once again it's Lambda and then we have a num and then that num is going to be multiplied by itself so that Lambda squares a number when it receives it so now let's define a numbers list because we need a collection of data now we've learned about different data collections it wouldn't just have to be a list we could have tuples and so on but I'm going to use a list for most examples today I'll pass in some numbers here 3 7 or 3 yeah 3 7 12 18 20 21 that's good they wouldn't have to be in order you could use any numbers you really want to and then I'm going to say squared numbers or squared nums let's just say squared nums equals and then we'll call map Now map is a function that is built into Python and it receives a function as the first argument so what I'm going to do is take this Lambda right here use control X and just paste it in here with Ctrl V so that is the first argument now the next argument is your data collection so now we'll pass in numbers and then it's going to iterate over every item in this list each number and it's going to apply that function to it and then it will create a new list well it won't actually be a list at first we're going to need to apply the list Constructor to it so I'm going to say print then I'm going to have list as the our list Constructor and then I'll say squared nums right here so let's go ahead and save this and we'll run our code and see what we we get so we have a new list here and notice each number has been squared so 3 times 3 is 9 7 times 7 is 49 Etc all the way through the list so really that's something we could achieve with a loop but knowing how to use math is so much more efficient and your code is so much cleaner this is just one line of code that we achieve all of that in by passing in a Lambda function and passing in our data collection to the function map now we're going to look at another built-in function that works much like map and it is called filter so we're going to use that same numbers collection up here and then we're going to filter some results with that so let's create another Lambda so I'll type Lambda and now this will receive a number as well we'll take that number and then we'll use the modulus and if you remember the modulus operator it actually Returns the remainder of division so anytime time we divide by 2 there's going to be a remainder if the number is odd so what we want to say is we're checking to make sure it's not odd or actually we should say we're checking to make sure that it is odd that's what I want to do is return the odd numbers if it was equal to 0 it would be even and if it's not equal to 0 as I typed here it will be odd so let's think about this Lambda what will it actually return well it's going to return true or false because we're doing a comparison so it's either equal to zero or it's not so it's either true or false if true this is an odd number so now let's define our odd underscore nums and we'll set this equal to filter now we're going to pass in the Lambda so once again I'll highlight this and Ctrl X to cut Ctrl V to paste and then we had our numbers list that I'll pass in here as the second param to filter we've got one line of code with Filter just like we did map and I still need to print and then use the list Constructor and say odd underscore nums and save let's go ahead and find out what is odd and what is not we actually had our Lambda return true or false and filter the filter function then only return the numbers that got the True Result and so we can see we previously had these numbers and 12 18 and 20 were even so we only have 3 7 and 21 in our new odd nums list so now both of these results could be achieved by creating a loop and looping through the numbers and doing the appropriate actions through each iteration of the loop however once again much simpler to have one line of code where you pass in a Lambda function and apply it to each item in your data collection that you also pass in to filter just like we did with map but map has a different approach than filter filter filtered out anything that did not get a True Result from the function we passed in and map returned the result of this function applied to each item in our data collection we've got one more higher order function I'd like to cover today so let's scroll up for some room and then I'll come down here and I'm going to type in import line but just know that when we save vs code is automatically going to take this import line to the top of the file so we won't see it down here on line 52 anymore it will be probably on line one so we're going to say from Funk tools import reduce now reduce can be a more complex function but at its most simple it just adds everything together so let's look at an example that is simple first let's start with our Lambda and the function that reduce accepts needs two parameters and the first is an accumulator or you could say a subtotal the second is the current which represents the current item so here we're just going to say take the accumulated total and add it to the current number as reduce iterates through our collection of data so now we need some numbers and let's define those here we'll say numbers equals and we'll go one two three four five and back to one that should work okay after we have our list of numbers let's define total and set it equal to reduce and then we're going to pass in our Lambda so I'll highlight it and say Ctrl X paste that in as the first param and after the Lambda we need to pass in the numbers data collection now that wrapped down to the next line but that's okay it's still basically one line of code you can see line 58 just got a little deeper here okay so now we've done that and we're just going to print total I do not need to use a Constructor here these are all numbers and they will just be added together so we'll save this and you saw the import is now gone it's probably at the top of the file let's go ahead and hit the play button to run and we get the total of 16 which is the total of all of these numbers now adding all the numbers together is a good example to well a simple example to show how reduce Works however you don't want to do that when there is a simpler solution and reduces kind of a complicated solution so if I remember right I named a function sum up here somewhere let's find it there is our sum let's call this something else like sum total so I'll just put a total at the end of this we'll say sum underscore total would be more accurate for a python name so we'll call this sum underscore total just to have it name something different because there's actually a built-in function named sum so you don't really want to name them after a built-in function so now we can just say print use the built-in function sum pass in our numbers which this is very much simpler than using reduce and if we run this code we should get the same number yes 16 twice so while we're using reduce we don't want to use it if there is a simpler solution but reduce can provide some more complex Solutions one thing you can add here for example is a starting number so a starting value let's go ahead and put that in and we'll say 10 and we'll save and run this code again and now we have 26 and 16. so we told reduce to start with another value however we could also do that with some if I remember correctly let's try try it out and put in 10 here as well so we run this and now we've got 26 twice so once again we're not doing anything with reduce that we can't do with sum right now so sum would be the better solution however let's look at a more complex solution for something else we could do with reduce so I'll scroll for a little bit of room here and we'll give a second example of reduce so I'll create a Lambda and this is going to be similar to what we had because it still gets the accumulator and the current params and now inside of this we'll take the accumulator into it we will add the length of the current item because the items are going to be strings so now let's go ahead and create a list of names and inside this list I'll put my name and then let's put Sarah Ito and let's put I don't know if you've heard this song but there's a long name involved it's John Jacob jingle timer Schmidt so there's a lot of characters there now and that's essentially what we were going for if you haven't heard that song look it up okay now we've got character count being defined and so what we're going to do is add up all of the characters in all of the items together and get a total and we can use reduce for that so we'll say reduce and here we'll pass in our Lambda so I'll control X and put it right in here as the first argument and now as the second argument I'm going to pass in names and remember we do have that optional starting value and here it's not optional because we're using strings but we want to tell reduce hey we're going to be using numbers if not it would view this as a string that was trying to add a number two and we would get a type error back so we put in the starting value of 0 as well and then we'll have our character count value so let's find out how many characters in total if we added all of the characters up from all three names that we have so now we can run our reduce and we get 47 so that is a little more complicated example there to show a good use of reduce even though it's still kind of a simple example here learning you'll learn more about reduce as you continue to learn more about programming but now today we have covered Lambda functions function expressions and higher order functions remember it's a higher order function if it was receives a function as an argument or if it returns a function I've got vs code open and a new folder for lesson 18. let's create a new file and let's name this file classes dot Pi now classes are kind of like blueprints when we want to create something and we're going to create objects with classes so you could say they are blueprints for objects let's look at a simple class I'm going to create a vehicle class notice we capitalize the class we defined so I used a capital V on vehicle now inside this class we can have properties things we Define like a vehicle might have a certain amount of doors or a make and a model which is what I'm going to use today but then there's also actions a vehicle can take such as going and stopping or let's call it moving or moves today so let's define a few things here and I'm just going to start with a basic method which would be an action we want to take properties and look at those as d details about our class or details about the object we're going to create from the class actually and we'll look at methods as the actions the object could take and we need to define those methods inside the class so I'm going to define a method called moves and we pass self in to our methods now all the self is is it's just referring to itself so we're going to need that and you'll see why inside of these classes and of course the objects as they're created but we'll just start by knowing we need to pass that in now that we have self passed in I'm going to print and here I'm just going to say moves along notice I'm not really using self right now let's just put a couple of dots but there we go a very simple method and it's inside the vehicle class so now if I want to create an object from this class let's call this my car so I'll say my underscore car equals and I'll call the vehicle class so now I've created my car which is different than possibly your car that we could also create from the vehicle class so I've got my car and now I could call the moves method on my car so I say my underscore car use dot notation and notice we have moves available here at the top so I'll hit press Tab and then just add the parentheses after to actually call that method and we'll save this file let's go ahead and run our python code by choosing run python file from the drop menu and now inside of our terminal here we see moves along so we called the the moves method on my car so to clarify this once again and I'll hide the file tree with control B but to clarify this my car is an object that I created from the class vehicle now I also mentioned that a class could have properties say we wanted to set the make and model for the vehicle we do that with an initializer function called init at the top so we'll say def we have two underscores which you've seen before when we use something special like Main and we use those inside of functions where we had two underscores Main and then two underscores and that's a common theme in Python so here we have our initializer or our init function and it receives self and then we're also going to pass in anything else that we need to pass into the class to create our objects and here I want a make and a model so these are the parameters and now here we'll say self dot make let's set this equal to make we'll do the same thing here self dot model is equal to model so we're referring the object to itself once it's created so self just represents the object that is created and we're saying the make equals make the model equals model and of course this is the blueprint we actually create the objects when we set our variable here like my car equal to vehicle and we call vehicle so now I can't just call vehicle like this I need to pass in a make and a model for my car so let's say I have a Tesla and then we'll say model 3 for example now it's going to have these values as well so above the call to the moves method I could also print and say my underscore car and I could say dot make and get that value now I'll do shift alt in the down arrow to just copy that down and I'll also say for model so I can retrieve those values from the object that I have created here so let's save this file let's run our code again with the play button you can see we have Tesla which was the mycar.make and then we have model 3 and finally we have moves along when the moves method is called now you can put more methods or properties if you want to on your class so let's put one more method in here that will use the properties that we have and retrieving those through what is called a getter is sometimes more often so are used more often so we would use that more often than we would say mycard.make for example so let's just create a function here that will return these values and I'll say Def and I'll call this get underscore make underscore model as I want it to retrieve both I'll pass in self once again now here we're going to use self in this method I'm going to print and I'm going to use an F string now inside the string and let's use double quotes here so I can use a single quote here inside the string when I say I'm a and I'll say self dot make which refers to that value that it will receive and self dot model if I spell it correctly and then let's put a period just to have proper punctuation and so when we call git make model it should return this statement and fill in self make and self model with the values it receives so now instead of print mic or a MyCar dot make and MyCar dot model I'll comment those out with control slash and instead I'm going to call my underscore car dot get make model and you can see that was available in vs code as well when I use dot notation and just put the dot after it showed the options so let's save this and run the code once again now you can see we get the statement I'm a Tesla Model 3 and then once again it calls the moves method and it moves along so as I said you can create more cars from this same class so let's do that now and let's create your car let's say your underscore car and of course you can set this to what whatever you want to I'm going to have a vehicle and say it's a Cadillac and then let's say it's an Escalade and then after that we'll go ahead and say your underscore car dot get make and model and your underscore car dot moves save our code so now we've created two different car objects from the same vehicle class we can run this code and first we get I'm a Tesla Model 3 and it moves along then we get I'm a Cadillac Escalade and it moves along so now you can see how we can create different objects from the same vehicle class I think you now have the idea about the relationship between creating a class and then creating objects from that class so now let's move on to inheritance and notice we have a very kind of generic class here we're creating a vehicle it doesn't say what type of vehicle we might want to start to get more specific as we create classes that depend on this vehicle class and we can do that with inheritance so let me do that I'll scroll down here I'll create a couple of new classes the first one I'll call Airplane because an airplane is also a vehicle and it's going to receive leave the vehicle class now inside of airplane we might give it another moves method now notice if we put the same method in here this will overwrite whatever it would inherit from that vehicle class so I'll say def moves once again and it's going to receive self and now inside of this I'll just say print and let's say buys along and now let's create another one I'll call this class and this will be a truck also a vehicle but it's a more specific type of vehicle and now we'll give it the same method also and we'll say self inside of here we're going to print rumbles along and then finally let's create one more and I want to do this just because of how simple this can be you can't have an empty class so I'm going to say something like a smaller vehicle here like a golf cart and it will also receive the vehicle and now inside of this class since it can't be empty we're just going to say pass and this means it's going to inherit everything as is we're not overriding the moves method as we did with airplane and truck now because all three of these new classes depend on vehicle it will inherit what we already set up in the vehicle class so we need to pass in a make and a model as well so let's go ahead and create these new objects now and we'll pass in those values as needed so I'm going to say Cessna and that will be our plane so I'll say airplane and now I want to pass in that is a Cessna brand or make and then we'll say it's a Skyhawk which is the model we need to move on to our next one so let me just shift alt in the down arrow twice and we'll start renaming everything here so this is going to be Mac as in a Mac Truck name this truck once again the brand here or the make will be Mac and let's call this a pinnacle truck Pinnacle model finally our golf cart here so we'll just say golf wagon that should work and then for this we'll say it is a golf cart and now inside of here we'll make this a Yamaha golf cart and I have no idea what the model number would be I'll just say gc100 and now we should have those same methods available to us not only the moves method but also the get make model method that we had above so let's go ahead and do that for all of these we'll say Cessna Dot and once we put dot we can see what is available we have moves and git make models so I'm going to just call both and we'll put moves here as well and now I'm going to highlight both of these let me scroll for some more room I'll do shift alt and the down arrow and it will copy both lines at the same time I'll do it one more time and now I'll select the third Cessna Ctrl D to also select the fourth and change those to Mac I'll select the fifth Cessna Ctrl D to select the next one and I'll change these to golf wagon that's going to make me laugh every time okay now let's go ahead and run the code and we'll see what we get here so we had our code from above and that stops after the Cadillac Escalade moves along so here we are I'm assessing a Skyhawk it flies along I'm a Mac Pinnacle and it rumbles along and I'm a Yamaha gc100 which is the golf cart and it moves along because we didn't set any new moves method on the golf cart we just put pass so it inherited the original moves method directly from the vehicle class and so now you have a basic idea of how inheritance Works in our airplane class our truck class and our golf cart class all inherited from the vehicle class but what if for example you wanted to pass in some more information besides the make and the model let's say the airplane also needs the FAA identification number but you have to have that identification number for every airplane so let's go ahead and put in our init function once again I'm going to grab that from the top because if nothing else it's going to need to match and once you put that in that means it's overriding the entire init function in the vehicle put it in here and now we have an identical init function but let's say we want to add one more reference here so let's put in our FAA underscore ID and we would need to put in our self dot FAA underscore ID equals fa underscore ID but there's something easier than just copying self make and model so let's get rid of those and instead we can use super and then after we use this special function here super we can say dot two underscores a knit two underscores and then make and model now this means we're going to inherit these from the parent so we don't need to set those individually like we would have in that parent vehicle class so instead of having self.make and self dot model equals here we put in our super function and then we just pass the init make and model there now we could write another method that would use this FAA underscore ID but I think you know how that works so this is just important if you are going to create an airplane that had more information than its parent would receive or would have received so when that happens you need to redefine the initializer and of course to use the make and the model if you don't want to Define each line once again you need to call Super so you can also bring those in essentially from that parent class now when we Define airplane here when I Define Cessna it looks this same except now we need to pass in and I'll just put some random number here but our FAA ID like that so that would be the appropriate way to now go ahead and build an airplane object from the airplane class because it will receive that one extra argument that is represented as the parameter here inside of the initializer function that FAA underscore ID now I think you should have a good understanding of how inheritance Works how these classes are three classes here inherited from the vehicle class and then we created our more specific objects of airplane truck and golf cart here below now there's one other thing I want to cover today and that's polymorphism so let's go ahead and get an extra line here in our code I'm just going to print I have a simple string and put a couple of new lines so we can actually tell when we log anything else over here in the terminal it will be a little separate let's get some more room as well and now I'm going to create a loop so I'm going to say 4 V oftentimes you see X or Y or whatever but I'm just going to say V for vehicle in and now I'm going to put in the different objects we've created today so I've got my car also got your car we also created a Cessna we created a Mac and we created a golf wagon now inside of this loop we're going to say V Dot get make model we're also going to say V dot moves because all of these objects have both of these methods and I notice this lines just a little bit long here I'm going to go ahead and do alt Z if it needs to wrap down yeah just wrap down the one character but that's the colon this is all still on the same line for our for Loop here now polymorphism is a big word and that's what we're talking about polymorphism is the ability to behave differently in response to the same input messages so what does that mean in our case well it means we're going to get different responses when we call git make model and moves even though we're giving these objects the same input messages we're saying go ahead and provide the response to get make model and provide the spons to the moves method and we're saying that to each of these objects so that is polymorphism essentially they all have the same methods but that doesn't mean they provide the same response so let's go ahead and save this and we'll run our code and we get those extra line breaks in here like I wanted and now we see all of this information so we're getting different responses depending on what type of method they've either inherited or that they have in their own parent class that they were created from essentially but what polymorphism is once again is we are giving the same input we can Loop through all of these objects and say get make model and moves but they all behave differently based on how they were built so that's polymorphism so today we've covered classes which are our blueprints for creating objects and then we covered objects themselves and what you do with those and how you create them from classes and then we covered inheritance where we have other classes that can inherit from a parent class such as airplane inheriting from the vehicle class and then we also covered besides inheriting these we can overwrite what we inherit as we had new moves methods for these two different classes and then we can also even pass more information in to one of these other classes if we want to so that led us to learning more about this super function here that's called in the initializer of a class that is inheriting so it pulls in from the parent class as well and then finally we learned about polymorphism which we were actually using before we even looped in here because we were calling moves on more than one object and we were getting different responses and that's essentially what polymorphism is next time we're going to work on a small project with object oriented programming and that's what you've learned the foundations of today when we create objects we will be using object oriented programming I've got vs code open a folder for lesson 19 over here on the left we haven't created a file yet and I want to start with a quick apology because at the end of the last lesson I said we were going to move on to an object-oriented practice project that would be oop for object oriented programming and I said that was next but during the week I realized that we should probably cover exception handling first so we're going to do this quickly today next time I hope to move on to that oop practice project okay so you've probably seen a python exception before let's go ahead and create one and we can do that by creating a file over here in our file tree and I'm going to just call this exceptions dot Pi now inside of this file I'm just going to say print X notice we haven't defined X Visual Studio code notes that and puts a little warning squiggly under here that says hey this isn't going to work but we're going to go ahead and put this into action so we can see the exception I'm going to choose run python file here and we see over here and I'll drag this over a little bit more and then I'm also going to do control B to hide the file tree now that we've created our file we can see it says this is a name error so this is a specific type of exception that's telling us name X is not defined so that's what an exception is and now we're over here in the browser and I'm at W3 schools and they have a list of built-in exceptions that are built into Python and I like the way they present this it's just a simple table here so the exception name is on the left and the description is on the right notice they each say raised that's because in Python we raise exceptions if you're familiar with JavaScript we can throw errors there but here in Python we raise exceptions so on the left we've got all of the exception names and on the right it says when they're raised and all of these are built in but we're also going to learn how to create our own custom exceptions today okay we're back in vs code and we still have our name aim error over here on the right and in our code we are going to throw an error if we run this so let's go ahead and handle this and we do this in Python with a try block first so I'm going to say try and put a colon then I'll tab over our print X which will still throw an error right now and then we can have an accept block and this will catch the error notice now we don't have the squigglies we had earlier this still says it's going to throw an error because vs code is helping us out but we can just say except right here and this will catch all errors now this is a bit generic you want to be more specific and I'll show you how to do that but at first I just wanted to show how you can catch pretty much anything right here so we can catch this error and then we can print something when we catch it or do whatever we want like say print there is an error now we won't get that specific information like we did here instead we will get this there is an error statement let's go ahead save that run the code just so you can see how it works and now we have there is an error right here in our terminal now what I would rather do than catch all errors because this would catch everything and really we wouldn't get any useful information it would just say there is an error I would rather catch the specific error that might occur like name error so now this will only catch the name error then I could say something here specific like let's see I'll say name error means something is probably undefined I'm going to save that but I'm also going to press alt Z to wrap the code down just in case I type a long line and we don't see it all underneath our terminal so now that we have that and I run this code again it's going to specifically catch that name error and now we can see we have that statement name error means something is probably undefined but another error it wouldn't catch so let's try something else here let's say up above our try except I can say x is equal to 2. and now I'm going to divide X by zero and that's usually a problem also with mathematics when you try to divide by zero so let's see what error we get when we run this code and yes we have a zero division error so that's another error and it was not caught here in our accept block it only catches the name error so now we can provide another accept block to catch that specific error too so zero division error and we can print something here like please do not divide by zero and that would catch that specific error so if we run that we now see that message and so we've cut two specific errors and that's still leaving everything else to be caught possibly by an accept at the end of this but there's other things we can do as well and it's not always bad to throw an error that I said throw there I'm thinking in JavaScript to raise an error or let python raise the error like we when we had one when we didn't catch our zero division here in our own except when it just was raised by python that's not bad either because you really don't want to just put a blanket over everything and then not know what that error might be however after the accepts we can also have an else so let's say there is no error now we would get here so inside of this else I could say print no errors now if we throw I say Throw again there I'm going to say that probably too too many times anyway if we raise an error like the zero division error it's never going to reach this else so let's go ahead and run this code again that should raise the zero division error here we go and yes we've got that please do not divide by zero it never reaches the else but if we go ahead and divide by one instead so we should not have an error and then we run our code then we get our response here which 2.0 and then we have no errors so we made it to the else block now one additional thing we can add here is a finally now in the finally block this is going to happen no matter what if we have an error this will still reach the finally block and if we don't have an error it will also reach the finally box so I'm going to say print and inside of our print I'm just going to say I'm going to print with or without out and error so either way we run our code now and we get I'm going to print with or without an error and if we switch this back to zero save the file run once again we get our please do not divide by zero message from our zero division error and we still get the print statement from our finally block as well now I mentioned a catch-all could be bad if we didn't get the information about the error but there is a way to handle this so let's go ahead and add that after we're catching the specific errors here we can say accept and then we're going to say exception with a capital e as error now inside of this block we will print the error so let's test that out now by coming back up to our try block here and I'm just going to comment out the division by zero but I'll leave it there for you in case you want to get the source code from the link to the course resources and now I'm going to say if not type and let's see X and then we'll go is string because it's currently an integer so it's not going to be type string this should make it to this if statement then or what's inside the block and we'll say raise and now we can raise a type error this is a built-in error so you can raise one of the built-in python errors on your own and with this type error we're going to say only strings are allowed and we'll save this and now let's see how we catch this it should catch down in our accept exception as error and print the error let's see what happens yes we get our only strings our allowed message from the type error and now notice we didn't have to pass this in I'll just temporarily say control X here to cut that out I want to paste it back in after I give you this example let's run this code one more time without that message in there and now we don't get anything at all so really what we want to do is put a message in there so we can know and we could even say type error only strings are allowed if we wanted to state that but it's just going to be good to give some type of information when you raise an error on your own so now I'm going to comment out these two lines and let's look briefly at creating a custom exception and we can get more specific but I want to give a generic way first and this is to just say raise exception and then we can pass in a message and I'm just going to say I'm a custom exception and we'll save that now this should automatically raise this exception so when we run the code that's what we get I'm a custom exception right here inside of the terminal but you don't often see a generic exception like this often the exceptions are named to specify what we expect that exception to be so if you're creating a custom one you can still give it a custom name and it should be descriptive so we could say something like not a string error or something like that I'm going to say and by the way they start out with class I'm going to say just not cool error and now of course this doesn't really describe much but it's just an example so all hi just not cool error which is a class and then you must pass in exception right here as well after this I'm just going to say pass we won't have any specific code to this error but now or this exception but now I can raise this so I'm going to copy this and instead of raise exception which I will comment out here so that is commented out now let's raise are just not cool air and now we can pass in a message and say this just isn't cool man and now we're ready to run the code once again and we'll see what we get over here and we get this just isn't cool man so we've created our own custom exception with our just not cool error and with that that's really all you need to know to catch exceptions or to create your own when you need them and I wanted to show you this before the oop practice project because we will be creating one of our own now that said remember to wrap at least a try block around what you're trying to do and then at a minimum you'll need one except even if you're just catching each exception as error but if you expect specific ones that are possibilities it is good to of course create those as well remember else is only going to happen if there are no exceptions and finally is going to happen whether there are exceptions or not these aren't required but you can add else and finally to your try except box I've got vs code open I have a folder for lesson 20 over here on the left and two lessons ago we covered python classes and objects and in the last lesson we learned about python exception handling so today we'll take what we learned from both of those lessons and complete a python pack practice project try saying that three times fast python practice project using object-oriented programming or oop if you will so let's start by creating a bank accounts file so I'll have a new file I'll name this Bank underscore accounts.pi now this file is going to hold the classes for several different types of bank accounts but let's start by just creating our first class which will be bank account so I'll type class and then bank account now inside of this bank account class we'll start with our init function and remember that's two underscores and then a knit and two more underscores and it will receive self and then it needs to receive an initial amount to where opening our bank account with so I'll type initial amount here and then also let's give this an account name that it receives and then inside this initializer function we'll say self dot balance equals the initial amount and then we'll also say self.name equals the account name that it receives and then we're going to print some output here just to get some output when we open our bank account so we'll say print let's make this an F string and inside the string we'll start with a line break so we start on a new line and I'll say account and then inside of this we're going to wrap this in single quotes we'll say self dot name and then another single quote and then we'll say created put a period another new line and now let's say balance equals and a dollar sign because this will be in US Dollars and we'll say self Dot balance and I'm going to press alt Z to wrap this down to the next line as it starts to get longer and then we'll format this so we put a colon and we'll put a dot 2f so that means we'll have two decimal points in our self.balance and that would represent the sense if there were any sense to go along with our dollars and that's all we need to open an account so let's save this file and now in our file tree let's create another file and let's call this oop underscore project dot pi and in this file we're going to import everything from our bank accounts file so we'll do that with from Bank underscore accounts import and then we'll put an asterisk which stands for all and then I'm going to create an instance of a bank account so I'll say Dave equals bank account and we'll start our bank account with one thousand dollars and we'll name the bank account Dave and let's go ahead and create a second bank account so I'll do shift alt and the down arrow to copy that down I'll double click Dave which selects the first one here on line four and then control D now I've selected both and I'll just type Sarah and it will chain Sarah with an a at the end and it will just change the name on both now let's go ahead and change Sarah's deposit amount here that she starts her account with and she'll get two thousand dollars to start her account so now let's save this file and let's go ahead and from the drop down menu choose run python file and you can see we've got a message here that says account Dave created balance equals one thousand and then account Sarah created balance equals two thousand now I want to change this view so this appears on the right so we should be able to go to view appearance and as I have done in previous tutorials choose oh it's panel position and then choose right and now this is over here on the right our code in the middle and we see our file Tree on the left now we're not going to add any more files so we can go ahead and press Ctrl control B to hide that file tree and have a little more room for our code and we can switch between the files at the tabs here at the top so now let's go back to bank accounts and let's add a method to our class and let's call this method get balance and it's going to receive self and that's all it needs to have because it's just going to Output the balance of the account so we'll say print make this another F string and inside of this we'll once again start with a new line and then we'll say account and we'll say self.name so it names the account and of course another single quote Oh we need a single quote to start with I said another and we didn't put the first one there we go so we're just wrapping that in single quotes in the output as we see over here where it says account Dave and account Sarah so after account and the name then we'll just say balance equals we'll have a dollar sign and now we'll essentially have the same thing that we had up here so we could just copy this where we had self.balance and we format it to have two decimals so I did copy C and now our control C and then control V to paste and so that is our method get balance now let's go ahead and call that over in our oop project file so just underneath where we opened our accounts I'm going to type Dave dot get balance and call that I'll copy that down with shift alt and the down arrow and we'll also get the balance for Sarah's account now let's save the file and let's once again run this file and now I need this just a little bit wider so it doesn't wrap down there we go so now we create both accounts and then we get the balance for each account with our get balance method now let's go back to the bank accounts class once again and let's add a deposit method so we'll say def deposit is going to receive self and it's also going to receive an amount so whatever the amount of the deposit is here we'll say self Dot balance and we'll set that equal to self dot balance plus the amount that we've received now I'm going to copy our print statement from above where we get the balance and I'll paste it below once again Ctrl C and then control V but I want to add just a little bit so before we have the account balance I'm also going to say deposit complete and then go ahead and save now essentially we're getting the balance once again so if you wanted to just have a print statement that said deposit complete and then we call get balance we could do that also so how about we do that since it looks like the same thing from above let's go ahead and delete what we were going to print we can get this all on one line and it doesn't really even need to be an F string here because we're not inserting anything and it looks like I need a quote right here at the end of our print statement but after that we could go ahead and call get balance as well and here we're going to do this with self dot get balance let's go ahead and save this method and now let's run the file with our oop project but we first of course need to call the method so I'm going to say Sarah and now let's deposit and now we need to pass in a value we're going to deposit so let's deposit an extra 500 into Sarah's account we'll save that let's go ahead and run the python file and now we have deposit complete and it went ahead and called the get balance method once again so we can see Sarah now has twenty five hundred dollars in her account now we need to go back to the bank accounts file and we need to add a withdraw method however this gets a little more complex because anytime you withdraw money you need to do a balance check to see if you have enough money or enough funds to complete the transaction so for this we're going to need to add a separate method called viable transaction which will make sure the transaction can be completed before we go ahead and complete it and because of this we're also going to want to create a custom error that I'm going to name balance exception so let's scroll to the top of our file and just above our class bank account let's create another class that I'll call balance exception and it's going to receive an exception and then inside this class I'm just going to say pass because we won't put anything extra here but this is a very descriptive exception because we're going to have a problem with the balance if we don't have enough funds to complete the transaction so now let's scroll back down underneath the deposit method and let's add our viable transaction method that we're going to need to use inside of our withdraw method so I'm going to call this viable transaction and then it's going to receive self and the amount and then because of this we'll say if self dot balance is greater than or equal to the amount then we can go ahead and complete the transaction so we'll just return but otherwise we'll just have an else we're going to raise the exception so this will be the balance exception and inside of this I'm going to put an F string let me go ahead and close the terminal now so we have a little more room to read this F string say F and then inside of this slash in for a new line and sorry account and now we can put self name but I want that in single quotes again self dot name another single quote after that only as a balance of and now let's put in our self dot balance and our format here of two decimals and it looks like we're pretty much complete we just need our closing parentheses there no we actually have the closing parentheses down below sorry I just put that on separate lines so that is our balance exception and the message that goes along with it which remember we created the class above and now we're just passing in a message with the exception here as we raise it inside of the viable transaction method and we're going to use this method in our withdraw method so now let's create the withdraw method so just underneath this we'll say Def and have our withdraw and it's going to receive self and an amount as well I'm going to scroll for just a little more room here and now inside this method we're going to start with a try because we also want to catch an error if we actually raise that exception so we'll have self Dot viabletransaction and we'll pass in the amount now here's where an exception could be raised and we'll want to catch that below if we have that occur so we will handle that in just a moment but now let's go ahead and say self dot balance is going to equal self dot balance minus the amount so we're beginning the withdrawal here because if we make it past this self.viable transaction and an error is not raised or an exception is not raised then we will make it onto this line because then it will be okay to go ahead and complete the withdrawal so now we'll say print and we'll have a new line here and we'll say withdraw complete now on the next line we can go ahead and say self dot get balance once again to show the balance after with the withdraw is complete but now after our try we can have our accept this will be a balance exception as error now inside this accept block we'll just print and this can be an F string and here we'll just say withdraw interrupted there we go spelled that correctly and we can go ahead and pass in the error message right here as well which of course already starts on a new line so I didn't put a new line there to go with it so this will print out withdraw interrupted and then of course fill in this information right here that goes along with the balance exception now let's head back to our oop project file and underneath the deposit for Sarah let's go ahead and say Dave withdraw and let's withdraw an amount we don't have like ten thousand dollars here we'll go ahead and run this file once again and we can see bring this over just a little bit but sorry the withdraw is interrupted there it says sorry account Dave only has a balance of one thousand dollars maybe I could bring this in a little bit so it reads better it's not wrapping too well there we go so sorry account Dave only has a balance of one thousand dollars so we raised our error and it did work as expected now let's go ahead and add a withdrawal that will work so Dave withdraw and let's just withdraw ten dollars now and let's run this file once again and now it says withdraw complete and account Dave has a balance of 990 dollars because if you remember up above we opened the account with one thousand dollars now let's finish our first a class here our bank account class let's finish this with a transfer method where we could transfer money from one account to another and this method is going to also check for a viable transaction because we'll need to withdraw money from one account and then deposit it into another so it's also going to call those methods so I'm going to once again scroll up for a little more room here and we'll start our transfer method so we'll say def transfer it's going to receive sell it's going to receive the amount and it's going to receive the account that we want to transfer money to once again start with a try block I'm going to print and I'm going to start a new line and I'm going to make it rather obvious that we're starting a transfer here so four five six seven eight nine ten I'll put 10 asterisks and then I'll put two new lines and I'm going to say beginning transfer a couple of dots and then I'm on Windows you can pull up an emoji however you want to on your operating system but on Windows I can press the Windows key and the period and my emoji selector comes up I'm going to type rocket and I'll just put a rocket here for our beginning message now after the transfer begins then I'm going to say self Dot viabletransaction and pass in the amount so we make sure that it is a viable transaction that can proceed and we'll say self dot withdraw and we'll pass in the amount once again and then we're going to say account this is the account we passed in that we're transferring money to and we'll call the deposit method on that account and we'll pass in the same amount there that has been withdrawn from the other account then we're going to print and here we'll say slash in with a new line once again and then transfer complete and I'll put an exclamation mark once again bringing up my Emojis I want to use a check mark here as well so now we have our full transfer complete message let's go ahead and put some more asterisks at the end of this too so I'll do a couple of new lines and then one two three four five six seven eight nine ten once again just to match that beginning message so there's our full try and then we have our accept as well and this will be accept balance exception as error and inside the accept block we will print I'll have an F string here and then we'll say transfer interrupted and I'll once again pull up my Emojis and I want an X I'm just going to use a red X there so it's obvious itches our attention and I'll close my emoji selector space over and we're going to pass the error into the string as well so we get the message from the error now let's go back to our oop project and then let's transfer some money so I'm going to say Dave dot transfer and first I'm going to try to transfer ten thousand dollars once again which should trigger our transfer error now not the withdraw interrupted but we should see transfer interrupted let's try that out so we'll run the file and clearly I forgot to pass in what else was needed which is the second account I need to actually transfer this to Sarah so I'm transferring ten thousand dollars to Sarah's account so we had an error when we didn't pass in the other param that was needed here so now let's go ahead and save this file once again run this and yes we had beginning transfer but then the transfer was interrupted and it says sorry account Dave only has a balance of 990 dollars so no way we could transfer ten thousand dollars let me do shift alt and the down arrow and change that transfer to 100 that we're going to send to Sarah so we'll see the beginning transfer and the transfer interrupted again but then after that we're going to look for a successful transfer let's run the file again and yes so above the transfer was interrupted but now here is a full transfer so we have beginning transfer then the withdrawal is complete because we call the withdrawal method and now it shows Dave has a balance of 890 and then it says deposit complete and it shows Sarah has a balance of 2600 and finally it says transfer complete and we have completed our main bank account class but now let's go back to the bank accounts file and let's start a new class so underneath this we're going to create another class and this one is going to use inheritance from the bank account class and this is going to be an interest rewards account and I'll abbreviate account like that and then we're going to pass in bank account which is the parent that we're going to inherit from now there will be no new properties so we don't need to create a new initializer at the top our init function but we are going to overwrite the deposit method because any deposit in this account gets an added five percent to the amount that's going in as the deposit that's the rewards so here let's say def deposit once again and we can see Visual Studio code wanted to fill everything out for us so it's already returning and calling super as the deposit amount that's very nice but that's not exactly what we want so I'm going to delete this second line that vs code added for me automatically instead I'm going to say self dot balance is going to equal self.balance and then I'm going to say Plus the amount that we're passing in but if we want to add five percent to the amount we don't want to just add the amount so let's go ahead and put a parenthesis here just to indicate our order of operations and we'll say amount times 1.05 which would actually add that five percent I'll close the terminal window over here again so this can stay on one line so we're not just adding the amount to the balance but we're adding an additional five percent to that amount after we do that we can say print and then we'll just we don't need an F string we'll just have a line here that says deposit complete and then on the next line we should be able to go ahead and say self dot get balance once again and this is really all we need for our new class because it should inherit everything else from the parent class bank account so we were just overriding the deposit so now it has the interest rewards added let's go back to the oop project file and let's try this out so first let's start by creating a new interest rewards account for Jim so I need to say interest rewards account now we're going to open this with a thousand dollars for Jim also and we'll name the account Jim I'll scroll up for some more room underneath opening the new account let's go ahead and call Jim get balance so we can check that method out then let's also say gym dot deposit which remember is also going to use get balance in there but we'll just pass in an extra hundred dollars to Jim so we should have eleven hundred dollars but also another five percent of one hundred dollars so at this point when we check the result we should be looking for 1105 dollars in Jim's account after that deposit because he would get a reward then let's go ahead and say Jim dot transfer and Jim will transfer one hundred dollars to Dave now the transfer method if you remember not only uses the deposit method but it also uses the withdraw methods so that should also indicate that those methods are working so let's save this and run our file once again okay let's scroll up so we can see where everything starts here and we have account gym created with one thousand dollars and now we got the balance which was one thousand dollars and then Jim deposits another one hundred dollars and with his rewards account he gets an extra five dollars which is an extra five percent of that one hundred so now Jim has one thousand one hundred and five dollars then Jim transfers one hundred dollars to Dave so we begin in the transfer it says the withdrawal is complete and then account gym has one thousand and five dollars instead of one thousand one hundred and five dollars and now the deposit is complete for Dave Dave doesn't have a rewards account so he just gets the one hundred dollars on that transfer deposit and it's back up to nine hundred and ninety dollars and then the transfer is complete so everything with our interest rewards account worked as expected and you can see it has all of the methods that it inherited from the bank account class now let's go back to the bank accounts page one more time and we have our interest rewards account class here and underneath this we're going to create one last class so let's call this class and here I'm going to say savings account now savings account is going to inherit from an interest rewards account I'm going to scroll up for a little more room here now our savings account is going to add another property to the class called fee and so in order to do this we are going to need to Define that init method for the class again and then we'll use super to bring in everything from the parent class and the parent class as we mentioned is an interest rewards account so let's start here just underneath and we'll say Def and then we'll put in our init method which will receive self it will receive an initial amount as our parent class bank account did which is actually a grandparent going up two levels there and then underneath here we'll go ahead and call that super function and then we'll have a knit after it and now we put in initial amount once again and after initial amount we'll also put in account name now no uh no colon after that I accidentally typed that for a second but no colon there and then we'll add our new property which is self dot fee and there's going to be a five dollar fee for any withdraw from this account now this is inheriting from the interest rewards account and it's a savings account so also any deposit will get that additional five percent just like Jim's account did when he had an interest rewards account however it's a savings account so anything withdrawn from this account is going to have a five dollar fee on every withdrawal so to do that we need to go ahead and override the withdraw method by adding a new withdraw method here so this is going to receive self and amount and now inside the withdraw method we're going to have a try we'll start with checking to see if we once again have a viable transaction so we're going to have the amount plus self dot fee because that would be the total amount withdrawn let me go ahead and close our terminal once again so we're not just checking the amount so this is a little bit different than the initial withdrawal method that we had above in that bank account class after this we're going to set the self dot balance equal to self dot balance minus the amount plus the fee that is added on so that total needs to be withdrawn from the balance then we can print and we'll start with a new line once again and we'll say withdraw complete and then after that we should once again call the balance with self.getbalance and we'll find out what the new balance is after that withdrawal is complete but if it's not a viable transaction we once again need to catch the error or the exception that is raised so we'll say accept balance exception as error now we will print and here we will have an F string we'll have slash in for a new line and then we'll say withdraw interrupted and then after that oh let's not put a period let's put a colon and we'll print out the error message as well now we can save this file and check it out I'm going to go back to the oop project file and underneath Jim let's create a new account for Blaze and Blaze is going to have a savings account and let's go ahead and pass in one thousand dollars when Blaze opens his account let me make sure I abbreviated savings account right if I look at the class yes savings account so that needs to match up we did call the right class there so we're creating an instance of a savings account so it starts with a thousand dollars for Blaze and then we'll say blaze and we'll once again check the get balance method there which is also called when we make a deposit and let's go ahead and make a deposit for 100 just like we did for Jim and finally we'll say blaze and transfer and we'll try to transfer ten thousand dollars to Sarah and let's go ahead and save the file and we'll run the file and see what we get for output so let's drag this over just a little bit more there we go let's scroll up here where we go ahead and create the account for Blaze here it is Blaze account Blaze created and then the balance is one thousand dollars then we called the get balance method you can see has one thousand dollars and then we deposited 100 and since he also has a savings account that inherited from the interest rewards account just like Jim he gets that extra five percent so now he has one thousand one hundred and five dollars and then we begin the transfer but it is interrupted because Blaze had 1105 dollars and he could not transfer ten thousand dollars to Sarah so we get the message that Blaze only has a balance of 1 105 so instead of transferring ten thousand that let's go ahead and bump that back to 1000 and now we can save and run this again we'll once again have a transfer interrupted but then we should have a successful transfer so let's check that out here it was interrupted but now here's the successful transfer we get the beginning transfer the withdrawal is complete and now Blaze only has a balance of one hundred dollars because he had one thousand one hundred and five dollars but he has a savings account so also that five dollar fee applied and it took away the five dollars with the fee and then he transferred a thousand dollars leaving Blaze with one hundred dollars then the deposit is complete and Sarah now has a nice bank account with three thousand six hundred dollars and we get the transfer complete message okay I think you're getting the idea overall now we've created three classes here and we've used inheritance as we've created them and then we've also added a new property to one class and we have used a couple of methods more than once essentially overriding one to add some new functionality as these classes needed the that new functionality now these could be used in a larger banking or part of a personal finance program for example but this is where we're going to go ahead and stop this oop practice project but I hope it has helped you review everything we've learned about python objects and classes as we move forward I've got vs code open and a new folder to the left for lesson 21. we're learning about two related things today python virtual environments and also pip pip is an acronym for preferred installer program or some have said pip installs packages so let's start with Pip so pip lets us install packages in our programs that are not already included in Python like the math module and other modules that we've used in previous lessons so let's look at how to do that now pip is already included with python so you should have it after we've installed now I have a terminal window open I press Ctrl and the back tick to open that up and from here we could type normally I guess you would type pip install and then the package name one package that's popular that we can work with today is called requests so you could do that but if you get an error and I would get an error if I entered this right now or at least my antivirus doesn't like it it I need to go ahead and type my python command which for me on Windows is pi it might be python3 for you on Mac or Linux for example and then Dash M which just means module and I'm launching the module pip to install requests now I've already got this installed so you may see a different message than I do when I press enter but let's go ahead and press enter it should install this onto our computer now you might get a longer message if you didn't have that installed because mine says requirement already satisfied so just remember if the PIP let me find it here again pip install requests I'll just type it out if that doesn't work for you remember to just go ahead and use the python command first with the dash m flag for module like I did there so you've got Pi Dash M pip install requests okay now that we have that installed where did it install well it's a global install so it's available to all of our python projects and you'll want to remember that for the future because we're going to come back to it when we discuss virtual environments now you can list all of the packages you've installed with Pip with Pip list so once again I need to start with pi Dash M and then I'll say pip list and this will list everything that I've got installed here which is quite a few on my computer that are installed globally but we'll once again come back to that with a virtual environment but remember the command pip list when you want to see everything that you've installed with Pitt now you can also install a specific version notice all of the different packages have versions over here so if I scroll up and find requests here it is let's see requests it's at version 2.31.0 well maybe I want 2.30 I could go ahead and install that with Pip install requests and then I'll set that equal to 2.30.0 press enter and yep my computer doesn't like it without the pi Dash M let me go ahead and try that again and I'll press the arrow up to just bring that back up and at the beginning I'm going to add Pi Dash M and then pip install requests 2.30.0 I'll go ahead and do this and it says the requirement is already filled for most of it but then here at the end it went ahead and uninstalled 2.31 and now it says it successfully installed 2.30 so let's once again look at pip list and we'll see what version we have now listed here in our list of all of our packages and you can see request is now at 2.30 so now I have an old version of the package and maybe I need to update it or I decide I want to update it so I'm going to once again say pip install and then I'm going to use the dash capital u flag put request back and it's going to update my request package to whatever the current release is so when I enter this it should now go back to 2.31 and now as you might expect you can also uninstall so let me go ahead and issue an uninstall command here with Pip uninstall and I'll say request now I don't really want to uninstall this but I'm just going to show you how it works so I'll press enter and it says do I want to proceed yes or no so at least it gives you a confirmation before it goes ahead and uninstalls I'm just going to press n for no and press enter now you could do the Y to see what it's like and then reinstall if you want to as well okay now you've got a good idea of what pip is all about it helps us install packages that are not already installed by default with python and now that you know this let's talk about why virtual environments exist so it's not unusual to have more than one python application already running on your computer and that's also not unusual to have a situation where one python app needs a specific version of a module and then another python app needs a different version of that same module so how can you provide two versions of the same module well remember we said pip installs updates globally so that can impact fact every Python program so how do we get around that what we do with virtual environments they're a solution to this issue and you use them in development but you don't include them in your git repositories or send them to GitHub so just note that you won't see any virtual environment files from this tutorial in the code repository for this lesson because I'm not going to send those to GitHub so we use Virtual environments with a project let's go ahead and create a small project that will allow us to demonstrate everything we're learning today I've already got the lesson 21 folder so now let's bring the terminal back up with control and backtick and we can go ahead and create a virtual environment I'll start with my python command then Dash M and then v e n v which is the virtual environment program that's going to help us create our virtual environment we're going to name it dot v e n v now you'll see this will create a folder inside of our project I'll just go ahead and press enter and notice we now have a folder over here in the left that's dot v e n v that's our virtual environment but we still need to activate our virtual environment so to do that we'll type source and then I need to type dot venv for the folder and then inside of this folder let me go ahead and expand it's got a scripts folder and inside of there it's got activate dot bat and an another activate file and so on but we're just going to call activate and what we need to do then is specify scripts and then activate if I spell activate correctly now this will go ahead and start our virtual environment notice now after I pressed enter we see in parentheses down here dot v e n v we're inside of an active virtual environment now I'll press enter again and you'll notice that once again ends with that dot venv inside of parentheses that's how you know it is activated now it's important to remember how to activate it because you're going to need to do that every time you come back to work on your project let's say you've closed this folder out and opened another project then you come back you're going to want to activate your virtual environment every time you're working on the project so you're not in the global environment now it's important to know you can also deactivate it and all you have to do for that is type deactivate so I'll do that and press enter and notice we don't have the parentheses and the dot venv anymore and if I press enter it still won't be there so now we're back in the global environment so I can use my arrow keys and just Arrow back up to the previous commands if I want to activate or deactivate right now but right now remember I have that big long list of packages that are in my global environment with Pip we can look at that again with pi Dash M and pip list so here is a long list of the global packages I have now let's go ahead and activate our virtual environment is now activated and now I'm not going to get an error on my computer if I just use pip instead of typing Pi Dash M now so now in the virtual environment you'll see me just do pip list and I don't have much because we just started our environment so we just have the basics right now inside of our virtual environment and notice it also says a new release of pip is available 22.3.1 should go up to 23.1.2 and it tells us how we could execute this as well so let's go ahead and do that now I can just use my Pi command here instead of python.exe then I'll say Dash M and then I'm going to say pip install we could use the two dashes and the word upgrade or you could use the one dash in the capital u like I showed you which means the same thing and then we'll just say pip and it should go ahead and update that for us and now it says we're at 23.1.2 and we should be able to say pip list now let's go ahead and install some packages that we can use with our small project that we're going to create so let's install requests once again and we're going to need this in our virtual environment we already have it in the global but that's not going to be for this project now we're going to just use a virtual environment for this project so let's install that with I'll say Pi Dash M and then pip install requests and now it should install that and we can check that to see if it's on our virtual environment with Pip list and now notice it installed several other things it didn't just install requests so this package requests has some of its own dependencies and we can see the details about any package if we use the show command so I'll say PIP show requests and now we get some details here so it says this also requires and it lists these other packages that it requires and notice those were installed and we should also be able to see those listed up here in the lib and then site packages folder and we see several things that were installed here as well now there's one more package I want to use today so I'm going to say Pi Dash M and then pip install and it's going to be python dash dot EnV go ahead and install this package as well and you could check to make sure it's installed with Pip list if you want to I'm confident that it's already there it says it is successfully installed I've temporarily opened up a web browser here and we're at Pi Pi which is p y p i dot org and this is the website that has the python package index and this is where you can search for these packages to use inside of your application so if you're wondering where I could find quests or learn about python-env that we just installed or many other packages go ahead and search for projects here on the python package index back in vs code now that we've installed these other packages we need let's once again look at our pip list so I'll say pip list and we'll see everything that's installed here in our virtual environment now these are the dependencies for our project and while I said we will not want to include our virtual environment files inside of any GitHub repository we can go ahead and include a list of requirements and we should create that so let's type I'll start once again with pi Dash M and then pip now freeze that's a new command so pip freeze then do a greater than sign and then put requirements dot txt so we're going to create a text file with the requirements in it let's go ahead and press enter and we should see this show up over here in our file tree and if I close the terminal we can see it lists all of the dependencies here for our project or if you want to use another word instead of dependencies it lists all the requirements for our project now as I've said I don't want dot v e n v the folder or anything inside of it inside of our GitHub repository or my GitHub repository for the course files as well so I'm going to create another file here called dot with a period first get ignore now this works with Git and GitHub and I'm going to list the dot venv folder inside of it and save this file so that way when I create a repository or when you would initialize a repository for your project using git if you know git if not I do have tutorials about that on my YouTube channel as well but this way it will make sure this folder or dot venv is not included in that git repository with the rest of the source code but we've left a requirements.txt that will tell everybody what should be installed to run the project and speaking of our project we haven't even created a python file yet so let's go ahead and do that and we'll name it weather dot Pi now we're going to create a simple program that goes on the internet and requests the weather from a service and of course Returns the current weather to us and we're going to be able to request the weather from any City that we want to so let's learn how to do that in the browser I'm at openweathermap.org and here you need to go ahead and just sign up for a free account I've already done so so I have my name up here in the top right once you have signed up for that free account and I believe you'll have to confirm your email probably and there may be a slight waiting period as well so no no rush but once you have all of that complete come back to the video and now I'm going to assume that is complete and you're back to the video and you've signed up for your own openweathermap.org free account from here you want to click your name in the top right and choose my API Keys now don't worry about seeing my API keys because I'm going to delete them after this tutorial and I can create new ones notice the generate button over here so I'm just going to use one that I have you're going to probably want to generate one or if you have a default one you can copy either way just double-click one of the API keys that you either generate or that you already have and Ctrl C to copy that now back in vs code let's create one more new file and it's going to be named dot EnV which dot means once again that it starts with a period now inside of this file I'm going to use all caps and say API underscore key equals I'm going to say control V or use Ctrl V to paste in that API key notice there's no quotes and they're not needed inside of this file this is our environment variable file and we use this in development this is another file that we never want to send to GitHub because it contains our secrets and we don't want to share those in a code repository on GitHub if you ever deploy an application on the web your host will allow you to insert the environment variables in spaces they have provided on the host for the website for example so you would take this value and take it to your host so you never include that in GitHub but you do use it during development in a DOT EnV file and that's what we're doing today so let's go to our get ignore file and besides the dot venv that's listed we also want to list dot EnV lowercase make sure it matches and save so you will not see the dot EnV file inside of my code repository for this lesson either back in the browser at openweathermap.org let's go ahead and click on API in the very top nav bar and once you're at API we need to scroll down and we're going to go to the current weather data API docs so click on API doc by current weather data now that we're here we see a URL that they're providing us where we can request weather data from and we're going to modify this just a little because we can provide a city name instead of the latitude and longitude one other thing we're going to do is use a unit of measure so let's go ahead and highlight this much and we'll just modify it so Ctrl C to copy this specific URL now I said we're going to use a unit of measure so over on the right hand side click units of measure now you'll probably want to apply whatever unit of measure you're used to for the weather I'm used to the Imperial because I'm used to seeing my temperature in Fahrenheit or temperature in celsius it says use metric and they use Kelvin by default so I'm going to set the units equal to Imperial you possibly want units equal to metric depending on where you live and now we're back in vs code I'm going to type a variable quickly named request underscore URL set this equal to a simple string right now and paste in that URL that we got from the openweathermap.org website I'm also going to press alt Z so it wraps down and we can see everything and now of course we're going to modify this but I'm just going to start from the top I just wanted to get that pasted in first oh and let's go ahead and add that last thing the unit as well so we'll say and which is an ampersand symbol there and now we'll say units and then we'll put it equal to Imperial and of course I'm having some trouble typing make sure you do not have a typo or it may not work so I added this final parameter on the URL and mine is going to be units equals Imperial we will come back and fix the rest of the URL but let's start at the top with our Imports so we're going to import requests and after requests let's say from dot EnV import load underscore dot EnV that's going to help us get our environment variable value we're also going to need to import OS which is of course built right into Python and now we need to call load.env and that's going to load in those environment variables so we can retrieve them and we only have the one which is the API key but it's still important to call this first and that way it will be available for us and now I'm going to create a function so we'll say Def and then we'll call this get underscore current underscore weather and then inside the function we'll go ahead and start with a line that is just a print and we'll do a new line let's do three asterisks for example and then say get current weather conditions and three more asterisks and another new line that is just our welcome message when the function is called after that we're going to need a city value so we can get the weather for whatever City we want and we'll create an input there we'll once again have a new line and then we'll just say please enter a city name and after that we could put another line break yeah let's go ahead and do that so one more line break there we can just space things out nicely and after we get that city name is where we're going to need this request URL of course we're going to have to insert the city name into it so now let's go ahead and fix our request URL everything we see before the line break is fine so everything we have here to weather is good and then you start the params with the question mark in a URL and we are not going to provide latitude or longitude however we are going to provide some City information so let me delete this Ampersand as well because the API key could be the first thing we apply here and we have to pass it as the app ID but this won't work just saying API key in there and likewise this also needs to be an F string so let's go ahead and put the F here which will allow us to insert those values so now I'm going to say OS dot get underscore EnV oh and I'm sorry there is no underscores get EnV without the underscore and now we can specify that variable name which was API key that we have inside of our DOT EnV over here so there is the variable name and we have now specified it and we use OS dot get EnV to get that and we loaded those values from that file with the load underscore.env but notice we haven't entered our city yet so before units let's go ahead and add another Ampersand here and here we just put a q which is an abbreviation in their API system for query I believe what we want to pass in here is the city and we'll just wrap that in curly brackets and then we have the final Ampersand and for mine units equal Imperial so that's the full request URL now let's go ahead and print request underscore URL and we'll just make sure that it's putting out what we expect it to so this will make sure you're not missing any values if we go ahead and test it that way so underneath this we can call our function with get current weather and that should go ahead and launch when we run the file so now let's go ahead and choose run python file and we have get current weather conditions please enter a city name so I'm going to say Kansas City press enter and here is what was output so here's the full URL and then we go ahead and get the app ID param and it's equal to that API key then we have another Ampersand which means there's going to be another param and this is the query which is Q equals Kansas City and then finally we have another Ampersand units equals Imperial so this looks like what I want although I'm a little concerned the Kansas Space City the space might create an issue we'll see if it goes ahead and works or not when we enter a city name with a space like New York or Kansas City or New Orleans or Los Angeles and so on okay I'm going to close the terminal and let's finish out this program we no longer need to print that request URL so I'll comment that out so just leave it in there for you in the source code for this lesson if you want it now let's set our weather underscore data equal to requests now we're using that request package that we installed dot get we're passing in the request underscore URL and then we want a Json format of data so Json is a string that is sent in an object kind of format if you're not familiar with Json I don't want to explain it all right now but it's the way data is sent back and forth on the web for many many applications and that's how we want to receive this so we'll see what that looks like when we go ahead and print the weather underscore data now when we call that function so let's save the file once again with control s and now I'll run the file and let's try this out and let's enter another city name that has a space just to see if it's going to work with that so yes it did work and this is what Json looks like and it doesn't read too easily in the terminal like this so maybe we want to add something else that will help us read it as well so now let's close this I'm going to scroll back to the top we're going to have one more import and that's going to be oops from EP print so what it stands for pretty print but it's just not saying the word pretty so we have P print actually and then import e print and now we'll come down here and we'll use that on the weather data so instead of just print it's going to be ePrint for pretty print let's save and let's run that once again happy to see the space inside of the name New York did not create a problem so let's run this for Kansas City again and press enter and now yes this is much easier to read than it was before the pretty print definitely helped out so we can see here is all of the information and the Json starts right here as an object and here's all of the data so we've got our Fields like and there is my temperature in Fahrenheit for Kansas City here's the current temperature which is almost the same has a lot of other details as well here in weather description is clear sky so we can get all of this from this object from the Json if we know how to access these values now let's once again close the terminal and let's go ahead and make this a legitimate module if we say if underscore name underscore twice once again equals two underscores main two underscores then we will call the function if not we could possibly import this as a module into another file if we wanted to as well I'm going to go ahead and comment this out but once again leave it in here with the pretty print just so you know how you can easily read that Json data if you want to and I will of course leave this import here at the top even though we're not using it with it being commented out let's go ahead and print out some more readable information for anyone that would use this module so I'll say print and now let's say let's just give a string for each value here so they need to be F strings and this is going to be whether or I should say current weather right current weather 4 and this is where we would insert our value so it's always going to reference the weather data variable that we get and now we just need to reference what's inside that Json well one of the properties was and let me get it right here we need a bracket first and then the name of the property one of the properties was named so this would say current weather for Kansas City for example now I need to go ahead and put in line breaks once again so I'm going to do a slash in to start out with so that's not right up against anything and now we put one here at the end as well or we could just wait to the next line let's wait to the next line so now let me copy this down with shift alt and the down arrow instead of current weather we'll just say the temp is and temp stands for temperature now we need to reference the main object that was in there and if you go back and look and you can do that if you open the terminal back up I'm going to reference Main and then the temp right here inside of main so main has its own object that Force main is a property and the larger object and then we're referencing temp inside of the next object so after we say main here we need another bracket quotes and list our temp now I'll copy this down and now we want the feels like so the temp is and we'll say what the temp is but then we'll say feels like and now we're going to list deals underscore like value and let's go ahead and extend this sentence right here so I'll say and and now let's enter in another value so it's once again going to be weather data and now we'll have brackets and this is inside of an array so we can look back at this but first it's actually weather and then weather is an array so we'll look back and determine this value so I want the very first element in the array so I'll save that much let's open the terminal once again and look back so it's weather now this isn't an object like main was this is an array and we want the first and only element in this array and it is an object and then we're going to reference the description here so we're saying whether first element in the weather array then we want to reference the description property of the object and finally we want to capitalize that string so I'm going to call capitalize on that at the very end but you know maybe I don't need capitalize because it's not starting the sentence it's at the end originally I thought about putting that at the beginning of the sentence so this is just our statement let's put a period at the end to make it a sentence let's go ahead and run this and see if we get some output that is more readable for most humans now we'll go ahead and run this and we've got get current weather conditions I'm going to enter in San Diego press enter and yes current weather for San Diego the temp is 76.32 feels like 76.98 and you clouds and maybe I should capitalize that and put the few clouds at the beginning because it doesn't feel like it reads quite right but it's close it's not too bad and maybe we want a line break at the end so just a couple of tweaks but overall this is our program I'll add those changes and it will be in the code repository you can add those as well and I hope you know much more about virtual environments and pip for python I've got vs code open and I have a new folder for lesson 22 over here on the left notice three files I've got names more names and contacts and inside of these files I've really just got the same thing four names one on each line and you'll see why we are using those we just need some text files to work with as we learn about working with files in Python so let's create a new file in our file tree and we'll call this files.pi I'd like to introduce an acronym and it's called rocks r-a-w-x and this stands for read append write and create you may have heard of the acronym crud before and this is very similar which crud is create read update delete but here we have read append which means the same thing as update write and create we will also learn how to delete files as we go but first we'll cover these four operations so the first one R is read and we'll start with that now if a file doesn't exist and we attempt to open it we will get an error so I'll put error if it doesn't exist just as a note here inside of our code for you now let's go ahead and open one of these files we have in our file tree and we'll just abbreviate the file with the letter F you see this fairly common you could write the word file if you want to either way it's going to hold the file and we can work with it so we'll say open and then inside of parentheses I'll just say names and S if I spell it correctly dot text and this will open the file but this has some defaults that we are not seeing and these are essentially what these are what we want to do with the file so if I put a comma here and then put an R for read that's the same thing it's still going to read the text file and if you really get into working with files you can even specify if it is for example a text file with a t or a binary file with a B we'll just be working with text files and that's probably what you'll do the most often so that's what I'll focus on today and we don't really have to specify that it's going to just have a default value for the files as t for text it also defaults to read if we don't specify that so really we don't have to put the comma and the r there and then it knows we just want to open this file in order to read it so now that we've opened the file let's go ahead and print the contents so I'm going to say print and I'll just say F dot read and call that method on the file and now let's go ahead and run our code so I will choose run python file and we get the contents of the file it just says Dave Jane Eddie and Jimmy and of course all the files have that same content I'd like to move this over to the right as we have in the past so let's go to view and then appearance then we come down to panel position and choose the right side and now we'll see our code run over here I'll still keep this open when I can or maybe toggle it with control B you can close it and reopen that file tree if we want to see what files we have over here now we should note we don't have to read the entire file so I'm going to copy this down so you can see both examples and now let's say I just want to read the first four characters of the file so I'm going to pass in the number 4 to the read method I'll run this once again and we should see just the first four characters but we see everything and that's because we already read the file so now we're at the end of the file so you understand kind of how that works work so let me comment this out now let's once again do the F which is file dot read and just get the first four characters which should just be my name Dave I'll run the file once again and now we only have Dave as the output okay I'm going to comment out that line as well and let's look at another example where we maybe want to read the entire line we don't know that there's only four letters on the first line or six letters on the third line and we just want to read the first line of the file so I'm going to once again use print so you can see what it does and instead of read I'm going to use read line and this is going to read the first line of the file so save and run the code and we once again get Dave but if I stack this now with shift alt and the down arrow I recreated that line do you think we'll get Dave twice will it read the first line twice or maybe it will go to the second line let's save the file with Ctrl s run the code and find out it went to the second line and notice there's a space between now which is different than when we were reading the entire file so that is also worth noting that you can read one line then move to the next so notice when you're reading a file just like I showed before where I had to comment this out up here when you're reading a file it moves through the file you'll eventually get to the end of the file so now I'll comment both of these out as well so I can highlight these and do control and the Slash and that will comment them both out now what I want to do is Loop through each line of the file and print those lines so that looks a little different let's say 4X and this would just be 4 we could say four lines so let's just say that four line in F which is our file then we're going to go ahead and print the line now this should Loop through and print each line let's find out when we control s to save and run our code once again again and yes it did it was just like doing F dot read line and of course we printed each one here so very similar but this is a little more concise and fairly easy to use now after we opened a file like this where we have f as an open file we should always close it when we're finished and to do that we just say f Dot close and now we won't see a difference here but it is important to close those files because it could be that you change something in the file but that change is not going to show up really until you close the file and then you wanted to reopen it then you could see that change so let's go ahead and run this code again and you'll see the same output but now we've closed the file and that's important every time we've opened a file then we do something with it then we should close that file now notice the file names we have over here on the left we have names more names and context so I'm going to try to open a file that we do not have so I'll press Ctrl B now so we can have just a little more room here but I want to show what you should do to avoid an error and we've already learned this we should use a try block and then inside this block we could say f equals and open now this could be the name of any file that doesn't exist so I'll just say name list Dot txt e and then after that I'm going to say print F dot read so I want to print the contents but I am making a mistake because this file doesn't exist so it might cause an error or it will cause an error actually because it doesn't exist so let's also print and say file you want to read doesn't exist nice little bit of a long message but a nice message to explain what's going on and then we can use our finally block and this comes in handy because this allows us to go ahead and close the file because remember we opened it before or we tried to open it before we had an error so if we don't open it at all we'll of course have the error but say the file did exist this would allow us to open it do something with it and in the finally block we could call close so it's a nice structure for that operation let's go ahead and save now let's run the code and we get the file you want to read doesn't exist so what if it did exist if we had our names.txt now let's save and run this again and now we printed the contents of those of that file rather than getting our error message the file you want to read doesn't exist we are now ready to move on to appending to files that means adding two files so I'll just paste this in it says append it creates the file if it doesn't exist so that's important to know also say we try to open a file that doesn't exist but we're opening it to append to it well it's going to create the file anyway so here I'm just going to say f equals now open and I'm going to open my names.txt file once again now I'm going to say this is to append so we need to pass in what we're doing with this file by default remember it's read so we didn't need to put in the comma and then the r in quotes but here we need the a for append I'm going to say f dot right and I'm going to write something new to the file I'll add a fifth name and that name is Neil and F Dot close so now I've added to the file but we are not really seeing what's in that file yet so let's go ahead and now read the file as well so I'm going to copy all of this down I'll highlight everything do shift alt and the down arrow we'll create one line here in between now I'm going to open this to read so I can get rid of the A and now instead of the F dot right I want F Dot read and I'm not going to try to pass anything into the read I'm going to want to print what we're reading so I see the new contents then we're going to close the file so we're appending to the file here by adding a fifth name then we're going to go ahead and open the file and read it and then once again close it so now let's run the code I'll scroll so we're way down here at the bottom to our prompt run the code and so we had our four names then we appended to the file when we opened it back up and read it again we had our five names and now we can even go to our names file and we can see Neil has been added on the fifth line of our file okay now you've already seen the right method here as I used it to write the name Neil to the end of the file on that Fifth Line however you haven't seen how we open a file for writing so let's do that now with right and really I'm going to put in parentheses here overwrite because we will overwrite whatever is in the file that we open so I'm going to say f equals open and I'm going to open my context dot text file and I'm going to pass in the W that stands for right now when we do this we'll go ahead and write something else to the file but just to confirm let's look at that context dot text file you can see that it has the four names in here that we started each file with so this is in our context dot text now let me go back to files now let's write something else to that file as well so after this I'm going to say f dot right which is not the same as opening a file for writing because remember we were able to open a file to append to it and we still use the right method so now we're going to use the right method as we opened a file to write to it and this will overwrite everything in the file I'm going to write I deleted all of the context and yeah that let's just leave it at that that's a fairly simple statement so that's what will now be in the file instead of those four names so now I'll say f Dot close and we've closed the file now once again we're going to want to read this file to confirm that what we actually put in it is there so I'll copy what we had above and now I'll paste this in and we're going to change this to read the context dot text file and then print what it finds inside the file so now let's run our code again and we have I delete I said I delete I should have said deleted I deleted all of the context so that's what was in the file let me change that to deleted or that's going to bother me let's look at the context file itself and yes it says I delete all of the context so I'll have to run that again notice what also happened when we ran the code again we added Neil one more time to our names.txt file so now it has Dave Jane Eddie Jimmy Neil Neil so every time we run this code right now we're going to add another needle to our names dot text and it might also be important to note that it didn't put that on another new line because we didn't put in a line break so if we wanted Neil to go to a new line line we would also want to put in a new line character with our slash n as we added that name to the end of the file and now let's look at a couple of ways we can create a new file so I'll put a comment here and say two ways to create a new file and each way has its own plus or minus depending how you look at it it kind of just depends what you need so here I'm going to say this opens a file for writing so you know we're going to use the W that permission and then we're going to say this also creates the file if it does not exist and I'm going to press alt Z so that wraps down to the next line just so we can see that and now I'll say f equals open and I'm going to name a file that doesn't exist I'm going to say name underscore list Dot txt and we're going to pass in the write permission so this is going to open a file for writing but if if we specify a file that doesn't exist it's going to go ahead and create the file so after we do that I'll just put F Dot close we're not really going to add anything to the file but let's see what happens when we run the code we updated our statement here but let's check the file tree to see if we have this new file and if we look over here we now have a name underscore list dot txt file we didn't write anything to the file but we opened it for writing and we specified the file even when it didn't exist so it was created now the second way to create a new file could also cause an error so I'm going to hide the file tree so we have a little more room and let me put a note with this I'll say creates the specified file but returns an error if the file exists so if we're trying to create a file that already exists this will return an error so we kind of need to check before we try to create the file so to do that we need to import OS and we're going to use that when we delete a file as well so let's import OS here at the top of our file now let's scroll back down where we were and on line 54 I'm going to say if not OS dot path dot exists now I can check to see if a file exists or not so I'm going to say if a file named dave.txt does not exist and that's what it means when we say if not and then we're checking this so if the file dave.txt does not exist then I'm going to say f equals open and will pass in Dave Dot txt and then we'll open it with X which remember means create then I'm just going to say f close now this should create a file named davetxt so let's look at the file tree as well so we'll be able to see it show up over here and we've saved the code let's go ahead and run that code and now we have a file named davetxt we didn't put anything in the file but we did create it now we can change this out as well so if you wanted to put in a file name like context.txt then it would say if it doesn't exist created you shouldn't get an error because it already exists so it shouldn't try to create it now I'm going to hide the file tree and let's use some similar logic here as we delete this file or we delete a couple of files that we don't need so I'm going to put delete a file here now here I'm going to say we can avoid an error if it doesn't exist and to do so this looks very similar we'll just say if OS dot path dot exists so notice now we're not saying if not we're saying if it does exist now what did we already create over here we've got a file with my name dave.txt and we've also got a names or name underscore list dot text if I remember right yes that didn't have anything in it either so we can delete one or both of those if we want to Here For example so I'm going to say if dave.txt exists then we're going to do something so now we'll just go ahead and say OS dot remove and then we'll pass in the name of the file dave.txt and we'll remove that file but we should put an else so we can put else and then we can say print and then here we'll say the file you wish to delete does not exist so that would say okay if the dave.txt file does not exist then we're going to get this message so let's go ahead and run this code and we'll see what happens and we've got I deleted all of the content here at the end so it must have deleted the dave.txt file we can verify that by looking at our file tree and that file is indeed gone now you could do the same thing and put in the name underscore list dot text and delete that as well if you want to because we're not really using that file either okay we have covered the operations I wanted to show you but there is one more thing let's scroll back up to the top quickly and just recap here we've looked at reading files appending files writing to files creating files and of course we also applied some checks like our try accept finally but I want to show you a way that people work with files and they don't use the try except finally instead they have some implicit exception handling and it makes this a little more concise yet so let's look at the width keyword and I'll do this here at the bottom so I'm just going to say with open and now let's open our more underscore names dot txt file and we'll say as F so once again F represents the file but this is just phrased differently it says with open as F now that we've done that we can just say the content here equals F dot read and that's not new before we were just printing F dot read and now we're just storing it inside of our content variable now after that let's go ahead and say with open and we can have another file let's look at what's inside of our files first so names has all of these names notice we've written Neil a couple of times now on new lines because we had the new line character before we put in that new line character we had three needles on one line but when this started out it looked like our more names file with just these four names so maybe we want to put our names file back to that we can read the content out of more names and then write it to names so we get it to look just like more names essentially copying the file so to do that let's go ahead and now say with I'll hide the file tree again so we have some room here I'll say with open names.txt and this is also going to be as f and now inside of this width we'll say F dot right and we're going to write that content that we stored so let's go ahead and do this and then we'll look at those files again so I'll run the code and I got an error because I wasn't thinking I was too quick and what happened was this defaults to open because it's a read we didn't specify here we need to go ahead and say we're going to open this for writing so we're going to overwrite what's in the file so we needed to pass in that W out of our rocks acronym so that W stands for opening the file as writing so now we should be able to avoid this error I'll save and run this again and yes I think we've succeeded but we're first going to have to check because we did all these other things in the file first but now let's see if the file has all of this in it or if it just looks like our more names file so if we come back more names just has these four then we read this took that content and we wrote to names which now only has the four names once again instead of all the extra neels that we had previously added to this file so I hope today's lesson has really helped you learn many different ways to work with files that will be useful for you in the future and remember the Rock's acronym r-a-w-x for read append write and create I've got vs code open you can see I have a new folder for lesson 23 the final lesson of this python series and course so it's the final project and there's so much you can do with python and there's always something new to learn but I feel like this course has provided you with all of the fundamentals you'll need to keep moving forward in your programming Journey so with today's project we're going to build this python web app with a popular python web framework called flask a couple of lessons back we learned about virtual environments and in that lesson we've retrieved current weather conditions for cities but we needed to use the terminal window today our web app will do the same it will retrieve weather conditions for cities but will deploy it to the web so you can share your project with everyone let's go back to vs code and get started in vs code let's open a terminal window with control in the backtick and we want to create our virtual environment as we've learned about before we want to do this right away so I'll type Pi if you're in a Mac or a Linux environment you might have to type python3 I believe but then we'll have Dash M for module then v e n v and then dot v e n v and I'll press enter it should create a folder over here in your folder for lesson 23 or whatever you call it and now we have a virtual environment so let's go ahead and activate that environment as well so I'm going to type Source then dot v v e n v and then scripts with a capital S now that's because I'm on Windows and I'd mention this during the lesson on creating a virtual environment but I don't think I mentioned that if you're on Linux and possibly Mac I think instead of scripts this might need to say bin as in b i n so here we'll say activate and press enter this should activate the virtual environment now I can press enter one more time and I should see yes it says Dot venu be in parentheses underneath after I pressed enter so I do know it is active and we've also learned about pip and we need to install a few packages we're going to use today so I'm going to type pip install and then after that I'm going to type requests and then python-enb because I'm going to need that as well and then also flask with a capital f okay that quickly updated it's also giving us a message about pip so if we want to run that we can so I'll type Pi Dash M then pip install Dash capital u is the same as two dashes in upgrade and then pip once again press enter and it should go ahead and update that installation as well and now we're going to deploy our project today so in order to do that we also need to create a requirements.txt file so to do that I'm going to type pip freeze and then the greater than sign then requirements Dot txt and it should quickly create a requirements file that we see over here in the tree and this should list the packages so when we deploy this of course remember we won't send our virtual environment folder to GitHub but we will send our other code including this requirement so when this is deployed and it gets to our host then the host will see what needs to be installed as we deploy our python project and so now I mentioned we will not send dot venv to GitHub so I'm going to create a git ignore file which starts with a DOT as well then get ignore and then inside of this file I'm going to list the dot venv so that is not added to a repository when we create one and if you're not familiar with Git and GitHub I do have a tutorial on my channel for that as well that you can check out now one other file we're going to create is a DOT EnV file and that's where we hold environment variables and you never want to share those those are your secrets that are linked to your account and we're going to have an account at the open weather map API so I want to type dot e n v in here as well and this will be a file we create that will hold our open weather map API key now we never want to share that with anyone so here I'm just going to create this file and say dot EnV now it's listed over here now I don't know if you have git installed or not git was not a prerequisite to take this course so if you're not familiar with getting GitHub you may not want to deploy this project to today you may want to go back and learn about git and GitHub and then come back and deploy this later now I already have git installed so I'm going to go ahead and initialize a git repository and then you'll see these files that we've included in the git ignore turn gray because they will not be sent to GitHub in the future like our other files will so I'm going to once again open the terminal and then just type get init and that will initialize my git repository here inside of this folder for our project and you can see these are green meaning that they are new files in our repository now this tutorial is not about git specifically so I don't want to get any deeper into that right now we want to go ahead and create this project but right now we need to go ahead and get an open weather map API key if you don't already have one from the previous tutorials I'm in Chrome at openweathermap.org now if you completed this just a couple of tutorials back when we got our API you can skip this part but if you haven't you're going to need an API key notice I'm already signed in up here and I've got my name Dave now you can get a free account and then sign in here if you don't have one but there's a drop menu now it says my API keys I'm going to delete any API key that I show you because you never want to share those but I'm going to click my API keys and you see I have one here called my new weather Key and here's the key so once you generate one of your own if you don't already have one in your account go ahead and copy it right here I'm just double clicking and then doing control C to copy we're going to put this in our DOT EnV file back in Visual Studio code back in vs code I'm in my DOT EnV file I'm going to type API underscore key with all caps and then equals and then control V to just paste in that API key notice no quotes around this but it will be considered a string now we'll refer to this later and I can go ahead and close all of these files out now we need to create a couple of specially named folders over here in our file tree so let's click the new folder icon let's name this first folder static and when I need lowercase now so there we go static the next folder we need to create should be called templates and so I've got templates I'll press enter and we have the two folders now first static this holds any static file that means non-changing so it can be CSS JavaScript images any type of file like that so to organize those files inside of static I usually create more folders so I'll create one inside of this called CSS because I'm going to create a CSS file inside of the static folder so I've got static CSS and then we'll eventually create a file in there as well now templates is where we're going to store our HTML files and with that we're going to insert some values from python into those HTML files and use those as templates for or our web page so let's start by creating our CSS file so I'll click on the CSS folder and I want a new file I'm going to name this style.css now this is not a CSS course I do have a CSS course on my channel and it's also been published on free codecamp so you can check that out I'm going to just paste in some very simple CSS Styles you can see I have a very simple CSS reset here if you're familiar with CSS if you're not of course you can copy this CSS code from my repository for this lesson if you want to I've got several Styles applied to the body of the HTML page and then I've got a few Styles applied specifically to the input and the button as well now if you see a white dot that means you need to save the file so I'm going to control s just to save that file now let's click on the templates folder I'm going to create a new file inside named index.html so this will be the home page that everyone sees is when they load our web app now if you're using vs code to create an HTML page you can use a shortcut here that's called Emit and Emmett has several commands I'm just going to type a exclamation mark which is an image abbreviation and with this abbreviation or shortcut if you will I can press Tab and I quickly get the outline or the skeleton if you want to say that for a web page so here's alt Z to just wrap that down so we can see the full line without going going off of the screen now I'm just going to fill in some information here so for the title I'm going to say get weather conditions and now besides that we're going to put a link to our style sheet and this is a little different even if you have written some HTML and CSS before so this is specific to how we're going to work with flask today and how it inserts some values so here I'm going to say link then I'm going to have my href and now inside of these quotes I'm going to use two curly braces and I'm going to say URL underscore 4 not form but four and then parentheses then single quotes the word static and after that I'm going to have file name equals and then I'm going to have another set of single quotes Styles slash style dot CSS so it is pulling in our CSS but this is just a little bit different than you may have written before now after these two curly braces here we need another space and we're going to type Rel which is an attribute of the link element and then we'll put equals and here we just have another set of double quotes and well we didn't finish the other double quote I guess I needed to end that double quote here sorry about that so let's delete that extra one it added so we've got a quote here with href and the href ends after the two curly braces so you want to quote there now we'll have our second set of double quotes and inside of this Rel we're going to say style sheet because that's what we're linking to and finally at the end we can have a slash and close out our link tag here so that is the full link now this is a little unusual compared to just linking to our style slash file.css but this is what flask is going to use to insert a value here because this is a template we will be inserting values into this file when it is called okay now inside of the body of our HTML we want to have an H1 and I'm going to say the same thing get weather conditions so you can just copy this from the title control C click here Ctrl V to paste it in underneath that we're going to have a simple form so we'll have our form and then it's going to have an action attribute right away so inside of this we're going to go to the slash weather page when we post our data from our form so inside of the form now we need an input and this input is going to be type text that's correct we can also give it a name equal to City and then after that let's give it an ID equal to City and I need that to go inside the quotes there we go then let's give it a placeholder like we saw in the example that says enter a city and then of course we need to close out our input tag with the slash there after that we need a button so we'll have our button and it is the submit type so vs code wants to help and now we have button type submit let's just put the word submit on the button as well control s to save and we're finished with our index.html template for our app now we will come back and create one more HTML template very soon but right now we need to create a python weather module that will retrieve the weather for any City using that open weather map API and this part's going to be very similar to what we did when we retrieved that weather and we just looked at it in the terminal window so now over in our file tree let's create a new file and let's call it weather dot Pi let's import everything we're going to use at the top so I'm going to say from dot EnV and then I'm going to import load underscore.env I'm also going to use pretty print so from ePrint I'm going to import oops import e-print and then I need to import the requests dependency that we added and I also need to import OS so the very first thing we want to do is load that API key value from our DOT EnV file and that's what load.env does so I'll just say load underscore.env put the parentheses on there to call that function now let's go ahead and Define our get current weather function so we start with the def keyword and I'll say get underscore current underscore weather and now it's going to receive a parameter and I'm going to say City but I want to give this a default value to say it's just pressed enter and the form is empty so by default I'm going to give it my area which is the Kansas City area you could provide your city or your nearest large city is what I would recommend if you want to put a default value here that's different than mine just to avoid a typo as I've been having lately I'm going to paste in this URL but let's go over the URL so you can get it accurately as well so here we've got request underscore URL notice it's an F string then it goes to http colon slash slash API dot openweathermap.org data slash 2.5 slash weather and then we have a question mark and this is where the params in the URL begin you need to put app ID equals then we use the OS module that we imported we'll say OS dot get EnV and then parentheses API key so we're getting that environment variable right here using OS dot get EnV and then we have an ampersand and then a q which is short for query and then that equals the city value that was passed in or Kansas City in my case if a value is not passed in one more Ampersand and I set the units to Imperial now you can look at the docks for the open weather map API because if you don't want Imperial if you want something else instead of degrees essentially for the weather you can change this to metric I believe okay now let's go ahead and get that weather data so we'll say weather underscore data equals requests.get and we pass in our request underscore URL and at the very end we need to add dot Json and put parentheses to call out because we want Json data and then we're going to return the weather underscore data so this this gets the data from the open weather map API and now I said we're making a module so to do that let's complete this by saying if two underscores name two underscores and then two equal signs equals main with also the two underscores which we've covered in this course so if this file is called directly weather.pi instead of calling the file that might call the entire application for the web then we're going to go ahead and run this file as if it's at the terminal once again so I'm going to print and then inside of the print statement I'm going to start with a new line and then I'll just say let's do three asterisks here and get all right weather conditions three more asterisks one more new line so that's just kind of a welcome to the app at the terminal window then we'll say City equals input and here we'll have a new line and please enter a city name and a colon and after that let's go ahead and come down and get our weather data so whether data is going to equal get current weather data and we're going to pass in whatever city was provided and again if they don't pass in a city it should go back to our default value here of Kansas City after that at the very end I just want to print say one new line and then we'll go ahead and pretty print oops don't want to do that having a hard time typing today at the end let's go ahead and pretty print our weather underscore data so this is if this file is called directly which is kind of the right thing to do for a module this would go ahead and provide the weather data at the terminal just like we learned how to do a couple of lessons back but today we're going to use this get current weather function in our web app so we can get that weather data and present it on the web with the template and now that we have our weather function we're finally ready to start working with flask directly and so let's go ahead and create another new file over here which will be the main file for the application sometimes people name that main dot Pi I'm going to name this server.pi because it will be a flask instance that is running our server essentially so that is also common you could name it either one you want but just remember what you do name it so I'm going to refer to it as server.pi like I used now inside of this we're going to create a route with hello world just to test it out first so I'm going to start start with from flask import flask with a capital f then I'm also going to import render underscore template and request now that is different than requests that we've imported in the other file I also need from weather import git current weather and we'll use that in just a moment now let's go ahead and Define our app so we say app equals flask and then inside of the parentheses we do two underscores name two underscores and that makes our app a flask app now we Define routes in flask and those are routes that we would access on the web so I'm going to say at app dot route and now I just want slash this would be the home page but then also commonly you should be able to access the home page if you go to slash index or slash index.html for example so I also want to add app dot route and then inside of this I want slash index so both of these will apply now following these routes we Define a function that will return something for the route so I'll say def index parentheses and now we'll go ahead and return something at this route so I'm going to return here I'm just going to say hello world to start out with just a simple example but of course we're not ready to run our file yet until we add our if name equals Main two more underscores and now in this if name equals main I'm going to start with app dot run and here I'm going to say the host is equal to now inside of quotes I'm just going to put 0.0.0.0 or zeros with dots in between that's going to make it run on our Local Host now I'm going to say Port is I'll give it 8 000. so we're going to go to localhost Port 8000 to see the app after we start it so we have a basic route here for our index or our home page if you will and we'll return hello world and it's going to go ahead and start the server with this simple command so let's run this file now and here we see running on all addresses so it should be running as expected and notice we get a warning here as well this is a development server don't use it in a production deployment so we'll want to fix that in the future as well let's go ahead and look at our web app right now that should say hello world and we'll need to do that in the browser I'm in Chrome and I have a new tab open I'm going to type localhost and then I'm going to want 8 000 after it so localhost colon 8000 I'll press enter and right now we have our hello world as expected back in vs code I'm going to press Ctrl C to quit the server for now and then I'll close out the terminal window and let's go ahead and adjust that remember that warning we saw that said hey this is a development server we don't want that we need to go ahead and replace that because we are going to deploy this app essentially put it in production so to fix this let's open the terminal once again and here I'm going to type pip install waitress now waitress is a package that is going to help serve our web app in production so now that I've installed that I've got a new dependency and that means I need to recreate the requirements file so once again pip freeze greater than symbol requirements.txt press enter it should now have added waitress to our requirements file let's check and yes there it is on line 14. and now that we have waitress added let's go ahead and add it to our flask app as well so I'll say from waitress and I'm going to import serve and serve is what we need to serve our applications so let's replace this app.run here with serve not server just serve and inside of this we need to start with app comma and then we can still say host with the four zeros we can still say Port 8000 all of that is fine we're now ready to add that second HTML page I've talked about so click on index.html click somewhere in the file press Ctrl a which should select everything Ctrl C to copy everything then you can click away if you want to now let's create a new file here with this new file typeweather.html and inside of our weather.html we'll get a jump start just by pressing Ctrl V and pasting in everything we had inside of the index at first and then I'm going to press alt Z to wrap any of those lines down as well much of this will stay the same but we're going to make a few changes so we need the same CSS link that's no problem we do want to change the title of the page so let's go ahead and select that and then I'm going to press Ctrl D and I'm selecting the second instance here of get weather conditions because we're going to change both of these to say the same thing I'll press backspace and it deletes both of those and I'll press two curly braces then the word title two more curly braces and then the word weather so whatever city is entered into that previous form when we filled this page out it could say Kansas City weather or Paris weather or wherever but it's going to fill that in as we use this template now we still want the same form underneath because we want users to go ahead and be able to request more data or more City's weather if they choose to after they request the first one let's create some space here between the H1 and the form so we can put in some more information now I want a paragraph and in this paragraph I'm going to use two curly braces once again type the word status two more curly braces then and two more curly braces type the word temp two more curly braces now I'm using degrees again so I'm going to use the abbreviation in HTML entity four degrees if you wanted this change to a different system a different symbol you can look that up on your own but I'm going to use Ampersand deg semicolon which will give the degree symbol now I'm going to just click on this line press shift alt and the down arrow and it copies all of that down so now I'm going to say feels like and after that I can delete status and but I'll leave temp I'm going to replace the word temp with fields underscore like so these are the values that we are filling in when we get that weather information but currently we're not handling the weather route and when we make a request for weather be it on the index.html page we look for the weather route or even on the weather page itself we submit this form to the weather route and then that data comes in and fills it out so let's go to our server.pi and handle a route for weather so we need to go ahead and create that function and Route underneath where we have the Route 4 index so I'm going to say at app dot route and here I'm going to pass in quote slash weather now beyond that let's go ahead and Define our function I'm going to call this get weather remember our other function was get current weather so I'll just call this get weather underneath this we're going to get the city value first now that City value is going to come in from that form data so here we can say request Dot args.get and then we want to get the city value so now we should have retrieved that and we'll have weather underscore data going to equal get current weather and we'll pass in the city value so now that we have the weather we want to send that data to that template so here we're going to say return and then we'll say render underscore template and now inside of these parentheses the first value we want is the template itself which is weather.html now we need to pass all of the other values that we're going to use let me scroll up just a little so we have some room and I'll say title equals whether underscore data then we want to use brackets and say name after that this would be the city name of course as well after that we want status equals once again we're going to have weather underscore data brackets and now we need to get some specific information that's in that Json and if you remember back to the lesson a couple of times before we had a fairly large Json object to navigate to get this data so here we start looking at weather and then we get the first element in weather and so we use a zero to get that and then after that we still need to get the description and then after the description I want to capitalize so I'm going to pass capitalize here and call that as well so that's going to be the status such as cloudy or whatever the status is I believe cloudy or few clouds is what we just had for Kansas City now let's go to Temp we'll set that equal to and now this is an F string so we start with f and quotes now curly braces and we'll say weather underscored data once again brackets now we already have double quotes on the outside so we need to use single quotes and we'll have Main and then we have temp once again you need to refer to the Json object to know how to get this data out of the object and I'm not breaking all of that down here for you because I did it two lessons ago so we've got main Temp and I want to format this to that dot one afterwards whatever it was dot 0.7.8 so I had like 97.3 degrees for example so I just want the one digit so here I had colon then a period and one and F so that's how I'm formatting that F string instead of a 2 which you've seen that format here before when we used the bank accounts I believe okay after that another comma and then finally we need the feels like value so feels underscore like set this equal to another F string so we have have our double quotes our curly brace inside of here weather data and then we'll once again have the single quotes around Main and then we'll have another bracket single quotes around Fields underscore like and finally we're going to format this the same so colon dot 1f there's all of our information passed in so you get how we're getting that out of that Json object that is returned from our get current weather function and after we do that we're passing all of these in that we're using in the template so the words we're defining here to the left are what's used inside of our weather template so when we go back and look at weather we just have to say title status Temp and feels like and we can use those inside of our template okay back in the server.pi one thing we didn't do is ever change our hello world and we want to do this but this will be fairly simple all we need to do here is say render underscore template as well and just pass in the index.html because it's not receiving any of these like the weather page is now if any of this went too fast feel free to go back to the previous lessons also of course my code is available at the link in the description and let's go ahead and run this code and make sure everything's working now as we expect it to and I'm going to choose run python file and now we're going to have to go back to the browser and look at the app I'm back in the browser I need to refresh our local host at Port 8000 and now we have our get weather conditions but what I notice is the CSS is not being applied I may have a typo let's go ahead and check out the functionality first though so here I'm going to type in New York and press enter and yes we've got the New York weather Haze and 88.1 degrees it feels like 93.2 degrees this is all good what's not good is we're missing the CSS being applied to the pages okay back in vs code I've made a very simple mistake easy to make I am looking in the file names or in the folder name Styles slash style.css inside of both the HTML files but when I look at the file tree I actually named my sub folder here inside of static CSS because I had CSS on my mind and not the word Styles so let's go ahead and change the name of this folder should be able to right click and choose rename which also looks like F2 would have done that and I'm going to switch this folder to style so I'm looking at static Styles and then the file style.css that will match what we put inside of both of our HTML files so we save that we should come back and go ahead Ike stopped my server if you haven't stopped it you might not need to I'm going to go ahead and restart this and let's go ahead and reload the home page so now the CSS applies like we expected to let's go ahead and type in a city name I'll put in Omaha and press enter and yes the weather app is working like we expect it to as well however this is the core usage what if we entered something that would be unexpected say we just press the submit button without entering a city or maybe we entered some spaces into the input and we submit I think we'll probably get an error well that's a surprise several spaces brought back a name from the API that I did not expect let's go ahead and hit submit without entering any spaces and see what we get now we have the internal server error that I expected so let's go make a few changes to handle these edge cases in our code we're back in vs code and we need to go to the weather module to start out and let's work with the module when it is called at the terminal line first because this will be easier to debug and check as we go what we need to do is get the input from the user and make sure that it is not an empty string meaning a string that actually has no characters but still the two quotes or a string that is full of spaces only so it would still be empty because then we could strip away those spaces and we would once again have an empty string so to do that we can put in a line of code here and I'm going to put a note and just say check for empty strings or string with only spaces so we know exactly what this line of code is doing so I'll say if not and then I'll use Bool and if you remember Boolean that's true or false well we're going to say we want content here so it won't be empty so we're looking at city but before we look at the city let's also strip away spaces so I'm using the strip method here so this strips away all those empty spaces because it would normally take away white space at the beginning and the end of a string but what if there wasn't anything in between so it's just going to strip away all of those spaces and then we're going to make sure we have something left so we can say if not Bool but first we're stripping away the spaces and then we'll go ahead and put our colon for the if statement then we'll just say City equals and let's give it a default value you like Kansas City if you remember we put in a default value for our function and I put in Kansas City however that doesn't mean an empty string couldn't be passed to our function and in that case the default value wouldn't kick in so this line of code is going to check for that so now let's just run this module and see if it works when we do not enter anything or when I enter several spaces so now we'll run the code this is the error that we got in the web app this is not the code that we're running so I need to press Ctrl c a couple of times and now it's running out the terminal so it says get current weather conditions please enter a name I'm going to drag this up just a little bit I'm not going to enter a name at all I'm just going to press enter and now it returned the weather for Kansas City because that's the default value I gave in the code if we stripped away everything and the city name didn't exist so as we look back here City equals Kansas City let's do this one more time and now let's do it with several spaces so I will go ahead and run this code once again I just press the up Arrow to pull that line up and then press enter and that's what ran the code here now please enter a city name I'm going to enter in several spaces let's see what we get back do we get something from the API that is not Kansas City no we get Kansas City so once again we stripped away all of those spaces and then there was nothing left and so then it defaulted to Kansas City feel free to put in your own city name here but now that we have debugged this or worked around some edge cases inside of our weather module we also need to apply something like this to our get weather function inside of our flask server so let's go to the server.pi file here's our get weather function and we're getting the Value City from the arguments essentially the parameters sent in the URL and so after we get City this is where we would need to check and I really want to put in the exact same code here that we used in the weather module to check for that so I'm just going to copy this that I put in on lines 23 through 25 with control C go back to to the server.pi I'm going to put this code right here so that is once again going to check for an empty string after that we're going to get the weather data from the API but what if the API does not find the city that we pass in what if we pass in some strange name that could also be a problem let's go back once again to our weather module and let's run this one more time and I'll just put in a random string that I know is not a city name so when it says inner city name I'm just going to put in something strange like that let's see what we get back notice we get a different object instead of that Json weather object now we get an object that has a code of 404 which means not found and a message that says City not found likewise if we would run our app here one more time just this weather module and I type in a name or I'll just press enter so we get Kansas City information we notice inside of our larger weather Json object here that there is still a code right here the code is 200 that means successful so we could look for a successful code of 200 to know that our request has succeeded now there's nothing to fix in our weather module it presented the object that was returned just fine but inside of our server.pi file we actually need to handle that in case we don't get the object that we expect because then we would get an error here as we attempted to get the name and the different weather values from the weather object if we did not have a weather object so to handle this case I'll put one more note underneath here and I'll say city is not Bound by API and in that case we'll say if not weather data and then we'll look at that code value and notice it doesn't have an e at the end but it's abbreviating for code then it looks like cod actually which is kind of funny but nope it is for code if it's equal or this is if it's not equal to 200 notice 200 is not a string because that object didn't provide a string it provided the number so if our weather data code is not 200 then our request has not been successful and we will not have the weather data we expect so in this case I want to return a message simply saying City not found and we could do this just like we did with hello world and say City not found and I'll save this for now but instead let's create one more template to handle that so in our templates folder I'll just click on index.html and then the new file icon and I'll call this city Dash not Dash found dot HTML and now I'm going to go to the index dot HTML file and press Ctrl a to select all and Ctrl C to copy from there I'll go back to the city not found file and press Ctrl V to paste everything in also alt Z so it wraps down now there's not much to change here but I'm going to change the title and once again after selecting get weather conditions press Ctrl D so it selects the second version of that which is down below in the body of the page here I'm going to type City not found after that I'm going to put an H2 underneath City not found in the body and just put try again with a question mark and then we'll once again leave this same form so the user isn't stranded on this page they could once again enter in a city name maybe they just had a typo so this will be our city not found page so after creating this template let's go back to the server.pi and now we can render that template here instead of the city not found string so I'll have render underscore template once again and now we're just going to pass in the city Dash not Dash found not HTML file now with this new code in place we should be able to handle those possibilities those edge cases as we would call them inside of our web app as well so if our files are saved let's open the terminal once again and we want to run the server Pi file so I'm just going to press play here and run this file and we can see it's running here let's go back to the browser and check it out so we had an internal server error before so I'm going to remove everything that came after the localhost 8000 now press enter and it should once again reload the app I'm ready to put in a town or a city name so I'll put in Austin press enter and yes it's working like expected so now if I just press submit without entering anything we get the Kansas City weather because that's what I put in for a default and if I put in some random characters that don't make any sense and press enter we get our city not found template and it says try again so I could try again I'll enter in many spaces which actually has no content whatsoever press enter and once again we get the Kansas City weather so that's really what we wanted to do it handles those and notice up here the city equals value when I put in all the spaces is represented as plus symbols inside of the URL which is a little interesting let's go ahead and enter something else it's just blank and then notice it's just City equals and nothing comes after it but we still get the Kansas City weather and now with our code feeling like it's complete it's ready to deploy to the web I'm back in vs code and now we're going to work with Git and GitHub and if you're not familiar with Git and GitHub you may want to stop the tutorial now learn about those before you try to proceed and deploy your web app because I'm not going to go into all of the details of how they work I'm just going to show you what I do because this is not a get or GitHub tutorial although I do have those on my channel okay so here we've already initialized our git repository earlier in this tutorial now with it initialized I see some files over here meaning they're new they're green in my file tree and I'm getting ready to add those but I'm I'm also looking at my file tree going hey this pie cash folder has been created that happens when we use modules we import modules then it just caches some things to work more efficiently but we really don't want to send that to GitHub either so let's once again go to the get ignore file and inside of there I'm just going to list the two underscores I cash and two more underscores and save and now that is also not going to be sent to GitHub with our git repository so once again it's already initialized so now I just need to add the files to the repository so I'll say get add and type a period that means all so I'm going to add all of those files now I'm going to commit the files to the repository so I say get emit Dash M for message and I'm going to say first commit press enter now all of those green files turn white in my file tree and they have been committed to my repository now they haven't been sent to GitHub yet so we need to go to GitHub and create a repository to send them to okay I'm on GitHub and I have an account here already if you don't you'll need to create one and then I want to click new for a new repository now I have a paid account because of my job I need to be able to do several things that only a paid account can do however if you have a free account you can only have public repositories I believe however I'm going to set mine to private because I'm just going to use it for this tutorial so here I'm putting in the repository name I'm going to put in Python Dash weather and so you could name yours whatever you want to after that I'm just going to scroll down and create the Repository after it does that it's going to give us this page of instructions and I'm really only interested in this part that says or push an existing repository from the command line and that's what we have back in vs code we have an existing git repository so I'm going to copy just by clicking this icon here all three of these commands and then we'll go run those commands inside of our terminal NBS code okay I'm back in vs code I'm going to type clear first here in the terminal just to clear everything else out now when I right click it's going to run the first two of those three commands and it's going to wait for me to press enter on the last one so I right click runs the first one it runs the second one and now it's waiting for me to push this is a get push the repository here on my computer in vs code to GitHub so when I press enter that's exactly what's going to happen and it quickly sent those files to that GitHub repository now I'm back in the browser at the repository I'll click repository Title Here near the top left and we can see these files are now in the repository at GitHub so now we want to go to render.com where we're going to deploy this web app and it will pull these files from our GitHub repository into render on its own we can set that up so let's go do it and now I'm at render.com if you don't have an account here you can sign up for one for free I'm already logged in so it is just showing me the dashboard button I'm going to click that dashboard button and now I am logged in and I can go ahead and create a new web service which is what we want so by creating the new web service it's going to give us a list of our connected repositories now I have connected my GitHub to my account and you could do the same if you don't see it like it's offering to connect gitlab which is another service like GitHub to my account as well so you might see it over on the right if you're not connected so I'm connected and now I immediately see my python-weather repository because I just created it two minutes ago I'll click the connect button and it will start to pull the code in from GitHub and now I can set up my web service or my web app here inside of render.com I'm going to name this the same thing python-weather I don't need to change the region I'm on the main branch in my repository so that's fine this root directory is optional I don't need to change that we will be using python3 and we have been using python3 so that's fine where we have the build command and pip install Dash R requirements.txt that's good because we do have a requirements file but we might also want to update pip as we have had some notifications about before needing updated so let's go ahead and put in hip install and we only need two L's there then I need Dash U capital u for that upgrade and then pip and then two ampersands and then it can do the next command which would be our requirements.txt so I just want both of those in there now as we come down to the start command here our start command is going to be python3 then we're going to run our server dot Pi file but we're not quite finished yet let's scroll down just a little bit further we're using this free instance which is fine but as we scroll down we need the advanced because we're going to add our environment variable remember we have an API underscore key in our DOT EnV file in development we need to take the value of that and put it right here back in vs code I'll close the terminal and click on my DOT EnV file here's my current API key value control C to copy that let's go back to that dashboard and we can put it in right here but we also need one other environment variable and no we did not have it in development but render needs it render needs to know what version of python we have been using so we'll say python version and now if you remember how to check your python version you could do that and put it in here if not let's quickly do that for you so back in vs code let's control in the back tick to open this up I'm going to just type Pi lowercase once again if you're on Mac or Linux type Python 3 I believe but after that you need dash dash version and then when I press enter you can see I've got python 3.11.2 if you want to enter in whatever version you have been using so here I'm going to put in 3.11.2 and remember I am going to change my API key value so don't try to use mine make sure you go to openweathermaps.org and get your own okay now that we've entered everything I believe we're ready to scroll down here and create web service so let's click that it will start to deploy and it will give us quite a few messages here in the this window I'll come back when it's finished I'm back and render says your service is live so that's what we wanted to hear let's scroll up and we can see our URL for our python web app right here it's at python-weather.on render.com so whatever you named your repository or your project here in render is probably what's here before dot onrender.com let's go ahead and click the URL and now we see our web app is actually on the web and you can share it with your friends let's go ahead and enter in another city name here I'm going to enter in Santa Fe press enter and there's the weather tonight it's getting a little chilly in Santa Fe maybe a warmer destination like Houston and press enter and yes the Houston weather is much warmer it feels like 95 right now so everything is once again working we can even check out not entering a city and I get Kansas City depends what city you put in for yours I'll enter in something that doesn't make any sense and of course that shouldn't be found and we get our city not found template so I'm happy with the results here I hope you are too and moreover congratulations on completing the python 4 beginners course and on completing this project remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon