Python for Beginners – Full Course [Programming Tutorial]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this full course you will learn the basics of python programming i'm beau carnes with freecodecamp.org i've previously created one of the most popular javascript courses on youtube and i've created many python tutorials now i've created this complete python course for beginners you don't need any previous programming experience to follow along and all you need to code in python is a web browser in this course i will teach you all the core aspects of the python programming language and i will simplify the more complex topics python is considered one of the most popular programming languages in the world and it's only growing in popularity python excels in a wide variety of scenarios such as shell scripting task automation and web development and it's also the language of choice for data analysis and machine learning but it can also adapt to create games and work with embedded devices we're going to jump right into it so you can start coding your first python program as soon as possible to get started quickly we'll use a replit which is an online ide that allows users to code and run programs in a variety of different languages all in a web browser and later i'll show you how to get python set up on your local operating system after the first project i'll go into more detail about each of the main features of python the section is comprehensive and detailed and in the final section you will use what you've been learning to code a blackjack game with me guiding you every step of the way throughout the course there will be a little repetition of some of the key python programming concepts to make sure you have a deep understanding of the language so let's get started we're going to start by creating a simple rock paper scissors game and we'll start by going to replit.com replied provided a grant that made this course possible and replie is going to make it super easy to get up and running really quickly so you can either sign up or log in and create an account i'm just going to use my google account okay now that you're logged into replit you can either just click the create button or this plus button over here to create a new replit and i'll make sure to create a python replit but you can see you can also select all sorts of different programming languages oh these are just the ones that start with the word python but so there's there's tons of different programming languages you can select but in this case we are just going to use python and then i'll click create reple okay so let me just kind of show off replica a little bit this is where we're going to create our python code i'm going to zoom in just a little bit so we're going to write the code right here and then we can see some output over on the right side and then you can create different files over on the left side here and then there's some other things like you can connect to version control and if you have environment variables we're not even going to be discussing those in this course there's a debugger you can connect to a database and just some other things but we're mainly going to just be using this main.pi program to write our program and we're going to see the results in the console so i'm just going to close this files window so it's a little bigger here i'm going to start off by showing you how to create a variable with python so this is a rock paper scissors game and there's going to be a players a player is going to have a choice and a computer is going to have a choice so i'm going to create a variable called player choice and i'm going to set that equal to rock so let's look at a few components about this this is the variable name player choice and you can see if you we use an underscore that's just kind of the convention for python to use an underscore if you're going to have a space in the variable name and we're going to assign it that's what this equal sign this is the assign operator and we're going to assign it to a string a string is just a word or a collection of characters like rock and we're going to put quotation marks around it now we could have also used a single quotes instead of double quotes as long as you use the same quote on each side that's what's important so we've now created a variable called playerchoice and assigned it to rock and now we can reference this variable later and whenever we reference the variable called playerchoice it's going to the code is going to automatically replace that player choice with rock so this is going to be a very interactive project i hope you're following along i hope you have already got replit loaded up like this now throughout this project i'm going to tell you what the next thing to do is and i want you to try doing it yourself before you watch what i'm going to do so periodically you'll want to pause the video based on and what i say you and try to implement what i say before you come back to the video and watch me implement it and see if you've implemented the the same way so i'm just going to zoom in one more time and this is the first thing i want you to do see if you can make another variable on the next line so you're going to press return or enter to go to the next line and this variable should be called computer choice and you should set it to equal paper okay so you can pause the video and see if you can make a variable called computer choice and set it to equal paper so here it's pretty simple here it's going to start simple but it's going to get harder as we go so computer choice equals paper okay so like i said it's starting simple but it's going to get more complex as we go along if you've done that you've now written your first line of python code in this course okay now i'm going to talk about functions a function is a set of code which only runs when it is called so i'm going to show you how to put this code into a function now one thing about python is that indentation is very important so after we create a we define the name of a function any line of code that's indented the same amount is considered within that function so i'm going to create a new line of code at the top and i'm going to call it get choices okay so we define the function with def and get choices and i'm going to select all these these two lines of code at the same time and just press the tab key and that's going to indent all these the same amount and you can see sometimes they'll be squiggly lines and if you hover over some of the squiggly lines it will tell you something in this case it just says the local variable called player choice is assigned to but never used that's not necessarily bad it's just it's just telling us that usually if you create a variable you're going to want to use it later well we are going to use it later we just haven't gotten to it yet so sometimes the squiggly lines will indicate there's some sort of error in the code usually i think it's the color red will indicate an error but if it's a different color it just may mean that there's something maybe not quite right but it's not really that big of a deal so if you have a variable that's assigned to but never used that's not going to stop your program but it's just saying that it's not this variable isn't really being used for anything yet but we will change that this function i'm going to show you how to call a function later but we're creating a function called getchoices that assigns these two variables and it's also i'm going to put another line at the very end here and it's a return statement and i'm going to return player choice this will indicate what's returned when this function is called so later we'll call this function get choices and it will return something it will return the player choice which is right here we'll turn in this case rock that we can use somewhere else in our code and i did just happen to put an extra line here that's just that's optional i put a blank line here just to kind of make things easy to kind of organize the code a little bit so different sometimes i'll just put an extra line between different sections of code and it just makes it easier to identify the different sections when you're looking at the code for the computer those extra lines don't mean anything the indentation though definitely does mean something so as long as every line of code is indented the same amount as the previous line of code then it's all within the same function okay so this is what i want you to do see if you can change the return statement so instead of returning player choice it's returning the computer choice so that's pretty simple it's now returning the computer choice here now i'm going to create another function down here this is just going to be an example function just so i can demonstrate something to you and then we'll delete it it's not going to be part of our rock paper scissors game but i'm going to create a new function called greeting and then i am going to add what it's going to do oh yeah put the semicolon you also know a colon so a function always has to have a colon at the end of how we define it so i'm going to return a string and it's just going to say hi and one thing you'll notice is that there's no you don't have to put any anything at the end of each line some programming languages such as javascript you're going to put a semicolon at the line at the end of the line but in python it doesn't matter you don't put anything at the end of each line so now i'm going to call the function to call the function i just type the name and i put the parentheses at the end so it's going to say so greeting is now going to call it's going to call this function and that's going to return the string hi now it's not going to do anything with the string because our program doesn't do anything with the string that's been returned it's not going to go into the console or anything but let's add additional code so we will make this string hi go on to the console first let me create a variable that takes what this greeting function returns so i'm going to type in response equals greeting so now we set the the what greeting is being returned to this variable called response and now i can use the print function and i can print the response and this will print it to the console so now i can we have this green button here this runs the program i'll click this green button here and now we can see it's high so this response is getting this high from here and then we're printing it right there okay i'm actually going to delete all of this and what i want you to try to do now is to call the get choices function and store the response in a variable called choices and then print the value of choices to the console so you can pause and try that really quick and then i'm going to show you how okay so remember the variable is called choices and we're going to set that equal to the get choices variable now ins or the get choices function now instead of typing out get choices you can see that this code editor is actually giving us suggestions on what we want to put in here so i just typed in get and you can see it's now saying get choices right here so i can instead of typing out the whole thing i can either click there or i can just press the tab key and it's going to fill in the rest of that function name so that's just something little that makes it easier to write a program and you don't have to type out every single thing so if you've already created a function or a variable then the the code editor then reply will will suggest what you may want to fill in when you're typing and most other code editors do something similar it's called code completion so i'm going to but i still have to add parentheses at the end and now i'm going to print the choices [Music] okay so i'm gonna just click this play button to make sure it does what we're trying to do yep it clicked paper great now let's talk about dictionaries dictionaries in python are used to store data values in key value pairs so let me just show you an example okay so a dictionary is going to have these curly braces at the beginning and end and then here's a key value pair there's one it's separated by a comma and then here's another key value pair so we're setting name we're setting that to equal bow and we're saying the color to equal blue so here's the key here's the value here's the key here's the value and the key or the value in a dictionary can be a variable like the color we could set that we already created this variable here i'm just going to copy the word choices and we can put choices and you can see now it's not surrounded by the quotation marks so if you surrounded by quotation marks it's a string but if we don't surround it by quotation marks it's getting the the variable here choices so this would be set to paper because that's what choice is going to is going to equal so we're about to delete this line because that was just an example but now before the return statement in this function we're going to add a new line we're going to create a variable named choices and make it equal to a dictionary the first key should be player with a value of the player choice actually this variable here the second key should be computer with a value of computer choice and then we're going to update the return statement to return the the choices dictionary now i'm not going to keep telling you to pause and try it yourself so just the rest of this time whenever i say what we're going to do you'll know that after i get done explaining it you can pause it and try it yourself but that's what we're going to do now so i'm going to create choices and it's going to be a dictionary and then it's going to have a player that's the key and the value is going to be player choice and i was just able to press tab to fill that in and then we're going to have computer and it's going to be computer choice and you can see sometimes if it goes to the next line there just won't be a line number right here but i can move this over for now and then i am going to oh i forgot to put the equal sign that's what that red squiggly line means so because the red means there is a problem in the program so it's not going to run correctly now the orange just means that we haven't used choices yet which we will right now because we're going to return choices choices okay so now we don't have any squiggly lines because we're using every variable that we created and we're returning choices here so you may have noticed that player choice it does not actually get set to the player's actual choice so let's fix that the input function gets input from a user and will use it to get the player's choice so instead of having players choice equal rock we're going to make players choice input enter a choice rock paper scissors okay so this is how you get input from a user we use the input function and this is going to be something that's going to be printed we'll print to the console here and whatever the result of this input will be that the the player that the user entered will get stored to this variable which we then can use later in our program so let's just try that out i'll click run and enter let me just stop and run it again okay enter a choice rock paper scissors i'll just put rock and now you can see the player's choice we're still printing that and it's going to print as rock great now let's just clean up this code a little bit we still have this here we don't need that dictionary that's not going to be part of our final code and now we'll make it so the computer can actually make a choice so we're going to learn about importing libraries creating lists and calling methods python libraries are a set of useful functions so you don't have to write code from scratch when you import a library to your program you get access to more features without writing additional code with basic python it's challenging to get your program to do something randomly but it's easy to choose something randomly using the random library so let me show you how we can import the random library import statements are used to import libraries and they're usually put at the top of a program so i'm going to press enter a few times here to add some lines at the top and i'm going to do import random so now we are going we we've imported the random library so we're going to use that random library soon but now let's learn about lists a list in python is used to store multiple items in a single variable lists are surrounded by brackets and each item is separated by a comma so here's an example i could create a variable called food and set it to this list it's going to have three items pizza carrots and eggs [Music] so this is a list of strings and then you can also get a random item from the list using we're going to use now we've imported random we can get a random item by using that that random library so i'm going to put dinner [Music] equals random dot choice and then i'm going to pass in the the list here so using the random library we can call choice and then we can pass in a list and it's going to choose a random item from that list and and set it to equal this dinner variable so right now the computer choice always equals paper but we want it to be a random choice between rock scissors and paper so before the computer choice variable is created we'll create a new variable called options and assign it to a list of the possible options rock paper scissors then we'll set the computer choice variable to be a random choice of one of the items in the options list okay i hope you already tried this now but let me show you how that's going to work we'll create options and we'll set it equal to this list of rock [Music] paper scissors and you can see the code editor will often pop up these boxes with more information about what we're doing to give us some some help with what we're trying to do here so we're going to set this computer choice to be random dot choice food not food i was looking at the food down there that's gonna be options there we go and let's just um try running this program and seeing what happens so i'm going to put rock and then we see the computer chose scissor it should be scissors that's why we're testing it out i guess i spelled that wrong okay so scissors with an s so now let me try running it again and you can see it shows scissors but if we run it enough time it should now it's choosing paper because it's choosing it at random okay that's working okay so now let's just delete all this code after the get choices function we don't need to test that get choices function anymore and now let's create a new function called check when so you shouldn't know enough how to you should know enough about how to create a function so def check [Music] when so this is just an empty function with nothing inside it yet but before we add oh with the colon so before we add any code inside the function we're going to create some arguments function can re functions can receive data when they're called the data are called arguments so when creating a function you can specify arguments inside the parentheses so we've been using this empty parentheses but i can uh put in tooth i can put in things within these parentheses when this function is called we're going to give it two pieces of data we're going to pass two pieces of data into the function the first piece of data is going to be player the second piece of data is going to be computer so the you can basically call these anything you want uh these are just we're creating new variables but when we call these functions we'll pass in two pieces of information that will then be assigned to the variable names player and computer that we can use inside the function so for now let's finish off with to a for a complete function the function has to have some code within the function so let's just add a return statement that's just going to return a list containing the elements player and computer so this check when function shouldn't actually return this this is just to kind of get get it quickly created it should actually return different things depending on the player and computer arguments an if statement will allow a program to do different things depending on certain conditions so an if statement will first check a condition and if the condition is true then all the lines of code under the if statement that are indented the same amount will execute so as a quick example i can say a equals three b equals five and then we can create an if statement here if a is greater than b then we will do something like print yes or we can do if a is less than b or we can do if we want to check if a and b are equal we can do eq we we'll put two equal signs now this is very important you never want to use one equal sign because a single equal sign is the assignment operator that's how you assign what variables are equal to so if you use a single equal sign or like then if i put if a single equal sign b without a double equal sign that is going to set a to equal b which is not what we want the double equal sign is going to check if a and b are the same value basically it checks if two values values are equal now you can also do a not equal so if you use the exclamation point that's not equal or you can use less than or equal to or you can do more than or equal to so i'm just going to delete all this for now so now we're going to update this risk turn statement uh before the return statement we want to we're going to check if player if player equals computer and if so if true will return the string it's a tie so let's do that if player equals computer and this is something that maybe you figured out yourself before you before you're watching this will return a string and the string is going to be it's a tie okay so now it's only going to return so a function does not have to return something and for this function it's only going to return something if this is true if player equals computer if not it won't return anything and just to make make you notice this see this line is indented within the if statement which is indented within this function and just really quick thing to note for a return statement parentheses are optional so i could also add parentheses like that but you don't need them but for now i'm just gonna get rid of them [Music] so currently when there's a tie the program now returns it's a tie but how does the player know that's true now let's have the program print which options that the player and the computer chose you can concatenate strings with the plus operator that just means you can combine strings with other strings or strings with variables so let me show you how you can print which options were chosen so i'm going to print you chose and then i'll put player so you chose and then we have to add a space here because it's going to print a space and then it will choose it will print this so if the player chose rock we'll say you chose rock and then we can concave so we concatenated these together but we can add another plus sign and put another string here and it's going to say computer chose oh it's like being covered up here by everything computer computer chose now i'm just about to type it in but see if you can figure out what to add at the end here to put in what the computer chose so computer chose computer or the the value of this variable here so a lot of times when with programming there's a bunch of ways to do the same thing so this is one way to combine strings and variables together there's another way that's a little simpler called an f string so an f string will allow you to make strings with and with variables and other python code so to do that you just put a variable or you just put f at the beginning of a string so let me just give you an example so we do age equals 25 we're going to create a variable and then i'm going to make an f string we'll make it a print statement and i'm going to put a string in here but instead of starting with a quotation mark it's going to start with an f and then i'm going to put gem is and then whenever you want to put a variable or any kind of python code we're going to put some curly braces and i'm just going to put the variable within the curly braces so years old and i'll put the end of the string or let me put a period here okay so gem is age which is going to be 25 years old so the f string is just a slightly simpler way to combine the strings and the variables so what i want you to do see if you can figure out how to update this line right here so it uses an f string and it uses these curly braces instead of all these pluses up there so yeah we're going to put f and i can delete a lot of these things here [Music] and then i'm going to put some curly braces you chose player there we go okay you cho there was a comma here you chose player computer chose computer okay so now we've been able to put in the variable within this string with the f string so we're going to test this out uh so in a code the code in this function never gets run so when we press the run button it's not going to run any of the code within the function unless the function is called within the program so we're not going to test out this function all right now what i want you to do is see if you can add a line to call the check when function and then just call it with uh rock and paper so we're going to just do check when rock or actually we have to pass in strings here rock paper so this is going to it's going to call this function with rock in terms instead of player and paper instead of computer so let me try stride running this program you chose rock computer chose paper and just don't worry about these little icons sometimes they just block what's in there but it's still behind that little search icon so it's to see it's doing you chose rock computer chose paper now let's get back to checking the winner so far this function is only going to check if there's a tie now we'll start adding code to check different wing conditions so let's learn about else and elif statements okay so down here i'm just going to give you i'm just going to paste an example so so here's the if statement if age is greater than or equal to 18 it's going to print this else so anytime this is not true then it's going to print you are a child okay now here i've combined it with something else the ellis statement ls just stands for else if it combines else and if so you have to put a condition so if age is greater than or equal to 18 print you're an adult else if now we're going to check if age is more than greater than 12 you were a teenager else if age is greater than 1 print you are a child or else if none of these other things are true we'll just print you or a baby so and it's it's only going to do one of these it's going to get to the for once it gets to the first one that's true then it's not going to check the rest it's just going to kind of go to the next line of code after all these statements so it's just going to choose one and once it gets the first one that's true then it's be done with this whole section of code you can also check for two conditions at once let me give you an example i'm just going to delete all this code and i'm going to create an alif statement here elif else if and we're going to check if player is equal to rock and i'm just going to type in the word and and computer is equal to scissors so now i'm checking if both these conditions have to be true so this condition and this condition have to be true before the following statement will happen which we're going to just put return rock smashes [Music] scissors you you when [Music] okay now the next thing we're going to do let's see if we can figure out how to do this we're going to add another lf statement and this time we'll check if players equal the rock and computer is equal to paper and if so we'll return paper covers rock you lose so we're going to make this kind of easier by just copying this code and then i'm just going to paste in this and then i'll just change this so players equal the rock and computer is equal to paper instead of scissors paper and it's going to say paper covers rock you lose and we won't even have an exclamation point anymore because it's not exciting to lose okay and you can kind of see there's a few we could add a few more elif statements to cover all the different situations but instead we're going to talk about refactoring refactoring is the process of restructuring code while keeping the original functionality when created pro when creating a program it's common to refactor code to make it simpler or more understandable so we are actually going to refactor this code that i've highlighted now and we are going to instead use a nested if statement a nested if statement will make the code more understandable at a quick glance like so you can put an if statement inside another if else or else statement so you'll notice here the first elf statement is if player equals rock and the second l of statement is if player equals rock so see if you can figure out how to refactor this to not have to use the and anymore we're just going to use one if statement and one else statement and then an if statement under that elif statement if that doesn't make sense you can just see what i do right now so i'm going to just move this down a little bit i'm going to actually copy and paste some of these items but we're going to start with l if player equals rock we're not going to have this i'm going to put this on a new line and say if computer equals scissors so first we're going to check if player equals rock and then if so we're then going to check it's going to be a nested if statement if computer equals scissors and if computer equals scissors then we're going to use this this return statement here so i have to make sure it's indented correctly it's going to re so this we have we have player if player equals rock then if computer equals scissors we'll return oh this needs to be indented one more time to be on inside that if statement and now we don't even need this elf statement this can just be an else statement else because if the computer equals scissors there's only one other option because we already know if player equals rock and computer equals rock will have already returned it's a tie and by the way once you return something the rest of the code in a function does not run so if we're returning it to tie nothing else after that is going to run so we know that computer can't equal the rock at this point so it's either going to be scissors or paper so i don't we don't even have to check if computer equals paper because at this point computer has to equals paper and then we'll just return this this line let's see there we go return paper covers rock you lose so now we just basically have to add two more sections similar to this so this one is if player equals rock then we have to have another section if player equals paper and then if player equals scissors and then we just have to have the the stuff inside is going to be pretty similar just corresponding to the different relationships between rock paper scissors so i'm just going to copy that and then i will paste it here and then one thing is important to make sure this elif statement lines up with this else statement and this is now going to be paper and then we are going to check if computer equals rock and a computer equals rock then we will say that paper covers rock you win or we'll say scissors cuts paper you lose and then the final one which at this point i'm sure you can figure out on your own we're going to add one more section and this if player equals scissors and then first we're going to check if computer equals paper if so we will do scissors cuts paper we're just making sure we're just making it so every time the first one is you win the second one is you lose but you could do it the other way around and then we will do rock smashes scissors you lose okay we're almost finished with this whole program so both the get choices function and the check win function they're both complete now let code to call the functions and play the game so first let's remove this this check when now we'll create a variable called choices and make it equal to the result of calling the get choices function and we just have to make sure it's not indented it's on the the first the first column i guess right here not ended at all so we'll do choices equals get choices [Music] and one thing about this is it's going to return a dictionary so if we look at the get choices so it's returning choices and it's going to be a dictionary like this now let me just copy this i'm going to show you something down here i'm going to just paste it down here and we'll just make an example of what it could look like it could look like rock and paper i always use rock and paper as examples because scissors is a little harder for me to spell so so that's a little easier so so let's one thing we haven't talked about is how to uh how to access a and specific element within a dictionary so this is a dictionary so let's say if i call this um well i'll just call it choices even because we're going to delete that and so we're only going to have this choices but if choices equals this and let's say i just want to get the the choice of the player let me show you how i would do that i'll just do p choice for player choice and i'm going to put equal choices and to get just the the value of the player i'm going to put brackets so the brackets look like that and then i have to put the the key that i want the value of so the key would be player so if i put the name of the dictionary which is this and then i put some brackets we're going to use brackets to identify what is the key that we want the value of so here's the key of the with the value of rock and here's a key with a value of paper so this is how we can get the player choice and i'm sure you can under see how you get the computer choices if instead if we take this computer word and put it right here uh computer okay i'm just going to get rid of all this here and we're going to we have the get choices here and now listen carefully to what we're going to do next we are going to create a variable called result and make it equal to the result of calling the check win function and when we call the check win function we're going to pass in the value of the player key and the computer key of the choices dictionary so let's do that so then you'll see what i mean a result is going to be we're going to call [Music] check when and then we are going to pass in we're going to pass in we have choices player and choices computer so because remember we had that we i showed the example that dictionary so we're getting the player key the value of the player key and the value of the computer key so now we know who wins we've now this result variable is going to be one of these strings have been returned either it's a tie rock space of scissors paper covered rocks and so on so now we just have to print the result we're going to print the result okay we can try out this game i'm going to click the run button okay this is why it's sometimes better to test a little earlier i just forgot the semicolon on some of these so um semicolon and see there's a red arrow i should have seen that semicolon and semicolon okay now let's try it i'm going to play the program into a choice i'm going to do rock and i just noticed something else i want to change so enter a choice here i started there's a parenthesis here there's no parentheses at the end so again i'm just going to change that really quick so enter a choice and we're going to put it in parentheses here and test again so rock okay you chose rock computer chose rock it's a tie okay i'm gonna play it again paper you chose paper computer chose scissors scissors cuts paper you lose okay we just created a python game so hopefully this gives you a better understanding of what it's like to program in python and you you now know about some of the basic concepts of python now there's a lot more to learn in python and we're going to be covering a lot more in this course i just wanted to start with a game and a full program so just right off the bat you could go to program so in the next section i'm going to start going over in detail all the most common features of python and we're going to cover some of the features that we've already used in this game plus a lot of additional features additional common features that were not used in this game and then in the final section of the course we're going to code a more complex game a blackjack game so let's get started with the next section one of the quickest and easiest ways to get started with python is by using replit.com but you may also want to get python running on your local computer so if you want to do that you can start by going on over to python.org and these go to the downloads menu and then you're going to just click what you want to download for it for so it's going to default to be for you the operating system you're on but you can also go to other platforms and make sure you can and then just find the platform that you want to download on and there's going to be instructions on here that's going to tell you how to go about getting installed on your specific computer so there's a few different ways to run a python programs and one of the ways is with an interactive prompt so after you get installed if you open up your terminal and type in python or sometimes it's going to be python 3 depending on how you got it installed you're going to see this interactive prompt and then you can just this is called a python rebel it's it's different from a rebel creating with created with replit but you can start coding in python right on here so i could say name equals bow and then you have to make sure you put the the quotation marks at the end and now i've gotten a variable stored as bow and then i can just type in the variable name name and it's going to show you show me the value of the variable and you can type in most different python commands right into this inactive prompt here and then i can just quit it when i'm ready to quit it's also common to run python using visual studio code so if you just search for visual studio code you can get to the the download page and then you can just download it for your system and there's also you can download for different systems and then once you open up visual studio code to get python working you're going to want to install the python extension so i'm going to click over here to extensions and you can search for python or it may just be listed here under popular extensions and i'm just going to click install and this is going to make it easier to work with python on visual studio code so now i can just kind of close some of this stuff here and i'm going to create a new file and i can just call the and i can just type in name equals bow print name and then if i save this as test.pi it's going to now it's going to add the colors that correspond to python and then i'm just going to click this play button here and it's going to play it's going to open up a terminal window here and it's going to run the program and it's going to print bow that's what my program did if i zoom out a little bit you'll be able to see the difference so well we just print the name and it and it runs the program just like that and then you can see on the terminal how the the command that was used to run that so we could use the same command on any terminal and instead of typing this whole thing for the location of python 3 i can just do python 3 and then you this is where that file is located so just copy that and i can paste it in here and it's going to run that program in this section we'll learn about the core features of python i'll go into more detail about some of the things we learned in the first project and they'll be covering a lot more concepts this section was heavily inspired by the python handbook by flavio copes and you can check that out on freecodecamp news and like the first part of the course i'll be running python in replit so once you get logged into replit just like i already showed you before you can hit the plus button here or the create button to create a new replit and then you can search for the programming language or you can just click it down here python we'll just create a python repel and then we can instantly start creating writing python code in replit so like i showed before we got our different files here we're just going to start by using one file here and this we're going to encode and this is where it's going to appear if we we run the code so i'm going to close off the list of files here and let's just start at the beginning again so you've gotten used to coding in python through creating a rock paper scissors game but now we're going to kind of do a deep dive into all the basic commands of python so there's going to be some review but we're going to be going into more detail about each of the elements and the first thing we're going to talk about is variables so we can create a new python variable by assigning a value to a label using the equal sign or the assignment operator so let me give you an example just like i was showing you before just name equals bo so let me just zoom in a little bit more here and so now our variable name is name and we've assigned it the value of bo and then we can also uh create we can create a variable with a number so i could do age equals 39. so a variable name can be composed of characters numbers and an underscore character but and it cannot start with the number so it could be anything like name one it could be all capital letters it could be it could have an underscore it can start with an underscore like i said like that and you can see that these are all it's putting these red squiggly lines because it's showing that that's not actual python code if you're going to create a variable you should be assigning it to a value or you should be using a variable that already exists but i'm just showing you some different examples of different variables now so here's an example of an invalid variable name if you just start with a number like that that can't be a variable because you can't start with a number and i couldn't put something like test exclamation point you can't use exclamation points you can't use percent signs and other than that anything is valid unless it's a python keyword so there are some keywords a keyword is something that's used to to write python like for if while import these are all words that have very specific meanings within python so you cannot use them for a variable name now there's no need to memorize them as the python editor here will alert you if you use one of those as a variable so that was just like if i say if equals hi and then you can see it's going to show you right here with these squiggly lines that we've done something wrong invalid syntax because and then also you can see that it turns blue this word turns blue because it's a keyword you can't use it as a variable name so like i said it's going to alert you if you if you use a keyword as a variable and you'll start to gradually recognize them as part of the python programming language syntax now let's talk about talk about expressions and statements in python so an expression is any sort of code that returns a value like for instance if you do one plus one or if you just do a string like bow this is going to like this is going to return to this is going to return the string bow so a statement on the other hand is an operation on a value so for example these are this is a statement here because we have an operation we're assigning this to the variable and then another statement would be like this print name so that's going to be a statement because it's doing something to the value now a program is formed by a series of statements and each statement is put on its own line like we have these two lines here but you can use a semicolon to have more than one statement on a single line so i i could put a semicolon here and then if i run the program it's still going to print the name and let's just do that we already learned how to run a program in replica click this button right here but we can see it's going to print bow and if i put these on two different lines it's going to do the same thing if i run the program it's going to still do the same thing here now let's talk about comments this is something we haven't talked about in this course yet so in the python program everything after a hash mark is ignored so if i put a hash mark i can say this is a commented line and when we run the program this line is going to be completely ignored and then we can also put in inline comment if i just put the hash mark here this is an inline comment and the cool thing about most code editors including replit is it's going to put comments going to make them gray so you know that this isn't really part of the program this is just some sort of special note that the programmer wants to put as part of the program so i want to emphasize again how important indentation is so it's very meaningful in python so you can't randomly indent things like you can't just press tab here to indent here and how this is kind of lined up here this line up here you can see this red squiggly line says unexpected expected indent so some other languages do not have meaningful white space an indentation doesn't matter but in python indentation matters so in this case if you try to run this program we can run this and you'll see an error right here showing up in red here it says indentation error unexpected indent because indentation has a special meaning so i can just unindent that here everything indented belongs to a block like a control statement or a conditional block or a function or a class body and we'll be talking more about those different blocks now let's talk about data types python has several built-in types so for instance this is a string so anything surrounded by quotation marks is a string that's one data type and you can check the type of a variable by using the type function so i could say type and then i'll put name and to make sure to be able to see in the console i'm going to print what the type is here and if i press if i run the program we'll see that the type is the class of str which stands for string and then we can test to see if something is a string by comparing it to str so i could do equals equals str and then if i run that it's going to say true because the type of name does equal a string and then we can also use is instance so i'm going to uh so if we instead of doing type we do is instance and then we have to pass it two things so the first thing we're going to pass it so we have the is instance we're passing it the name that's this variable and str we're trying to see if name is an instance of a string and if i run that it should say true again so we've been testing against the str class the string class but it works the same for other data types so so there are some data types around numbers so an integer number integer numbers are represented using the int class or the int class and floating point numbers or fractions are a type of are the type float so i can say age equals 2 and then we can just check is instance and i can pass in the age and then i can pass in an int so if i run that we're going to see that i've done something wrong oh i spelled that wrong there we go okay now i'm going to try this and we'll see true true and i can also type in float true false it's not a false or it's not a float because it doesn't have a decimal point if i did 2.9 then it should show that it is a float because it has a decimal so python automatically detects the type from the value type so it automatically knows this is a string it automatically knows this is a float but you can also create a variable of a specific type by using the class constructor passing a value literal or a variable name like for instance we have this and we check to see if this is a float and it's saying false but i can make it a float by typing in float and just p putting the value into the flow here so we're going to make it a float so now it's true true and you can do the same thing with strings or integers or other data types and you can also convert from one data type to another by using the class constructor so so that's basically what we did we just converted this from an integer to a float but i can also do something else i can convert something from a string to an integer so for instance i'm going to we'll just get rid of this one completely here and we'll just use this one so a string is anything in quotation marks so if i do 20 age 20 and i test if this is a an int it's going to say false it's not an n so i'm printing whether it's an instance of an int but i can convert this string into an integer by just doing integer and this let me run the program and it says true another thing about this is you don't just have to pass in the actual data or the actual string i can pass in a variable so i can say number equals and now i'm going to make it a an x it says number but it's actually a string but i can pass in the number here and then it's going to set that to age and it's going to be true so we create the string we convert the string to an integer and we tested that that age is an integer so when we do something like this this is called casting we are it's basically trying to extract an integer from this string of course the conversion might not always work depending on the value that's passed so for instance if we write test here in the string instead of the 20 we may get an air so let me just run this and see now we have an error it says invalid literal for for int int with base 10 test so we can't convert the word we can't convert the string test to an integer so python does its best to do the conversion but it doesn't always work there are a few other types so let me see are some other common types of types so there's the type of complex for complex numbers bool for booleans list for list tuple for tuples range for ranges dict is our dictionaries and set is a type for sets and we'll explore all these soon we'll go into more detail about about all these different types of types well now let's talk about operators we've already seen one operator that's this one that's the assignment operator but there's also arithmetic operators comparison operators logical operators bitwise operators and plus some interesting ones like is and in so we're going to be going over a lot of those right now so we talked about the assignment operator which is used to assign a value to a variable or to assign a variable value to another variable now let's talk about arithmetic operators it's just what you use to do math mathematics so here are the different arithmetic operators so we have plus one plus one equals two then minus multiplication division we have remainder so four divided by three equals one but there's a remainder of one we have exponents four to the power of 2 is 16 and floor division so floor division does a division problem and then just basically rounds down so floor division does the division and rounds down to the nearest whole number so actually this would be better seen if we do four five divide by two five floor division divided by two is going to be two normally be 2.5 but floor division is rounding down to the nearest integer the nearest whole number and then also note that that the minus can also be a make something a negative number so i could do 4 plus negative or i mean 1 plus negative 1 and then that's just going to equal 0. and then the plus operator can also be used to concatenate string values that's something we talked about earlier but i could say scamp and then put a plus is a good dog and then like if i print this out i put the the parentheses around it i can and then we'll see the whole string here sk scamp is a good dog that was the name of my first dog when i was a kid so we can also combine these arithmetic operators with the assignment operator let me show you what i mean so let me just get rid of this here and i'm going to do age equals 8 and age plus equals [Music] 8 and i'll do print age so we've so all these different operators can be assigned with it can be combined with the assignment operator and now it's going to add 8 to the age so if i run this it's 16. so this actually just means age equals age plus eight so this age plus equals eight is the same as saying age equals age plus eight so it's just going to add this number to the current age and set it equal to the age and you can do that with any of these like i could do times and that would be age equals age times 8 and 64. and so on with any of these arithmetic operators okay now let's talk about comparison operators now we talked a little bit about them before but let's see some examples again so this is to compare if two things are equal and then we have not equal we're comparing them to see if they're not equal or count this is if a is greater than b or more than b and then this this is less than or equal to b now let me just tell you a trick of how i keep the keep track of which one is greater than and which one is less than if you see this less than one if you kind of tilt your head a little bit it kind of looks like an l see like l and this one doesn't look like as much of an l so this less than operator kind of in some ways looks like a capital l that's kind of just squished over and that's how i keep track of which one is less than which one is greater than and so these are all going to give either a false value or a true values speaking of true and false true and false are examples of boolean the boolean data type the boolean data type just means true false or true so a boolean is either going to be true or false there's only two options and there are a few boolean operators so let me show you what the boolean the boolean operators are either not and or or so when working with two or false attributes those work like logical and or and not so when you're using uh not it means it's not true you're checking you're checking to see something is not true and means they both have to be true and or means either this one has to be true or this one has to be true in order for the full thing to be evaluated as true and let me show you something about or now or using an expression returns the value of the first operator operand that is not a false value or a falsie value otherwise it returns the last operand so it's going to return the first operand that is not a false value but since this is a false value it's returning the second operand since this is a false value it returns the second one since this is not a false value it will return the first one and this is considered a false value if it's just an empty bracket that's false so it's going to return the second value which just happens to be false and since this is a false value it's going to return the second option which also happens to equal to false so one way to think about it for the word or is so the pi this is how the python docs describe it if x is false then why else x so this would be like x this would be y if else is false then why else x and then for and down here let's look at some examples for and and only evaluates the second argument if the first one is true so if the first argument is falsy such as false zero and empty string empty brackets it returns that argument otherwise it evaluates the second argument so the way the way the python docs describe it is if x is false then x else y okay let's quickly discuss bitwise operators they're very rarely used only in very specific situations but it's worth knowing what these bitwise operators are just in case you're in the very rare situation that you need to use them and then two other types of operators are is and in now is is called the identity operator it's used to compare two objects and returns true if both are the same objects if both are the same object and i'll be talking more about that later in the section on objects and then in is called the membership operator this is used to tell if a value is contained in a list or another sequence and we'll be talking more about the in operator when we're discussing lists and other sequences later in this course and the final thing i want to talk to you about is the ternary operator now the turn area operator in python allows you to quickly define a conditional so here will be like kind of the slow way to do it without a ternary operator so let's say you have a function that in this function is comparing age with 18 and it's going to return true or false depending on the risk result so instead of writing like this we can implement it with a ternary operator so let's do death [Music] is adult i'll call it is adult 2 because it's the second way of doing it and this time we're going to use the ternary operator it's just going to be return true if age is greater than 18 else false so you can see first we define the result if the condition is true then we evaluate the condition and then we define the result if the condition is false it's basically an if else statement all on a single line okay let's talk more about strings in python so a string in python is a series of characters enclosed in quotes in double quotes or it could be single quotes as long as the type of quote is the same on both sides and we already talked about how you can assign a string to a variable [Music] and we already talked about how you can concatenate two strings using the plus operator like phrase equals bo and then you can concatenate with the plus operator is my name [Music] and then also instead of putting a string here you can put the variable so i could put name is my name and we already have the variable here to equal bo so when you concatenate you can concatenate the strings or the variables you can also append to a string using the plus equal operator so let's say i want to add to this name and i'm so i'm going to say name plus equals is my name so we're adding is my name to the end of this so i can say print name and then we can see what it looks like when you use the plus equal operator so bo is my name and then we already talked about how you can convert a number to a string using the str class constructor like if we had age equals we could make this a string but we passed this integer it converts to a string and now it's going to be a string now here's something new a string can be a multi what can be multi-line when defined with a special syntax so if you enclose it if you enclose the string in a set of three quotes so let me show you an example get rid of all this and i'm going to print an entire string here so we're going to make this a multi-line string i'm going to put three quotation marks and then it's going to start with three quotation marks and end with three quotation marks and then i can make it multi-line so i can say bo is and then i can put some extra lines 39 years old now if i print that and you can see it's going to print the different lines here so we just made a multi-line string and you can also instead of using the double quotes you can put a single quote as long as they're the same at the at the beginning and ending now a string also has a set of built-in methods let me show you an example so if i have this string bow but i'm going to put at the end of the string i'm going to put dot upper and i put parentheses at the end so if i run this now it's going to print it in all capital letters and the same thing you can use with lower so if it if i had a string that had a few capital letters okay now it's all lower now i can also type in a title and this is going to make each lut so i can say bow person uh and i do this so it's going to cat it's going to a title that's going to make the first letter of each string a capital letter i can also check things like i can say is lower and it's going to check if it's all lowercase letters false but if i make it so it is all lowercase letters it's going to say true so here's just a list of a few common ones [Music] you can do is alpha to check if it contains only characters is l num to check if a string contains characters or digits and is not empty is decimal lower to make it lower case is lower upper is upper title starts with to check if it starts with a specific substring to check if it ends with you can replace part of a string split a string you can strip the white space from a string you can append new letters to a string you can find the position of a substring spring string and there's a few more but these are some of the most common things you can do with a string and then one thing to know about these is that they they all return a new modified string they don't actually alter the original string so let me show you what i mean by that so let's say we have we'll do name equals bow again let me zoom in a little bit and we're going to print name dot lower now i'm going to print name so if i just run this and we first figure out what went wrong here it looks like there's a few extra parentheses [Music] okay let's run this and you can see it's going to make it all lowercase but then when i print the name again it's not still lowercase because this just returns a brand new modified string it doesn't actually change anything in the original string and then you can use some global functions with strings as well so one function we haven't discussed yet is the l e n function which stands for length it can give the length of a string so i'm going to type an l-e-n and then so there's just some global functions that work with a lot of different types of data and the length of this is four you can see and then you can use the in operator now i briefly mentioned the n operator earlier so let me show you one use case so we can use the in operator to check if a string contains a substring like for instance i can say a u in name so let's check if name contains the letters a u well true it does but if if if it if it if it didn't if i just add an extra string it's going to say false okay another thing with strings um escaping is a way to add special characters into a string for example let's say we wanted to add a double quote within the string how can i add a double quote into a string that's wrapped in double quotes if i put a double quote like that that's not going to work because this is going to be the string and then it's not going to the code editor is not going to know what to do with this last little bit here so the way to go is to escape the double quote inside the string with the backslash character so right before this quote i'm going to put the backslash character and then you can see it now all is all the same color as a string and if i print it it's going to it's not going to print the backslash character so putting a backslash is how you escape a character and that just means this the the backslash character means that the next character is not going to mean what it normally means it's going to actually just be the string of that character and you can do the same thing with so with in this particular example you may not need to do it because you can always just put a single quote at the beginning and ending and as long as you have a different type of quote at the beginning and ending then you can put a double quote in the middle but let's say you want a string that contains both a single quote and double quote within the string then you will have to backslash like if i just put a single quote there it's going to mess it up but if i put it backslash now it's going to have the single the double quote and the single quote right within the string and you can also use the escape character for special formatting characters like uh for instance what if i want there to be a new line between the first two and the last two letters of the string if i do slash n that is going to not actually just put a slash in let's see what happens when i put that this is means new line you can see it says be new line a you and then another way a reason why you may want to use an escape here like let's see what happens if i do this this that's not looking how i want to look because it's normally normally when the code is running if it sees this backslash it thinks it's an escape character so if you want to actually add a backslash to a string you have to escape the backslash so now it's be backslash au okay we're done talking about escape characters now i'm going to tell you how you can get a specific character in a string so given a string you can get its character using square brackets to get a specific item given its index starting from zero so one thing to know about programming is that whenever you're counting from in most programming languages you start counting starting at zero so this is going to get the letter at index one so this is index zero the b the e is at index one index two index three so if i run that we can see we are getting the e that's at index one if i want to get the b i just put a zero in the brackets and we get the b and then we can use a negative number to start counting at the end so if i put negative one it's going to start here zero one and that's going to be a oh you okay i guess when it's going backwards it's not going to start zero because there is no negative zero that makes sense so negative one is going to be the last character in the string so negative one negative two negative three and so on we can also use a range using what we call slicing so if i put 1 colon 2 this is going to be every character starting at index 1 and ending before index 2. so it starts at index 1 so it starts with that character and it ends before an x2 which is a so that's actually only going to return an e but if i put 3 here now we can return a u and if i put bo is cool we can put one further down i'm going to put 7 and we can see it's going to return part of this string and then you can also start if you just put a blank before the colon then it's going to turn everything up to it's going to start at the beginning and return everything up to character seven and you can also do in the opposite direction so if i put a blank after the colon it's going to go to the end of the string so it's going to say is cool so let's talk about booleans well we already talked more about we already talked about booleans but we're going to talk a little bit more about boolean which is considered the bool type and this can have two values true or false so i can say done equals true or you can do done equals false now notice that it always has a capital t or a capital f so if you don't put a capital t or capital f it won't be considered the the true boolean value in python and booleans can be especially useful with the conditional co with conditional control structures like if statements well we already discussed if statements in the first part of the course and we'll be discussing them more in detail later but let me just show you an example so if done and i'm going to erase this done because we want to be true so if done and then we'll say print yes [Music] else print no okay so i can run that and it's going to print yes because done equals true but if done equals false [Music] then it's just going to say no so when evaluating a value for true or false if the value is not a bool or boolean like if it's not true or false we have some rules depending on the type we're checking so numbers are always true except for the number zero if i put 0 here it's going to evaluate to false but if i put any other number here it's going to be true even like negative 1 or anything like that it's going to be true oh i guess that i didn't put negative 1 i put equals 1. so if it's negative 1 that's going to be true so strings are always false oh strings are false only when empty so if i say bow here this is going to be true because it's not an empty string but if i make an empty string then it's going to be false lists tuples and sets and dictionaries which we'll talk about more later are false only when empty so it's going to be if a list double star dictionary is is filled with something that is true and then also you can check if a value is a boolean so if i say done equals true i can do print type we're going to check the type we're going to check if the type of done equals bool so let's check it does that equal boolean true it does now let's see let's change this to a different type and it's going to say false so it can still evaluate whether this is true or false but the type is not a boolean the type is a string and let me show you another example code so the global the any function it's a global function it's very useful when working with booleans it returns true if any of the values of the iterable such as a list if any of them are true it's going to return true for all of them so for instance book one read that's true but book two read that's false but this is going to return true because it's checking if any of them are true and then it's going to set this to true now the all function is is similar but returns true if all of the values are true so we see we have this value as true we have this value as false whereas any would have returned true this is going to return false because it only returns true if all of the values are true okay now let's talk about more number data ties we already talked about int an integer whole number we've already talked about float which is any number with a decimal point there's another type called complex complex numbers are an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part imaginary numbers are real multiples of the imaginary unit which is the square root of negative one often written i in mathematics or j in engineering python is built in support for complex numbers which are written with the the j notation so the imaginary part is written with a s with a j suffix so you can combine it you can use a literal value like complex equals two plus three j so the the j means it's the imaginary part of the number or you can use the complex constructor so i can put num equals complex and then i can pass in two comma three so the three part is the imaginary part the two is the the real part the integer part and then once you have a complex number you can get it's real or imaginary part like this so i can say print [Music] num dot real or num dot match so this is going to be the 2 this is going to be the 3. so if i just uh let me i think the problem was num num one no so i'll do num one and num two and we're gonna do this as num two okay let's check this so this is the real part this is the imaginary part you can see they're being returned as floats and you can use the type function to check the type so now let's talk about some built-in functions that help with numbers so one of them is abs abs will return the absolute value of a number so if i say 5.5 that's just going to be 5.5 but if i put negative 5.5 well it will be 5.5 so [Music] so if i print this see 5.5 basically it just makes it so it's not negative then you can also use round so if we do round let's make this just 5.5 round is going to round to the nearest integer so if i do this it's just gonna be six so point five is going to round up but if we did uh four nine it's going to go down to five you can also specify a second parameter to set the decimal points precision so i can go to if i do one here and i round it it's going to instead of rounding to the nearest integer it's now going to round to the nearest tenths place value or one decimal point there are several other math utility functions and constants that are provided by the math standard library like there's a math package a c math package decimal pages fractions package that makes it easier to work with different types of numbers we'll explore some of those more later on now let's talk about in nums and noms are readable names that are bound to a constant value so to use a noms we're going to have to import and numbs from the inum standard library module like this from enum import enum and now we'll be talking more about importing stuff from modules later but once you import it then we can initialize a new and nom in this way so do class state enum and so we can have inactive [Music] equals 0 and active [Music] equals one so basically the the word state this can be anywhere any word we like so we're setting uh basically a variable called state.inactive which is going to equal 0 or state.active to equal 1. so you can reference this how you would reference it you can do print state dot active and then if i just run the program we'll see now you can see it's just going to return state to active instead of one so to actually get the value you use state to active dot value and then we run that and then we'll see one here if you we want to just return state.active that the sa that value can be reached by the number assigned in the num so state we can do one and if i print that it's now going to say state.active same for using the square brackets notation so i could do states i'll do see square brackets and put active if i print that it's going to print state that active so this is basically the only way to create constants in python python is no way to enforce the variable should be a constant so some people use enums to create a constant and then nobody can reassign the value so when we do state or state active dot value so this is it's not going to be able to be reassigned so basically there's two ways to do we can do this bracket notation or we can go back to the other way active now we can also list all the possible values for enum so our num is called state and we can now just print all the values oh i actually did that wrong it's supposed to be a list so this is going to list the values of the state and we can see we have inactive 0 and active is 1. and we can also count them using the length function so we're going to print the result of a length state and that's just going to give us 2. okay let's talk about more about user input now we already discussed a little bit in our first program but you can do get user input by using the input function so let's just get rid of all this and we'll do age equals input and we can say print your age is and then we just can concatenate that with the variable age and then also if you want to so let's just do a quick test and right now it's looking for the age right now i can put five your age is five so there's two ways to make it say what is your age we can do a print statement right before here and do what is your age and then now we can put four your age is four now you can also ins instead of putting the print statement right before here i'm going to copy this delete that and we can put it right in this input function and then i'll say it'll still say what is your age and i can put an age here so one thing to really realize about this is that it gets the input at runtime meaning the program will stop execution and will wait until the user types something and presses the enter key you can also do more complex input processing and accept input at program invocation time and we'll see how to do that later on if you want to get the input when the program is run that's going to work better for command line applications other kinds of applications will need a different way of accepting input let's look more at control statements this is another thing we've already discussed earlier but we're going to review it and and look at it in a little more detail so a control statement is like an if statement so if condition that's this variable here equals true then it's going to run everything in the block a block is the part that is indented one level usually it's going to be either four or two spaces in this case it's four spaces sometimes it's two spaces it doesn't matter it could even be one space as long as it's the same as long as every line of code is indented the same amount so if i just run that the condition was true the block can be formed by a single line or multiple lines and it ends whenever you move back to the previous indentation level so for instance if once we are not indented i can say print outside if so then that's always going to pres it's always going to print this because it's not in that if statement and then we have the if else statements where the else is if if this does not true then it's going to do whatever is in here so if i just change this to false then it's going to print whatever the condition was false and then we can have this series this is something that we showed in the per the program earlier but if and then elif combines else and if so if this is not true then i'll move on to this line and else if this is true then i'll do this else if this is true and it'll just keep going on and then it will always do the this is if none of the other ones were true it's going to do this so since it was testing this it's not even going to evaluate anything later but if we move this to false and we change this to bow then it's actually going to skip all the way down all the way to this else here and if we do flavio you can print that and then it's going to say hello flavio from right here okay that's all we're going to talk about for this for now since we've already covered it earlier in the course now i'm going to go into more detail about lists lists are an essential python data structure and so an example of a list would be let's create a list called dogs so we're going to create the dog names we have roger we have sid and this allows you to group together multiple values and reference them all with a common name so we have a list of dogs and this is just two strings so the list always going to have the opening closing brackets and each item in the list is going to be separated with a comma and a list can hold different types of values so these are all strings but we can have a string an integer a string a boolean and you can mix different types of data types in a single list and then you can check if an item is contained in a list with the in operator so we talked about the in operator earlier but let me show you how that works so we're going to print here's where we can use the in operator we're going to check if roger is in dogs so let's see so run that true but now let's check if bo is in dogs well false because it's checking so this is how you can check if an item is in a list you can also define a list as an empty string so i could actually just remove all this and now we just have an empty list and this is obviously still going to be false because there's nothing in that list but let's go back to when we had some items in the list and you can reference items in a list by their indexes starting with zero so i'm going to do dogs and then i can use these brackets so and now i'm going to put the so this is where we're going to reference the thing an item from the list and i'm going to type in 0 which will be this item right here roger or i could put 2 and it's going to do 0 1 2 and now we're going to have sid and the same and you can use this same notation to update an item in a list so i'm going to add another line of code here and put dogs 2 is going to equal bo and now i'm just going to print the entire list here and now instead of being roger 1 said true to roger 1 bow true because we've updated the item at index 2 to be bo instead of sid now you can also use the index method so um instead of like if i want to find the first item in the list i could do it like this so you can also use a negative number here just how we saw on the string so negative 2 is going to start with one two actually let's do negative one so it should return true here okay true so it starts with this one if you put a negative number you can also extract part of a list now this is very similar to what we showed using with the string let me just add another item here [Music] now i am going to use the colon to do part of a list so i'm going to 2 4 and so this is a slice so it's going to start at the second or zero one two which is now bow because we change it to bow and it's going to go through four it's going to go through four but not over pat not including four so it's going to be 2 3 and then not 4 so it's just sid and true or bow and true because we updated 2 to bow and you can also just leave this blank so it's going to go through the end of the list or if you leave the first number blank it's going to go it's going to start at the beginning of the list and we can go through for instance index three and so that's a way to slice the list you can also use the the length function so let's find out how many items are in the list i'll use the length the length of dogs is six or six items in the list we can also add items to the list by using the append method so i'm going to do dogs dot append and then i can add an item so i can say something like judah and now if we see the length there's now going to be 7 and if we just print the full list then we can see that we can see all the items including the one that was just added we can also use the extend method the extend is another way to add an item to a list so if i do instead of dogs append i can do dogs that extend and then i'm going to pass in instead of just passing in the string i'm gonna pass in the item as a list so i'm gonna and it's gonna add it just the same but now i can actually combine two lists together so i'm gonna put a five so if i do this we can see now we are taking this list and extending it by adding this list on the end this is a two item list and we have that six m list and now we have the eight item list you can also use the plus equals operator so to use the plus equals operator i'm going to do dogs it's the same it's going to do the same thing as extend so plus equals and then we have this list take this parentheses off here and it should look exactly the same see it's showing up the same thing up here so the plus equals is going to be the same thing as extend where it takes the list that's already exists and adds this other list to the end and when you're using the extend or the plus equals you don't want to forget the square brackets here so if you if you forget the square brackets and let's say i'm just going to add this iron to the list it's now actually going to put each letter individually here so if i you can kind of see it better if i move over here so it so that so you want to make sure you put the the brackets and another thing you can do is remove you can remove an item using the remove method so i'm gonna do dogs dot remove sid okay now i'm gonna play it here and it's saying what did i do wrong here oh obviously um i'm moving sid but we've already changed the element of sid to bow so let's remove quincy and let's try that okay so now there's no quincy so another common thing to do another common list method is pop so if i do dogs.pop it's going to remove and return a single item so first i'm going to [Music] do dot print dogs that pop and then i'm going to print dog so if i so first it's going to return 5 that was the last item that we added onto the list and now when i print the list that item's not in the list so pop is going to remove the last item from the list and it's going to return the last item it's going to return and remove the last item from the list and then it's not on the list anymore now let's make this let's let's simplify this just go back to the initial list and i'm going to change this to items now i'm going to show you how to add an item in the middle of the list at a specific index you can use the insert method so i'm going to do items dot insert i'm going to put the index which is going we're going to insert at the index number two and the item is going to be test and then i'm just going to print that print items and then i'll run that and then we can see it index number two we now see the item test now to add multiple items at a specific index you need to use slices so let me show you how you do that so we're going to do a slice and i'm going to set that equal to test 1 test 2. we print that so now you can see we have test 1 and test 2 right here right behind this search thing here and we've inserted multiple items into the list starting at index 1. now you can also sort a list so if i do here we go um items dot sort it will sort the list but you have to make sure okay we have an error it's not supported between we have a combination of ins and strings so let's make it so it's all strings in the list and then it should be able to sort it okay now the strings are in alphabetical order and if we're using integers or floats and they would just be in numerical order now one thing that's interesting about that if i put change this to bow you'll see now we have this at the beginning and this at the end so a the sort method orders uppercase letters first and then lowercase letters so to fix that actually to make it make more sense we're going to change that to bob and to fix that within the sort i'm going to i'm going to put key equals str dot lower and now it's going to sort these correctly how you would imagine not caring about uppercase or lowercase letters sorting modifies the original list content so to avoid that you can copy the list content using so let me show you if we do items items copy equals items and then we make a slice with with nothing at the beginning and nothing at the end so it's going to start at the beginning of the list to the end of the list and now we can have a copy and i can print items copy so if i print that so now we see we have the sorted list that's that we ran the sort on but we also still have the original list so it with all the words in the original order and there is also a way to sort a list without returning a new list there is also a way to sort a list without modifying the original list so instead of copying a list um what i'm going to do is i items instead of doing items dot sort we are going to do we're going to use a global function called sorted so in the sorted function we are going to pass in two parameters so first is the list items and then the second is how we're sorting it so this just makes sure that the key the case of the letters don't matter and then i'm just going to print that now if i run this you can see we it we print printed the sorted list and now we're printing the list and it's not it's no longer sorted because this creates a new list without modifying the original list okay now let's learn about another data structure called couples so this time i'm going to put tuples so we're using a comment here so tuples are another fundamental python data structure they allow you to create immutable groups of objects this means that once a tuple is created it cannot be modified so we already saw that we could modify lists but tuple you can't even add or remove items they're created in a way similar to lists but using parentheses instead of square brackets so for instance i'm going to do names equals instead of using square brackets we're going to do parentheses roger and sid okay so a tuple's order like a list so you can get its values by referencing an index an index so i could say for instance names and if i do the bracket i could put a zero here to return roger and then you can also use the index method for instance names dot index and then i can pass in something like roger and then this is going to return 0 because it's going to get the the index number of that so as with strings and lists using a negative index we'll start searching from the end so i could do that i can do negative one to start not negative zero negative one to start searching from the end here and you can count the items in a tuple with the length function so i could do if i do length and then do names it's if i printed that it would just print 2 because there are two items in that tuple then you can also check if an item is contained in a tuple with the in operators very similar to a list so i can do this time i will print it i'll do print roger in names so if i print that and run it we'll see true because roger is in the names and then you can extract part of a tuple using slices just like we could do with with strings and lists so i could do names and then i could do 0 starting at the whoops 0 2 so that's just going to start at the zero index and be done at the index 2 and then and then you can use the so you can get a sorted version of the tuple using the sorted global function so remember when we were looking at lists when we used the sorted function it created a new a new list or so when we're creating using the sorted function for tuples it creates a new tuple so i can say sorted [Music] names and this would put them in alphabetical order they already in are in alphabetical order but say there is one more word in this list and then i can print this [Music] to print the sorted version but it's not actually going to modify the list because you cannot modify a tuple and then you can create a new tuple from existing tuples using the plus operator so i could say something like new tuple [Music] equals names and then i can use the plus operator and then i would say i would just say tina and quincy i could add a few i could add so these will combine two tuples into a new tuple but you can never like i said you can't actually modify the original tuple now let's learn about dictionaries dictionaries are another very important python data structure while lists allow you to create collections of values dictionaries allow you to create key value pairs we already discussed dictionaries a little bit but now we're going to discuss even more about dictionaries so let me give you an example of a dictionary with just one key value pair so dog equals and then we're going to use the curly braces to create the dictionary and i'll put name and then i will put roger and just like any type of strings we could make these single quotes or they could be double quotes and the spaces here are not very important but it's common to put spaces in between these things for better readability and the key can be any immutable value so this is the key this is the value and the key can be any immutable value such as a string a number or a tuple the value can be anything you want so a dictionary can contain multiple key value pairs so like for instance we got the name we can have age and that's going to be 8. and you can access individual key values using the notation like this so i can say dog so i'm using the bracket notation i can do name so if i print this it's just going to print roger and then again i can use the single quotes 2 if i want and it still prints roger and then you can use the same notation to change the value stored at a specific index so let's say i want to change the name so if i do dog and i'm going to say that the name is now going to equal sid now i'm just going to print the whole the whole thing and we can see the name is now sid instead of roger so another way to get a specific element is to use the get method so if i do a dog dot get and then i do name so i'm going to try to get the name here it's going to return roger so one good thing about this is that you can add a default value like let's say i'm going i'm searching for color and it's saying none it's giving it none because there is no color but what if i want a default value so i'm going to put comma and then i'll put brown so now if it cannot find the color in the dictionary it's going to return brown but if it can find the color like let's say color and this is a green dog okay we'll return green so with the bracket notation that was showing you earlier you cannot have a default value so that's one good thing about the get method now you can also use the pop method to retrieve the value of a key and delete the item from the dictionary we also showed the pop method for lists so for instance i can say get dot pop and then i will pass in name and then right after that i'm just going to print dog that the the whole dictionary so first we're going to get roger and then when i print the dictionary here it's not going to show roger anymore because we we deleted it pop will return the item and delete the item now you can also use a function a method called pop item the pop item method well let me show you that one pop item it's going to retrieve and remove the last key value pair inserted into the dictionary so in this case it should be color so if i run this it's going to return color green and now when i print out the dictionary it's not going to show color green because that was already removed it removed the last item you can also check if a key is contained in a dictionary by using the in operator so we're going to say we're going to try to find out if color is in dog if there's a key called color in dog we run that and it says true another thing we can do is get a list with the keys in the dictionary using the keys method so if i do dog dot keys and then we'll run that it's going to show the keys so the keys are name age and color we can see that it's inside the thing called dick keys but we can also pass this into list so we return an actual just the list part so now we can see it's just an actual list name age and color then we can do the same thing with values so instead of dog.keys let's do values print that and you can see we have roger 8 green we can pass it into a list to return the app just the list here roger 8 green and then finally if we just do items [Music] it's going to return all the items in the list or all the items in the dictionary and convert it into a list so you can see this is the first item in the list this is the second item and then we have the third item here so we can see each item of the list each item of the dictionary is now in a list and then like a lot of the other things we can use the length function and i'll just put dog and we can see that there are three items in dog now you can also add a new key value pair to the dictionary so let's say i want to do dog food or i it doesn't even have to be a single word i could put favorite food and i'm going to say meet and now we're going to print that let's see what do we oh this was supposed to i did that a little wrong there we go this is actually how you do it you put use the bracket notation equals and let's put what it equals there okay now you can see that we now have a new item on the list favorite food meet then you can also delete an item from a list or a delete a key value pair so i'm going to d e l means delete dog or dog there we go and this time i'm going to delete color and i'm just going to use single quotes instead of double quotes to show you that doesn't really matter the type of quote and now you can see we don't know what color this dog is it's no longer a green dog and then you can also copy a dictionary so if you want to make two copies of a dictionary you can do do like this dog copy that's the name of the new dictionary i'll do dog dot copy and that would be the new copied version of the dictionary okay now we are going to talk about a new thing called sets sets are another important python data structure sets kind of work like tuples but they're not ordered and they are immutable so you can change them you can also say that they kind of work like dictionaries but they don't have keys they're all they have an immutable version of a set called a frozen set so let me show you how you would create a set so let's do names and you we're going to use curly brackets just like that and just like that so we have two names so you can see the differences the a dictionary you use the curly brackets but there's going to be key value pairs but this doesn't have key value pairs in a list it's just going to be a item after item like this but there's going to be brackets instead of curly braces so one thing about the sets is that they are not ordered so sets work well when you think about them as mathematical sets so for instance let's have we're going to create a set 1 with roger and sid and we're going to have a set 2 which is just going to have roger and so you can intersect two sets so uh the inner intersect the intersection of these two sets will be set one and set two so if i just print that out print intersect and then we can just run that and we're gonna see what so it's just roger so the intersection of these two sets are just roger the all the items that they have in common you can also create a union of two sets so instead of just calling this union i'll put mod for modification and so i can show a few different things with the same variable name and the union symbol is just the straight line like this it's not an i it's just the straight line it's on the same key as a as the was it the forward slash backslash one of the slashes now we're going to get every single item in both sets which happens to in this case just happen to be the same as set one but if we change this one to the word luna it's just a different name and now we're going to get each item in both sets or said luna roger for the intersection and then we can also get the difference the difference between two sets so let me change this to back to roger and for the difference between two sets i'll use a the minus and the difference is just going to be sid that's the only thing that's different between the two sets you can also check if a set is a superset of another and if a set is a subset of another so how you would do that is so we're just saying like is this greater than that which means it has everything of the in the other set true now if we put the other direction is does this set have everything in this one no it doesn't you can also count items in a set with the length function that's pretty self-explanatory i won't even show it to you we've seen the link function so many times you can also get you can also get a list from the items in a set by passing the set to the list constructor so i'm just going to remove this and we will do list set one okay so now we have a list of the set and then you can check if an item is contained in a set with the in operator just like the list and the other way we the other places we use the in operator and then one more final thing about a set a set cannot have two of the same item so that's another thing that's useful about sets so if i type in rogers now we have roger sid roger if i play this we'll see it's only going to print sid roger it's not going to add the roger twice to the set so that's another useful thing about sets is that make sure there's only one of each item in the the set so if you have a list that has multiple items you can convert it to a set um and then i'll just make sure there's only one of each thing in that set now let's talk more about functions we already talked about functions in the last section but we're going to do a review and then go into even more detail about functions so a function lets us create a set of instructions that we can run when needed and i'm just going to paste in a function and again the indentation it can be either four spaces two spaces as long as it's indented the exact same amount so functions are essential in python and in many other programming languages they help us create meaningful programs because they allow us to decompose a program into manageable parts and they promote readability and code reuse so this one is a function called hello that just prints hello this is the function definition so there's a name called hello this is the name here and then the body of the function which is the the set of instructions and the body of the function is everything that's after the colon and everything that's indented one level on the right so to run this function we must call it so i can just type in hello hello and then this is the syntax to to call the function and i can call it multiple times so i can just copy this and paste it and now if i just run this program it's going to print hello three times the name of the function is very important so the name of the function is hello it should be the function name should be descriptive so anyone calling it can imagine what the function does a function can accept one or more parameters this is something else that we saw before but i can type in a parameter right here and this becomes a variable that we can use in the function so i can change this instead of printing hello it's going to print hello and then we'll just put name and now i can call the function with the name and i can actually um call it with different names so we'll do bow and we'll do quincy and then if i just play that we see hello bo hello quincy so as you can see we call the function by passing the argument and again you can use single quote or double quotes here it's better to be consistent just always use single quotes or always use double quotes but for teaching i like to switch it up to just to emphasize that you can use either so let me tell you about the difference between parameters and arguments these two words parameters and arguments are sometimes used interchangeably and it's common to get confused about the distinction we call parameters the values accepted by the function inside the function definition and arguments are the values we pass to the function when we call it also an argument can have a default value that's applied if the argument is not specified so let me show you how i would do that so we have it name so right now it always needs to be get a name well first let me show you what would happen if i called the function without passing the name i'm just going to run that and we can see we're going to get an error hello missing one required positional argument name but we can make it so you can call this function without passing in a name where it's optional you can't if you want so i'm going to put an equal sign and then i'm gonna type in my friend and just to make consistent make this consistent i'm gonna make this all double quotes okay so this is now an optional argument so it's it's you can pass in the name but if you don't pass a name it's going to default to my friend so i'll just run this again with that default value and now it's hello bow hill quincy hello my friend because we called this and we didn't specify any argument or parameter and then we can also accept multiple parameters so i'm just going to get rid of this default value and i'll put 8 so now we're accepting a name and an age so we can now use both parameters in our function so i can do plus hello name [Music] you are and we're going to add the age and now it's going to be passed in as a number but we're going to convert it to a string so you are [Music] years old and then we have to make sure we have to make sure to add a space in here so there'll be a space space after this word then the number then a space and then years old so i'm gonna now have to pass in the number and now i can run this function now showing the red squiggly lines i sometimes the the red squiggly lines will appear when it's actually correct so let me what am i am i doing something wrong here oh i need to put the parentheses if the red squiggly lines appears when it's actually correct they'll it they'll go away usually within a few seconds or if you hit enter so that actually was a problem i forgot the parentheses at the end um so you can see this is what the whole function looks like if it's all on one line but i'm just going to move that over so hello bo you are 39 years old so we've used the name and the age so parameters are passed by reference all types in python are objects but some of them are immutable including integers booleans floats strings and tuples this means that if you pass them as parameters and you modify their value inside the function the new value is not reflected outside of the function let me just give you an example of that so if i just i'm just going to paste in some new code here and we can see we have this function called change and we're going to pass in this value if we pass in this this valve variable 1 to the change function and we set value to 2 well then we're going to print the value and see what happens and you can see it's now just 1 here so so it didn't change the value the value so what we change inside the function doesn't affect anything from outside the function and then you can see we have these orange squiggly lines here local variable value is assigned but never used it's just showing that actually this isn't really doing anything once it's inside the function and we change it doesn't change anything outside the function so if you pass an object that's not immutable you do change one of its properties and the change will be reflected outside so this was mutable this is immutable an object that would be mutable would be like a dictionary so if i change this to a dictionary and i put name and i set it to bow but then inside the change i do value dot name or not i'll put the the brackets value name so the key of this dictionary and i set that to sid and i run this we'll see now the name has changed to sin so we changed we use the change function to change name to sid and now it actually is changed because a dictionary is mutable so a function can also return a value using the return statement so i'm going to update this whole thing and talk about return statements a function can return a value using the return statement so it's going to return this name that we then can continue to use in our in our program it doesn't have to return name it can return anything that happens inside the function and the when the function meets the return statement the function ends so you can have a return statement have code after it but it will just end like for instance if you have the return statement in a conditional like in an if statement we can also omit the return the return value so it's just going to end the function and not return anything so i had mentioned having the return statement in a conditional so that's a common way to end a function if the starting condition is not met like for instance if we update the function to this so if not name return this so if i mean if not name return or else you don't even need an else because this will just in the function and you don't even need an else this will happen if there is a name now we just said that you have to pass in something if you don't have a default value so the way to get to that would just be to call the function with false so if we call with false then it's just going to return it doesn't do anything but if we call it with bo then let's see hello bo so you can also return multiple values by using comma separated values so for instance i can i'm just going to take this part off here and then add a return statement return and then i can return the name i can return bo in case that's not the name i can return 8 and then i can call this and i'm just going to call this with sid and we can see what happens now oh it doesn't it's not it doesn't actually print what's been returned but if i print this here we go then we can really see what happens so in this function it's going to print this but now we're also going to print what's returned so let's see what that looks like so this is what when we print what was returned it looks like this so it's sid bo 8 so one thing related to functions and also related to other parts of python is variable scope so let's look at this we've declared a variable up here and when you declare a variable that variable is visible in parts of your program depending on where you declare it so if you declare a variable outside of a function the variable is visible to any code running after the declare after the declaration including functions so we call this a global variable so we've declared this before the function so we can now access it inside a function and also outside the function so if i so we can see 8 and 8 and it shows right here what's going to show in the console here but if we declare a variable inside a function let me give you an example if we declare this variable inside the function i'm just going to move it down to here now it's a local variable and it's only visible inside the function so let me just delete with this because it's not actually going to be doing that so if i run this we're going to see there's there's an error name age is not defined we're trying to print the age here but since the age was declared inside the function it's not available outside the function it's only available inside the function so you just have to be aware sometimes there's local variables that only apply inside the function and there's global variables if you that can apply inside a function and outside a function okay now let's look at something else with functions and this is nested functions functions in python can be nested inside other functions a function defined inside a function is visible only inside that function this is useful to create utilities that are useful to a function but not useful outside of it so you might ask why should i be hiding this function if it does no harm well one because it's always best to hide functionality that's local to a function if it's not useful elsewhere also because we can make use of closures which we'll talk more about later so so look at this example so we have this function talk and inside the function we defined another function called say and then what we what we do is that we can call that say function inside the function and so the way this works is we pass in the phrase so here's the phrase and the phrase i'm going to buy the milk and here we do we we split it so split is a way to create a list of out of this string so we have this string but it's going to split it on every space so it's going to create a list of each word individually and then we're going to run this loop more on loops later and we're going to for every word in the the words list we're going to say the word we're going to say the word it's just going to print the word so if i just run that i am going to buy the milk and every time it prints it it prints it on a new line so this would just be an example because we're never going to want to use this save function outside the talk function so it's better just to put it inside the talk function and then i'll just paste in another example here if you want to access a variable defined in the outer function from the inner function you first need to declare it as non-local so we're using non-local here at non-local count and this allows us to access this variable that was declared inside the out so this is the outer function count and we have this variable called count and to be able to access that variable in the inner function we have to call non-local or we already talked about variable scope and if we didn't call call this non-local then we could not access the count variable from inside the function so like for instance i'm going to run this it's going to print the count which is just count plus 1 is just adding 1 to this number that's all the function does but if i take off this word non-local here and i run this we're going to get an error because it doesn't know what count is it doesn't know that we're referring to this count in the inner function so we'll just put that back on there and then it should work again this is especially useful with closures which we're just about to talk about so closure is a special way of doing a function in python if you return a nested function from a function that nested function has access to the variables defined in that function even if that function is not active anymore so let me show you an example i'm going to paste some code that'll be very similar to this code but just a a little different and then i'll explain it so now instead of count it's a counter so we're returning count from this nested function and from the outer function we're returning the nested function we're returning the increment function and then here instead of just calling the function directory the outer function we're assigning it to this variable and now we're going to print we're just going to call we're going to call this variable which is the returned inner function so we're basically calling the inner function and it's still going it's because we're calling the inner function it's not going to reset the count to zero every time and it can keep track of that value and we have this using a comment what it's going to return but we can also run the program and we can see one two three just like that so we return the increment inner function and that still has access to the state of the count variable even though the counter function has ended so let's move on to objects [Music] everything in python is an object even values of basic prim of types like integers strings floats are objects lists are objects as well as tuples dictionaries and pretty much everything so objects have attributes and methods that can be accessed using the dot syntax for example let's define a new variable of type int so i'm going to do age equals eight age now has access to the properties and methods defined for all int objects this includes for example access to the real and imaginary part of that number so i can do a print age dot real and then if i just run that the real part is eight i can also print the imaginary part of the number and manage and there is no imaginary part of the number so it just does zero i can also get the the bit length age dot bit length and if i run that we can see the bit length is four so the bit length method returns the number of bits necessary to represent this number in binary notation so there's just a lot of things that you can use for all int objects and these are just a few of them so a variable holding a list value has access to a different set of methods so i'm going to update this again we're going to do items equals and we're going to create a list one two so i can do items dot append i can append a three i can append another item i can do items dot pop which is going to remove and return the last item which is the three and the methods so so these are the methods of pin and pop and the methods available to an object depend on the type of value the id global function provided by python lets you inspect the location in memory for a particular object so for instance i could do a print and i'm going to do id what's the id of the items object and we can see this is the location in memory so some val some objects are mutable while others are immutable this is something that we already talked about a little bit that depends on the object itself if the object provides methods to change its content then it's mutable otherwise it's immutable most most types defined by python are immutable for example an int is immutable there are no methods to change its value so if you increment the value like with um age equals age plus one it's actually going to create an entirely new value so it it's not going to even be the same object at all because age you it has to create a whole new one to reassign it but something like a in in a dictionary it would actually be the same object but you could just change different parts of it now let's talk more about loops so this song we already discussed a little bit in the previous section but loops are one essential part of programming and in python we have two kinds of loops while loops and for loops so before i um show i'm going to paste in this code but i just want to show something really quick see how there's a line like dotted line here and a dotted line here this is showing the default indentation which we can change so i'm actually going to go and change that really quick let me wait i think i'm gonna have to yeah i'm gonna zoom out so i can get to this and i'm gonna change the indent to four and now it's not going to have a little line right in there so now i'm going to go back here and let's zoom in again okay so let's talk about while loops while loops are defined using the while keyword and they repeat their block until the the condition is evaluated as false so while condition equals true so this particular example is an infinite loop it never ends because this condition is always going to so if we run this program which i'm not going to do right now because it just goes on forever while this condition is true keep running the code inside the loop all the lines of code that are indented the same amount so let's halt the loop right after the first iteration i can do condition equals false [Music] so now if i run it it just runs the loop one time so in this case the first iteration is run as the condition is evaluated true and then at the second iteration the condition test evaluates to false so the control goes to the next instruction after the loop which in this case there is no next instruction after the loop it's common to have a counter to stop the iteration after some number of cycles so here's a while loop with a counter so you you start the counter at zero and then while count is less than 10. we're we're gonna print this count equals count plus one so it's going to increment the counter every time until we get to the end so it's gonna see it's gonna print this until eventually the count is greater than 10 so or 10 or 10 or greater while count is less than 10. so once it gets to 10 the loop will stop um again another way to doing to do this we could have just done plus equals plus equals one so if i run that it's going to do the exact same thing and other type is the for loop so using for loops we can tell python to execute a block for a predetermined amount of times up front and without the need of a separate variable and conditional to check its value it's commonly used to iterate the items in a list so we have this list there's obviously four items here and then four item in items so items is this list and then for each item in the list we're going to print the item pretty straightforward and it prints each item in the list or you can iterate a specific amount of times using the range function so let's say we don't have we're not going to define this here we're just going to do 4 item in and then here i'm going to type in range and then i'm just going to type in a number how about 15 so i'm using the range function that basically just returns a list and then if i do that we can see it's going from 0 to 14. so the range function is going to return a a list that goes from 0 to 14 so there's 15 items and it's going to print the items now if we just go back a few steps to when we had the list here we can i can show you how to get the index so right now it's just printing the items one two three four but what if we want the index of the list we can do that by using the by wrapping the sequence in the enumerate function so for items in and then i'm going to do enumerate i'm going to pass in so this is going to return each item and the index of the item and since there's going to be an item in an index but it's actually the index and then the item i'm going to type an index comma item so this enumerate is going to get the index and the item so now i can print the index and the item here and if i run that so index zero item one index one item two index two item three and so on and it doesn't even have to be numbers we can do names [Music] and if i just run that whoops not that one and then we can see the the index and the item then let me put in some more code here so i can talk about break and continue both while and for loops can be interrupted inside the block using either break or continue continue stops the current iteration and tells python to execute the next one and break stops the loop altogether and goes on with the next instruction after the loop ends so i'm going to just play this so here we're saying if item equals two continues that means it's going to skip that iteration so if i play this one three four so it's not going to it's not going to get to the print item because it's actually skipped that iteration it just doesn't run any code after the continue if this is true and so it doesn't print 2. so if we change this to break it will be very it'll be a little different here this time it's going to just print one because now it's breaking out of the loop entirely and it's not going to run any more iteration of the loop okay let's talk about another thing classes classes in python so in addition to using the python provided types we can declare our own classes and from the classes we can instantiate objects an object is an instance of a class a class is the type of an object so here's an example i'm going to create a class called dog so uh to create a class you just put the word class and then put the the class name and now i can i can add a method for the class so to define a method i'll just do define bark [Music] and i'm going to put the word self here and inside this i'll print [Music] woof [Music] okay so self as an argument of the method will point to the current object instance and must be specified when defining a method so when you're creating a method inside a class you're always going to start with self so we create an instance of a class which is an object like this so i'm just going to put roger equals dog okay so i've created a dog just like this and then i can print type roger so let's see what the type of this roger is we can see it's the class to dog class roger is a dog a special type of method called in there's a special type of method called init which is a constructor so let me show you how to create a constructor deaf so we can use this a constructor like this to initialize one more properties when we create a new object from that class so you can see we always have to add self but now these are the two variables we can pass in when we create a dog and that will associate be associated with that that object so down here i can call um i can call dog but i can pass in roger for the name and the age and now when we create this dog it's going to assign the name to self.name and it's going to assign the age to self.age and let me show you how you can access that information so i'm going to print instead of printing the type i'm going to do roger dot name and now it's going to when i do roger.name that's self.name so self is roger and we do self.name it's going to be the name that was passed in and then we can also do the age and then we can finally call the bark method so we have bark here now we can see what that does so i'm just going to run that and we have roger we have eight and then this is because i should have put parentheses here so let me put parentheses after bark and so we have wolf here so roger 8 wolf and the reason why it says none here is because i didn't have to put the print see i i put pranks that was in this groove if you're playing print on everything but calling bark already prints wolf so when i do it when it's when it's printing it's printing because since roger.bark doesn't return anything there's no return statement that's why it printed none so there'd be two ways to fix that either instead of printing wolf i could return wolf or i could just not do the print here so let me just take that off okay roger 8 wolf so one important feature of class is inheritance let me show you an example of inheritance i'm going to create a new class before the dog class and this is going to be a class called animal and the animal class i'm going to put a function called walk and i'm going to always pass in self and this is going to print [Music] walking [Music] and then we can make the dog class inherent inherit from the animal class so we have class dog but if i put parentheses here then i can type in animal and now the dog class is going to inherit from the animal class and now i can go down here and after roger.bark i can do roger.walk and if i run that okay so roger 8wolf but now it's going to be able to do walking and you can see the dog class doesn't actually have a walk method but it's getting it from the animal class it's inheriting this method and in that way you're able to i could create a class cat a class frog a class bird and each of them could inherit the walk method and then it would have walking and we'll be doing a little more with classes in the the final project in this course because we'll be going a little more over object oriented programming but right now let's talk about something new i'm going to just delete all this and we're going to be talking about modules so every python file is a module you can import a module from other files and that's the base of any program of moderate complexity as it promotes a sensible organization and code reuse so it's basically how you can create a software that has multiple python programs in the same piece of software so in the typical python program one file acts as the entry point and the other files are modules and exposed functions that we can call from other files so let me just show you an example i am going to open up this files tab and i'm going to create a new file and this is going to be called dog dot pi and now i have dog dot pi open i no longer have the main dot pi open and i'm going to define bark and what bark is going to do is just print woof [Music] okay now i'm going to it's just going to automatically save for me i'm going to go back to the the python file and now i'm going to import dog and let's see oh it's just saying it's unused i thought maybe this thing wrong but that just means i import dog and i haven't used it which i'm about to do right now so dog dot bark so now if i run this program it's going to say wolf but that's not from this file it's actually importing this function from from the dog file so that's a way you can break up your code into multiple files we can also use the from import syntax and call the function directly let me show you what i mean so instead of import dog i'm going to say from dog import bark and then instead of calling it dog.bark i can just call bark because we're only importing bark well we've imported bark directly instead of the whole dog so i can run that and it says wolf so the first strategy allows us to load everything defined in a file when i just said import dog that allows everything defined in a file so i could have a bunch of function like bark or walk name or there could be a bunch of functions if i just say import dog it imports all of them but the second strategy from dog import bark allows us to just pick the things we need so we're only going to import the specific functions that we need those modules are specific to your program and importing depends on the location of the file in the file system so suppose you put dog.pi in a subfolder for instance let's say i create a folder and i call it liv for library and let's say i put dog.pi in this subfolder like this now in this folder to make this work i'm going to have to create an empty file named init.pie so i'm going to add file and i'll do init dot or under underscore underscore init underscore underscore dot pi and this tells python that the folder contains modules now i'm going to go back to my main file and i can i can import dog from lib so i'm going to say from lib that's that subfolder import dog and then i can do dog dot bark so let's run that to make sure there's no errors it worked correctly so i was able to import this file from the subfolder or you can reference the dog module specific function by importing from lib.dog so i can do from lib.dog import bark and now instead of calling dog.bark i can just call bark and it says wolf so i'm going to close this here and now let's talk about the python standard library so basically there's all these pre-built modules you can you can load a lot of code from the standard library python exposes a lot of built-in functionality through its standard library the stand library is a huge collection of all sorts of utilities ranging from math utilities to debugging to creating graphical user interfaces so there's a bunch of them but here's some of the more common ones we have math for math utilities re regular expressions json to work with json date time sqlite 3 os for operating system utilities random for random number generations so statistics requests for http request http to create servers url lib to manage urls so you can import these modules that allow you to get extra functionality so we already looked at a little bit at the math one we already looked a little bit at random in the the first uh project that we did but let's just kind of look at a little more how you would do this so now we are going to use the the math one we're going to import math and so this is how you would introduce you would use a module of the standard library so we already saw how to import modules that we created it's very stan it's very similar with the standard library so now that i've imported math i can now use functions and methods from from the math module so i can do math dot square root and i can pass in 4 and then i can just print that so we can see what the result is okay 2.0 or we can just like we shall we saw before instead of importing math i can say from math import square root and then instead of just doing math dot square root i can just call this square root method here and it's going to do the same thing so that's basically how it works for for all the modules in the standard library okay now we're going to start going over a few kind of miscellaneous slightly more advanced topics in python so we're going to talk about how to accept arguments from the command line in python well first of all let's see how to run a program from the command line in replit so let's say we have a program it just says print hello okay so we've been running it by just clicking this play button but there's another way to run a program in replit and i go over to the shell so this is the command line in replica we can clear this and now i'm just going to type in python main dot pi okay so what we call python to run the python program and then we just put the name of our file with main.pi so whether you're in replit or if you're running things locally you should be able to run a program in the same way depending on how you install the program locally instead of typing python you may type in python 3. sometimes the way people install python it will be python 3 because we're using version 3 of python so now let's see how you can call a python a program on the command line and pass in some arguments right when we run the program from the command line so a basic way to handle arguments is to use the sys module from the standard library so let me give you an example so first of all we're going to import sys now just so you know usually you're always going to have import statements on the first line i'm just putting this comment on the first line to remind us what we're working on right now so now i'm going to we're going to import the sys library now i'm going to print and i'm going to first i'm going to oh we're going to print the argument cis.arg the so this is how we can print all the arguments that were passed in when we called the program so so i'm going to see we have python main.pi and now i'm going to put bow 39 okay so you can see it's printing the list of arguments so this is basically just a list the first item is the name of file then we have the the first word and then the second one and you can see they're both strings even though this is a number it's coming in as a string so then we could do something like this we could say name equals cis.arg v and then i would get the element at index 1 which is the name here and i could print [Music] hello and then we're going to do a name oh hello hello and then name so let's call this again and instead of i'm not going to do 39 it's just going to be python main.pi bow hello bo so we've now been able to use the argument that was passed in now this is a simple way to do it but you really would have to do a lot of work using this method because you really should validate the arguments make sure the type is correct and you need to print feedback to the user if they're not using the program correctly so i got zoomed out a little bit and i'm going to show you this other method so python provides another package in the standard library to help you called arg parse so first you would insert import arg parse [Music] and then let me show you how you would use it so you call arc parse dot argument parser and then pass in the description of the program so the description of the program is this program prints the name of my dogs then you proceed to add arguments you want to accept so for this example program we are going to accept the c option or it can be slash c or dash that's color and we are going to be calling it color and then later we can we do parser.parse args and then we can access args dot color to get the color that was passed in and then you can specify whether it's required and what help is going to go along with that so let me show you how you would do that we're going to do python main dot pi i'm going to put dash c and then i'm just going to put red okay so you can see if i go this out a little more you can see this is the command i called this is the command i run i pass in red and then it just printed red that's what we have right here and so let me show you what would happen if we if we don't specify the argument so if i just run it without the red so it's now giving me some information usage well main.pi we need to put dash c and then we have to put a color and then it says the following arguments are required this dashi or dash sc so it's it's showing us that we need to if we we've called the program wrong and we're going to need to call it with the dash c you can also set this option we can set an option to have a specific set of values using choices so after required true after this comma i'm going to type in choices and i'm going to set this to equal see i have this empty dictionary but i'm just going to well not a dictionary but because it's not going to key value pairs i can do red and yellow so now it's it can only accept two options so i can call it here with red but if i call with blue it will say invalid choice blue i need to choose from red or yellow so using this arc parse makes it easier to deal with arguments and also makes it easier to communicate information back to the user about what we're trying to get so there are more options with this but those are those are the basics now let's talk about something completely different lambda lambda functions so let me just give you a quick example [Music] lambda num num [Music] times 2. so lambda functions also called anonymous functions are tiny functions they have no name and only have one expression as their body so they're defined using the lambda keyword and so this is going to be the argument and this is going to be the expression the body must be a single expression and it has to be an expression not a statement so this difference is important an expression returns a value a statement does not so it has to return a value so the value that's being returned is the number times two the number that was passed in going to multiply it by 2 in this example so this is basically the simplest example of a lambda function it just doubles the value of a number and lambda functions can accept more arguments so so for instance i could do [Music] lambda a comma b and then we can multiply a times b lambda functions cannot be invoked directly but you can't assign them to variables so for instance i can assign this to the variable called multiply so multiply is going to this function is going to be assigned to this variable here so then the way that i would use that i could print now i'll print the result of calling multiply and then i pass in two and four so if i just run that okay 2 times 4 is 8. we can see right in the console here and then i'm going to just zoom in just a little bit so the utility of lambda functions comes when combined with other python functionality for example in combination with map filter and reduce so speaking of map filter and reduce that's what we're going to talk about now map filter reduce so python provides three useful global functions we that we can use to work with collections so this is map filter reduce so first let's talk about map and since their functions are going to have the parentheses at the end so map is used to run a function upon each item in an iterable item like a list and create a new list with the same number of items but the values of each item can be changed so here's an example we have this list and then here's the function and then we are going to map through each item in the list and so here's the function we're going to run we're going to run this function on each item in the list and now we're going to get a new list so i can do print result now if we print that i'll just run that function and we can see okay we get a map object so then we can always just pass it into the list function and then we can run the program again two four six so one two three became two four so yeah whenever you want to do run a function on each item in a list you can use map and when the function is a one-liner it's common to use a lambda function so we just talked about lambda functions so now let me show you how you would do this as a lambda function so double is going this is going to be a variable and we're going to assign it to a lambda function and i'm going to so now this lambda function takes the number a and then does a times two so and this we just keep the same because now we're using a lambda function here and we're taking each number and passing it through this function where we have the the this is each number in the list and we multiply it so if i run this program it should look exactly the same and we can even simplify it even more so this is where lambda functions really shine instead of assign it assigning it to double first i can copy the whole function i can delete this completely and now i can just put it right in here so now we're mapping over this function and we don't even have to create the function in a different line and assign it to a variable first we can put the lambda function right in the same line right within the map and now i run this and it's going to give us the same result so remember we started with when i first showed you this example we had a much longer piece of code now we've simplified it with the lambda function so the original list the original list is left untouched in a new list with the updated values is returned by map the result is a map object which is an iterable so that's why we needed to cast it to list to print its content okay now let's talk about filter let me put in let me just update the code here it's kind of similar but now we're using filter filter takes an iterable and returns a filter object which is another iterable but without some of the original items so you can do so by returning true or false from the filtering the filtering function so here's the filtering function we are going to check if the item passed in is even so so here's the list here so you can see we're calling filter we pass in the function the filtering function and then the list and we're going to return true or false from this function so if it can be if it's divisible by if when you divide it by two we have zero remainder then it's even so that would return true so this line would return true and then if not it would return false if it's odd so now any even number is going to be added to the result and any odd number is not going to be added to the result so basically we're filtering the list based on this function and then here we just print we convert that result to a list and if we run that it's two and obviously if we can just put in uh more numbers here and run that again we have two four six and then we can just like before we can use a lambda function so i'm just going to copy this here we can just delete this whole thing and we are going to put a lambda function here so lamb duh [Music] so now you can see we're just putting the lambda function in the in line here and we are checking to see if it's this is going to turn true or false whether it's even or not and so i run the program and it's going to give me the exact same result here okay the final thing we're going to talk about is reduce reduce is used to calculate a value out of a sequence like a list so for example suppose we have this list of expenses stored as tuples and so so we had dinner 80 car repair 180 or 120 and we want to calculate the sum of this property in each tuple in this case the cost of the expense so here's kind of the long way of doing it without using reduce we basically take every expense in expenses and then we add to the sum here and we add expense one that's going to be the the item at index one and then we get the sum and we can print the sum so that's kind of like the long way of doing it without reduce but there's a quicker way so to use reduce reduce is a little different from map and filter where it's not available it's not it's not available automatically we have to import it from the standard library func tools so i'll do from funk tools or function tools import [Music] reduce and now i'm going to create a new i'm going to create a new variable called sum and we're going to set it to reduce we're going to use reduce and now i'm just going to pass in i'm going to go directly to the lambda function so lambda let me just kind of explain this for a little bit so reduce the first is going to take a function the reduction function and then the iterable here and the function has to take two arguments so this the first argument is the accumulated value and then the the right argument is the updated the update value from the iterable so we're going to continue adding these two item we're going to basically add every item together and reduce the i the numbers at the first index all into down to one value by adding them all together so i'll just pray here play here and then we get the same number 200 and you can see it's a lot it's a lot quicker just to use the reduce function compared to the other code we had previously okay next up we are going to talk about recursion in python not recursion error just recursion and a function in python can call itself that's what recursion is and it can be pretty useful in many scenarios a common way to explain recursion is by using the factorial calculation so let me show you how you would calculate factorial this isn't python code this is just an example here so a fact when you do 3 factorial that means you do 3 you multiply every number between three between this number and one together so three times two times one equals six four factorial is four times three times two times one five factorial is you know five through one and so on and then every number you multiply every whole number down to one so using recursion we can write a function that calculates the factorial of any number so let me show you so here's the function you can see inside the function it's calling the same function so a recursive function it's always going to have a base case that's this and the recursive case so the base case is when we're going to leave the the recursive function so if n is equal to one we're going to return one and that's basically going to get out of the recursive function uh but if n is not going to equal one then we have the recursive the recursive case where we're going to call the function so you always need to have at least you always have need to have a base case so eventually the recursion can stop if the recursion doesn't ever stop then you're going to get a recursion error basically python by default will halt recursions at 1000 calls and that's when you get the recursion error so this is going to get the factorial three but let's just do this a few more times so you can see the difference so three four five and now we'll test this out 6 24 120. okay now let's talk about decorators so decorators in python are a way to change enhance or alter in any way how a function works decorators are defined with the at symbol followed by the decorator name just before the function definition so for instance let's say we have a function hello and it's just going to be the simplest function we're just going to print hello uh so to make that to add a decorator i'm going to put like this an at sign and then the decorator name in this case we're going to type in log time so the function has the log time decorator assigned so whenever we call the hello function the decorator is going to be called a decorator is a function that takes a function as a parameter wraps the function in an inner function that performs the job it has to do and returns that inner function so for instance i'm going to create another function here that's going to be the log time function and now we we can do something before and after the function like for instance we can say print before and then after we are going to print after now if i run this oh and we have to call the function that's always important now if i run this before hello after so you're going to often use decorator functions when you want to change the behavior of a function without modifying the function itself so a few good examples are when you want to add logging test performance perform caching verify permissions and so on you can also use one when you need to run the same code on multiple functions okay now let's talk about doc strings so doc strings [Music] documentation is hugely important not just to communicate to other people what the goal of a function or class or method or module is but it's also it also communicates to yourself when you come back to your code like many months from now you might not remember all the knowledge you were holding in your head when you wrote the code so at that point reading your code and understanding what it's supposed to do so that at that point reading your code and understanding what it's supposed to do will be a lot more difficult so a lot that's one of the reasons why people add comments so another way is to use a doc string so let me show you what a doc string looks like the utility of a doc strings is that they follow conventions so they can be processed automatically so this is how you would define a doc string for a function basically you're putting the three quotation marks here three quotation marks there and then this is a description of what the function is this is how you would define a doc string for a a class and a method so got the class this is what the class does is this is what the method does and then it's also common to add docs place a doc string at the top of the file so if you put a doc string at the top of the file it's going to look like this and it's going to explain what the file is all about and docs stock strings can also span multiple lines just like this is a multiple line docs string as long as it has the three quarts three quarters at the top three quarts at the bottom and then python will process the doc strings and you can use the help global function to get the documentation for a class a method a function or a module for example i'm going to go to the bottom of this and i'm going to say print help and then i'm just going to type in dog now i'll run this and let me just run it again so now you're going to get information about the dog we know that the dog has a name and age it's a class representing a dog and the has these specific methods and then it says more we can get more information data descriptors defined here we have and this is just going to give us all this information about the dog and we and so that's why it's good to use doc strings because there are specific standards and it makes it easier to get information using different helper methods and standards allow and standards allow us to have tools to extract doc strings and automatically generate documentation for your code so besides just this help functions there's a lot of other methods to pull out these docs strings and get information about your code and next we will learn about annotations python is dynamically typed so we do not have to specify the type of a variable or function parameter or a function return value annotations allow us to optionally do that so if we want to actually show what type we're expecting for different values so here's a function without annotations and then here's how we would make it have annotations so uh we want to make this function only accept an int so i'm going to put colon int and then after here i'm going to put actually before the colon here i'm going to put a little arrow here and then i'm going to put in int so now we're specifying that this function receives an int and then it's also going to return an end and you can do the same thing with variables so if we have a variable if i had a variable called count and was equal to zero i can add an annotation to make it be an int like that so now we're specifying that this variable is going to be an integer python will actually ignore these annotations a separate tool called mypi can be run standalone or integrated by ides to automatically check for type errors statically while you're coding it'll also help you catch tight mismatched bugs before even running the code a great help especially when your software becomes large and you need to refactor your code okay now we'll talk about exceptions [Music] it's important to have a way to handle errors and python gives us exception handling to do so so for exception handling you would wrap lines of code in a try block and then inside this block you'll put the lines of code and then if an error occurs python will alert you and you can determine which kind of error occurred using an accept block so we're we're trying some lines of code here and then we're checking for a specific error and then if that error happens we would handle that error but if a different error happens then we will handle the different error you can also catch all exceptions using an accept without an error type so at the very end you could just do accept and then if you don't have an error type then it's going to handle the rest of the exceptions and just to make this clear this is just an example where it says air one you have to put a specific error in that spot you can also put an else block at the end to handle that that will run if the no exceptions are found so if there are no errors in this code that's right up here we can have an else and then run specific code at the bottom that that runs if there's no errors and then we can have a finally block so anything in a finally block is going to just always run at the end whether or not there are exceptions or no exceptions the code in the final block is always going to run the specific error that's going to occur depends on the operation you're performing for example if you're reading a file you might get an eof error would just look like this eof error which means end of file if you divide a number by zero you'll get a zero division error if you have a type conversion issue you might get a type error so let's try this code so i'm going to just delete all this and we'll do result equals 2 divided by 0 which you cannot do so just print the result and if i run that we'll see this error over here zero division error division by zero so it's going to get an error when we run the code and then whenever there's an error anything after the error occurs will not happen so we're not going to print the result because there is because the this this line resulted in error so we're not going to run the following line of code so now let's try adding that operation in a try block so i'm just going to paste it all in here and so we're putting the operation in a try block and then we're expecting a zero division error where we'll print cannot divide by zero finally we will set the result to one and then print the results so let me just run that code see cannot divide by zero and then we print one we because we set it in the final block here so this try block lets us recover gracefully and move on with the program you can raise exceptions in your own code too using the raise statement so i could type in raise and then we can raise an exception intentionally and error so if i just run this it will say an error because that's what we typed in so you can make it say anything you want for your error and this raises a general exception and you can and you can intercept it just like this so i could say try and then we raise that exception and then we can do accept exception as error and then we can print the error okay if i run that so now instead of we don't see all that red anymore because it's not stopping our program because of the error but it's now printing the error message right here just like that you can also define your own exception class extending from exception so i could do class dog not found [Music] exception and then i will extend from exception [Music] and then i can just put pass for this one here let me adjust that so pass here just means nothing and we must use it when we define a class without methods or a function without code so if you're not going to put anything so this is just an example so i can just put pass to mean that we're not going to have any code in this so now we can try it out so i'll just paste that uh so we're going to raise dog not found exception and then if we're we're going to candle this exception and just print dog not found so let's try that yep dog nut bound because it raised this exception here we can also actually do something in the exception so if i can say print inside and then i'm going to run that and i'll do inside and dog not bound the with statement is very helpful to simplify working with exception handling for example when working with files each time we open a file we must remember to close it with makes the process more transparent so let me show you some example code without the with statement so we're not going to go into a lot of details about working with files here but i just want to kind of just give this one quick example so if we're going to be working with files in python so we can open the file and then we can read the file we can print the content from the file and we we're going to try that because there could be an exception and then finally we're always going to make sure to close the file but an alternate way to do it would be like this um so with we're going to open the file as file and then content file.read and then print the content and with using with it's going to make sure to automatically close the file at the end in other words we have built-in implicit exception handling as close will be called automatically for us and with can do a lot more stuff as well this example is just meant to introduce its capabilities now let's talk about third-party packages and we're going to talk about pip so let's learn how to install third-party packages in python using pip the python standard library contains a huge number of utilities that simplify our python development needs but nothing can satisfy everything that's why individuals and companies create packages and make them available as open source software for the entire community so the modules are all collected in a single place called the python package index which is available available at pipe.org that's pi pi.org and they can be installed on the system using pip there's over 270 000 packages freely available most computers are already going to have pip installed and it already has pip installed so let me show you how you would install a package we'd have to go over to the shell here if you're not on replit you can just do in your terminal and i'm going to clear this here and i'm just going to do pip install and then you can put the name of a package for instance one popular package is called the request package it's an http library so i can do requests and let me just so you can see i have to make sure i spelled that right [Music] and it's going to install that package right now so once the we install this package it's going to be available for all our python scripts because packages are installed globally and the exact location depends on the operating system you can also upgrade a package to its latest version by doing pip install dash u and then i will just put the package name so in this case we'll just do request again and then it's going to just update it to its latest version in this case it updated from 2.28.0 to 2.28.1 you can also specify a specific version when you're installing and then you can also uninstall a package so i'll do pip uninstall requests and then i can say that yes i do want to uninstall that and then once when you have a package installed i'm just going to install request again and then you always have to make sure you spell it right so once you have it installed you can do pip show requests and then it's going to show some information about the package so see we can see the name the version uh the summary and then a bunch of the author and a bunch of other information about the package okay i'll just clear this now we're actually gonna backtrack a little bit we already talked about lists but i'm gonna talk about a more advanced way of using lists called list compression list compressions so list compressions are a way to create lists in a very concise way so suppose you have this list like this it's a list of numbers and we'll just do one two three four five so we can create a new list using a list compression composed by the numbers list elements to the power of 2. let me show you what i mean so let's get make a new list numbers power [Music] 2 equals and let me just show you how you do this list compression so this is the list compression syntax and if i print this [Music] we can see that now we have every element in the list to the power of two list compressions are a syntax that's sometimes preferred over loops as it's more readable when the operation can be written on a single line so for instance this is how you would do it uh with a loop so what we do in a single line up here we take a few lines to do in the method with a loop so list compression just makes it simpler and then you can do the same thing with map as well but again it's just a little more complex sometimes it's just simpler to use a list compression using the syntax here now let's talk about a few more advanced topics in regards to functions polymorphism polymorphism generalizes a functionality so it can work on different types it's an important concept in object oriented programming so see in here we've defined the same method on different classes so the dog has eat and the cat also has an eat method then we can generate objects and we can call the eat method regardless of the class the object belongs to and will get different results so we create the two objects the dog and the cat here and we're calling the eat method on both objects and if we run this you can see what we're getting eating cat dog food eating cat food and so you could do a lot of things with this like maybe you have a list of different animals and then you can loop through that list and call the eat function or the eat method on each animal in that list and they don't have to be the exact same class to be able to still run the eat method so we build a generalized interface and now we do not need to know that an animal is a cat or dog we just need to know that we can call eat on it now let's talk about operator overloading [Music] operator overloading is an advanced technique we can use to make classes comparable and to make them work with python operators so let's take this class dog so here's a dog class and you can create a dog with a name and age then we'll create two dog objects we'll do roger equals dog and we can pass the name and eight [Music] and then i'll make another one we can use operator overloading to add a custom way to compare these two objects based on the age property so like how could you compare this dog and this dog well we can make it possible with operator overloading so let me just show you this example here so this function here gt is going to compare things as to figure out what what is greater than you can now we'll be able to compare two dog objects to see which one is greater than the other and this is how we're going to figure out which is greater than return true if self.age is greater than other dot age which is the other one you're comparing it to else false now we can do print roger is greater than sid so we're trying to figure out this is true or false if i run this it's going to say true roger is greater than sid because 8 is bigger than 7. but if we like put 9 here run that now it's going to be false so in the same way we define this underscore underscore gt underscore which means greater than we can also define methods for like less than lower or equal to greater equal to or not equal and then you can also create methods to go with different arithmetic operators so we can do add subtract multiply division floor division mod power so you can see all these different ones you can make it respond to the different operators so the example was just a greater than operator but we can make functions to show how it's going to respond to all these different operators there's even a few more methods to work with other operators but you get the idea we've learned a lot about python and now we're going to bring a lot of what we've learned together to code a blackjack card game and in the process we'll learn about object oriented programming in python so we'll start by creating a new python project on replit and i'm just going to close this tab here and i'll zoom in just a bit and just like our first project i'm going to say what i'm about to do and i want you to see if you can do it on your own before i show you how to do it and with all you've learned so far a lot of this you're probably going to be able to figure out on your own as i give you the instructions without even seeing how i how i do it but then you can come back to the video and see how i do it or i guess you can just watch and not even try to do it yourself but you're going to learn a lot more if you try to code this by yourself along with me as i do it but right before i do the different steps so the first thing we're going to do is create a variable called a suit and set it equal to hearts and then a variable called rank and set it to equal k for king and then a variable called value and set to equal 10. [Music] okay simple two variables equal to strings and one variable equal to an int so now we are going to add a print statement and print the the phrase your card is with a colon at the end and then we'll add another print statement and print the rank so now we're just printing the variable here and we're going to be doing a lot of refactoring as we create this program let's refactor this so it's just one print statement that's going to print your card is colon space and then the rank so we are going to be doing string concatenation [Music] just like that so you can concatenate as many strings and variables as you want so let's update the code so that the print function print prints your card as k of hearts so we just need to add of and we have to make sure we put spaces on each side of the word of and then suit and let me just adjust this here okay as you know you can use a list in python to store multiple values or items at a time so above the suit variable create a suits variable and assign it to a list of suits in this case spades clubs hearts diamonds we learned about how you can use the bracket operator to access a specific element in a list the number inside the bracket specifies the index of the list to access remember the indexes start at zero so you update the suit variable so that the value of hearts come from comes from the suits list now we'll practice a for loop so add a for loop to the end of the code that prints each suit and then we'll just test this out i really hope you actually are following along and trying it out right before i show it to you that's how you're going to learn the best here so spades clubs hearts diamonds now this next thing is is just to see if we can do it so it's not going to be part of our final code but right before the loop we just added see if you can add another item to the suits list that's the string snakes there's a few different ways to do it but we will use append snakes so this is just going to append the word snakes at the end of the list so if i run this we can now see snakes at the bottom okay now we're going to start the process of representing a full deck of cards with python code so we're going to actually get rid of a lot of this we're going to get rid of all this we're just going to have the suits and then we're going to have this for loop at the bottom we're going to do a lot of refactoring as we go mainly for educational purposes but also so we can get the a really good blackjack game so we have a list of suits after that we're going to create a list of ranks that's a 2 3 4 5 6 7 8 9 10 j q k [Music] now before the suits list create a new variable called cards and assign an empty list to the variable you can an empty list is just two brackets with nothing inside now in the cards list there should be an item for each card in the deck each item in the suits list should be combined with each item in the ranks list for a total of 52 items or cards let's work our way up to that so first we'll update the print statement in the for loop so that it prints a list with two elements the first element should be suit and the second should be the first element of the ranks lists so this should print an ace in every suit so i'm going to update this so it's going to be a list with suit and ranks the first item is going to be at index zero now let's print that out so we got them these four right here now instead of just printing an ace in every suit let's print every rank in every suit this can be done easily with a for loop nested within another for loop so inside the for loop add another for loop that loops through the ranks then update the print statement so that it's not just printing the first element in the ranks list but it's printing the rank from the for other for loop so let me show you what i mean we're going to do four for rank and ranks and then we have to make sure to indent this print statement so it's inside this other for loop and this is now just going to be rank so it's going to print the suit and rank and i'll just run that and now we with this nested for loop we have every card at every rank in every suit all 52 cards are printed as two item lists an element in a list can be another list so instead of printing 52 two item lists let's append those 52 cards to the cards list so we already have the cards list here it's empty but i'm going to do cards dot append and so we're appending this item all these items to the cards list so let's check what the cards list looks like by printing out printing it out at the bottom remember make sure this is not indented at all and we'll do print cards and i'll run that and then here it is here so this is the list it's not one there's just a comma between each item in the list here you may notice that all the cards are in order in the cards lists for a game like this though the cards must be shuffled so to help with this import the random module at the top of your code so that's just we just do import random [Music] now we'll be able to use the the random module so this is going to import the random module which contains a variety of things related to random number generation and as you probably remember when you import a python module it allows you to use additional commands in your code specifically we're going to be using the random.shuffle function so right before at the end where it says print cards we're going to call random.shuffle and pass in the cards list to that function and then if i play this here or run the program we can see that these are not in order anymore see ace of spades three of spades king of diamonds jack of hearts so these are no longer in order because they've been shuffled now let's remove a single element from the cards list this is similar to dealing a card from a deck and this can be done with the pop method so after the cards are shuffled let's create another card variable and just pop off a card from the cards list and put it into that variable called card and just print that card so i'll do card equals cards dot pop and then instead of printing all the cards i'm just going to print a single card i'll run the program see every time i run the program you can see we're getting a different card we're dealing a different card because it's been shuffled so we've already learned all about functions and now we're going to create a function so create a function called shuffle that just has the single line that shuffles the cards so it's just def shuffle and then i just have to make sure this is indented so now when we call the shuffle function it will shuffle the cards so right before the print statement call the shuffle function and instead of just printing the single card print the cards so do shuffle and then i will print all the cards and let's just try out the program and we can see there was a problem it's because we didn't put the the colon here so that's an important part of creating a function is putting the colon there now we'll create another function called deal and we'll put this line inside the the deal function so we're going to define deal and i'll put the colon this time and make sure to indent that and we can see this has a orange squiggly line underneath it because variables can only be accessed in the context that they were created so the card variable will not be available outside of the deal function you can get a value out of a function by returning a result using the return statement so at the end we're going to return the card okay now we've taken care of that squiggly line there so after the shuffle function is called we'll call the deal function and assign the return value to a variable named card then we'll update the print function to print card instead of cards so card equals deal and then we'll just print the card and again we see a different card every time we run the program what if you want the deal function to deal more than one card well let's refactor the deal function to and accept to accept an argument so any number of arguments can appear inside the parentheses when a function is created separated by commas inside the function the arguments are assigned to variables called parameters so start by making it so we'll start by making it so the deal function takes an argument named number then we'll make sure when we call the function we use the new parameter by making it so we're gonna deal two so i'm just gonna put number here it's gonna it's gonna deal a number of cards we're gonna deal two and i just didn't say this before but now instead this is not one card anymore so we're going to update this to be cards dealt but there's a special shortcut you can either it's going to be command or control d and now i'm actually selecting the card two different times see i i now have multiple cursors here so basically i selected the word i double clicked to select the word then did command or control d now it's selecting two words and now i can type in cards delt so now i can type in two places at one time so that's a cool thing that you can do in replit and you can do it in many other code editors and i'll run the program but it should still only deal one card because even though we're passing this parameter into here we're not doing anything with it yet here so we want to update the deal function so it's going to return a list of cards instead of a single card in the first line of the function create an empty list named cards delt then update the last line of the function to return cards dealt instead of return card so let's do that really quick we're going to do cards dealt is going to equal an empty list and i'll just copy that and paste it right here now do you remember how to use a the range function with a for loop we talked about it earlier in the course we just briefly touched on it but let's create a for loop that's going to add a card from the deck for each card dealt so we can do that by creating a for loop for x and range number now this is a common thing you're going to be doing in python creating a for loop that's going to be in range number because now it's going to loop this many times it's going to loop this many times which is the number we passed in here and we're going to do a few things in this for loop first we are going to actually do this what we already have card equal cards dot pop and then we'll do cards delt dot append card so now just this card that we popped off the deck we are appending it to the card's delt and then we're returning the cards dealt here so down here in the code let's separate out a single card from the two cards dealt so let's create a variable called card and set it equal to the first item in the cards delt list and then we'll just print that card instead of cards dealt so we are going to do card equals cards delt and then we just use the brackets and put 0 to get the first item in that list and then we'll just print a card now i'm just going to test out the program we're still just seeing a single card here but it's doing a lot more behind the scenes now so now let's separate out the rank part of a single card so after we create the card there let's create a variable named rank and assign it the rank from the card so we'll do rank equals card and then i have to get index one because the rank is this that's the nine here the second item in this card is the rank so each rank has a different value in blackjack the value of an ace or an a in this in this program is 11 or sometimes it can actually be one it's going to be 11 or 1 but we'll get to the one part later so jack j q and k which is jack queen and king have the value of 10 and then the numbers have the value of the number so we need to check what the rank is and set the value depending on the rank so this is the perfect time for a conditional statement specifically an if statement before the final print statement or program we're going to add an if statement to check if the rank equals a and if so we'll assign 11 to a variable named value so we'll do if rank and i hope you remember if you're flying along i hope you remember to use two equal signs instead of one equal sign here so if rank equals a then value is going to equal with a single equal sign is going to equal 11. now if rank does not equal a we'll want to check if it equals j q or k that can be done with an elif statement for now we'll just create an if statement to check if the rank equals j and then if so we will set the value to 10. so we talked about the three logical operators and or and not you can use these three operators in conditional statements to check multiple conditions at once so we want to check if rank is j or rank is q or rank is k so update the code with the the and with the ors now there can be any number of ls statements after an if statement but at the end there can only be a single else statement and like we discussed the else is just going to be if none of the other ones are true so let's add an else statement and inside we'll just assign rank to value because we've already gotten all the letters out of the way the rest are numbers and we can assign it directly to the value now we'll instead of printing the card at the end let's print the rank and the value so i can just type in rank comma value and when that multiple values in a print statement are listed with a comma separating them both values are printed with a space in between so let's test this out a few times q10 five five 6 6 so we can see every time we press it it's going to be a random rank and value now we already talked about dictionaries in python it's like a list but more general you can think of a dictionary as a mapping between a set of indices which are called keys and values so key value pairs each key maps to a value so above the print statement let's create a variable called rank underscore dict for dictionary and create a dictionary with two items a key value pair for the rank and a key value pair for the value so we have the string rank here and then the actual rank variable string value and the actual value variable before we are printing the rank variable and the value variable but let's update this code so we're actually getting the rank and value from the rank dictionary right here so i'm going to copy that and then i just pasted that but now i'm going to use bracket notation and so i'll put two brackets but then i also have to surround this in quotation marks and then i'm gonna put the rank dictionary the brackets and then the quotation marks because we're accessing that key there and then i can just run the program and it's still doing the same thing as before just a lot more complicated as far as the code goes but it's going to be good to have more complicated code as our program is going to become more complicated as we go so when writing a program there are many ways to do almost everything now we're going to refactor the code to get the value of each rank without using an if statement instead we'll store both the rank name and value in the ranks list using dictionaries so let's delete all the code lines of code after where it says shuffle so here i know we typed in a lot of stuff there but it was just kind of to practice and now we're going to practice a different method of doing this so now let's create a new card variable a new variable called card at the end and let's assign to the card variable a a single card that will deal from the deck but we'll make sure that card is not in a list so this is a little tricky i'm gonna do deal and i'll deal one card but now i have to get the first item so this is going to deal one card but the one card is going to deal is going to be in a list so i want to get the first item in the list which is going to be the only item in the list so i had to put the zero in brackets here to get that card out of a list before it goes into the card variable now we're going to update the ranks list so here's the the ranks list each element the list should now be a dictionary when lists or list elements are long it's common to put each element on its own line so we're going to put each element on its own line and each element is going to have the rank and the value so for instance it will be rank a value 11 rank 2 value 2. so it's going to look like this and i'm now i'm actually going to zoom out just a little bit and we have all these they're all these ranks and each one in this list is a dictionary each element in the list is a dictionary okay now that this is updated let's go down and just print a card so we can see now that we've updated that ranks list so print card okay so this is what it's going to look like coming from our list so we got the suit and then we have the rank that's also going to have the value here the rank and the value we can see every time we click it we get a random item now let's update the code so instead of printing the whole card we just print the value so in this example the value is two so we just want to print this to just that that value so how can we update this see if you can figure out how to update this line so only prints just the value number there so first of all we have to see that we're in a list and we need so this is the first element of the list this is the second element so wait to start by getting the second element of the list which is index one and then we have an object here or a dictionary i mean and we need to get so here we have this key value pair so we need the value at that key so to get the value of that key we are going to put more brackets and i'm going to put value the key of value so now with that should work let's try it okay nine seven see every time it's gonna just give us the value of the card now we'll start defining classes that will be used in order to separate out different aspects of the game so classes you may remember provide a way of bundling data and functionality together creating a new class creates a new type of object allowing new instances of that type to be made an object can contain a number of functions which we call methods as well as data that is used by those functions called attributes so we're going to use classes to model three parts of the game a card a deck and a hand so far we've mainly worked on the elements of the debt class so right after this import statement at the top we're going to make a class a class called dec and we're going to put everything that we've written so far in that class so we're just gonna do class deck colon okay now we just highlight everything here and then i'm gonna press tab to put everything in the class of deck because everything's indented a little bit and then these last few lines of code we don't need so i'll just delete those those are just for testing out a class is like a template you can use that class to create an instance of the class called an object then you can use the instance each instance keeps track of its own state so you can update an instance created from a class and it won't impact other objects created from the same class soon you'll see an example of all this to make it easier to understand but first let's prepare a class to create an instance from it when you create an instance of a class python automatically calls a function also called a method in the clast named init remember we already discussed this earlier in the course so the contents of this init method should be code that is run one time to initialize the instance so at the beginning of our class let's create this init function so we'll do def underscore underscore init underscore underscore and if you remember from before we always have to pass in self to all of these functions in a class because then it gets itself is referring to the instance of the class that we've developed now we're going to indent all the code that's not part of the shuffle or deal function so the code will be part of this new function so i'm just going to highlight all this here including the suits here and then just press tab so like i said we just added self in here you should always all the methods in a class or all the functions should have self anything inside the parentheses remember is called an argument their variables pass them from the color to the functions as i've said all functions in a class should receive self as an argument and self represents the instance of the class by using the self keyword the function can access the attributes and methods of the class so let's make sure to add self as the first item in the parentheses of the other functions so we are going to add self here and then see how we already have number here but we're going to hit self at the beginning and we so we can still call this function with just a single number but it's going to also get a reference to the instance here now i want you to notice that the cards here is underlying in red so before it wasn't when we were before we made this into a class we could just access this cards variable but now we cannot so let's fix that inside a class in order to access a variable in multiple functions also called methods the variable has to start with self dot so we're going to change all instances of cards in every function to self.card starting with this so self dot cards now this is going to make it so we can access it in other places and then we'll change this to self dot cards and then this is self dot cards and then self dot cards so now this will be a variable that's specifically associated with the instance of the deck that's created and then we can access it in all of these other methods okay we can now create an instance also called an object of the deck class so at the very end of the code let's create a variable called deck 1 and make it an instance of the deck class so to make sure i'm not indented at all and i'll do deck 1 equals deck there we go now since we created cards with self.cards we can access that we can access cards from the instance of the class so let's just print out the cards from our deck one so do print deck one dot cards and we can try that out now you can see the the list of all of these cards it has the suit and the rank and the value for each card so underneath where we created deck one let's create deck two we'll create another instance of another deck so [Music] so now we can call methods on these instances and you see some of the methods we have we have shuffle and deal so on deck 2 right after we create the deck 2 let's shuffle the deck so deck 2 dot shuffle and then i have to make sure to put the parentheses at the end here right if we print deck one let's print deck two or the cards of deck two so i'm gonna copy that and then we'll print deck two cards so now we should see that the deck one cards are not shuffled and the deck two cards are shuffled so let me move this over here i'm gonna run the program and let's see if we can see that where deck one so here's where here's deck one and we can see how it's all diamonds diamonds diamonds diamonds diamonds all the diamonds are in a row because unshuffled but then if we go into deck 2 we can see we have diamonds clubs spades diamonds hearts so these are shuffled in deck 2 they are shuffled okay the deck works now let's add safeguards to prevent errors every time the deal function is called a card is removed from the cards list you can only remove a card if there are cards to remove so before the program tries to pop a card off self.cards is to check if the length of self.cards is greater than zero remember you can get the number of items in a list with length so see if you can figure that out on your own and then i'm about to show you how it's done so when it's going to deal here right as we're dealing we're going to add an if statement here so if the length of self dot cards is greater than zero and we do we don't need this parentheses here so if the length of self.cards is greater than zero then we will do this we'll pop up a card and add it to the cards dealt if not we just won't do anything and then we'll return cards dealt which could be an empty array if there were no cards on the deck now let's add something to the shuffle function a deck with only one card does not need to be shuffled so let's add the appropriate if statement to the shuffle function so we'll do if the length of self dot cards is greater than one then we will shuffle and then make sure i'll make sure to put the colon there okay since a card is a separate concept than a deck next we'll make a card class so let's create a card class with an init function and in that init function we'll set self.suit to equal hearts so hopefully you already tried this i'm going to do class card and then i will do def net [Music] and then after the suit will lose self dot rank and set it to a so currently anytime a card is created it will be an ace of hearts let's refactor the code so the suit and rank are specified when a card object is constructed so the init method can take additional parameters besides self that are passed into it as objects is constructed so we'll update it to take suit and rank [Music] now we'll create a special method that's underscore underscore str underscore underscore when a class has this specific method it's called when print is invoked on an object from the class so we want to make it so when we print an object from the card class it will print something like 10 of hearts or three of clubs or something like that so we don't do print here we do return it's going to return this to the print statement it's going to turn self dot rank and then we have to get the rank [Music] and we do plus and then of or to put a string there plus self dot suit so now it's going to return the rank which is like 2 or a of and then the suit which is one of these so let's just try it out real quick and we go to the bottom we don't need any of these to test because we're testing something completely different now let's do card one equals [Music] card i'm going to create a card and i have to pass in remember i have to first pass in the suit so how about hearts and then i have to pass in the rank but we want to make it look like these ranks so i'm just going to copy one of these here and then after we create the card i can just print card one let me clear this and then i'll just run that j of hearts oh see i got the j of hearts and feel free to add a few more cards like this and test out a few more if you want okay now we're going to refactor this slightly you remember way toward the beginning of this course we talked about f strings so f strings allow us to put variables right within a string do you remember how to do that let's see if you can update this to use enough string so first we're going to create a new string but we're going to start with the letter f and then inside this string we put curly braces around the python code and we don't need these other strings here so now we put another curly brace and then an ending string here okay it's still showing these um red squiggly lines because if i have a double quote around the strings and anytime other quotes are in the middle i have to put a different type of quote so we're going to use single quotes okay so now we can make this a whole a string but we use the brackets to put the variables right within the string so now we've updated that to use an f string so currently in the deck class the last line of this init method appends a list as an item to the cards list instead of appending suit comma rank we'll create and append an instance of the card class then afterwards when a deck is created it's filled with cards so it's just like this we're just going to delete that i'll put card and then i'll pass in a suit and they rank so now we're passing in card instances so we're done with the deck and card classes and we created them in such a way that they could basically be used for any card game now let's make a hand class this will represent a hand in the game of blackjack so create a hand class and add an inet method and initialize a variable called self.cards that is set to an empty list so let's go down here and we can also get rid of all this test code here so the new class is called hand and we'll also make the hand keep track of the value of the hands a self.value will start it at zero in this blackjack game there will be a human controlled player and a program controlled dealer so let's add a dealer parameter in the init constructor method of the hand class and then when the hand classes create a dealer should be set to true or false to keep track of what type of hand it is so i'll pass in the parameter dealer and then we just have to create a variable and call dealer and set it to dealer so self dot dealer equals dealer [Music] if you remember from before function parameters can have default values so we want to make it so the default value of dealer is false so then if we create a hand and we don't set the dealer value it will automatically be false and i'm just going to take out these spaces here to make it smaller here so now a hand can be created let's give it some functionality we'll add an add card method and the method should take a card list as a parameter and then we need to add that card list to the cards so we can use the extend function the extend method to append each item in card list onto the cards list so it's just going to look like this self dot cards dot append no extend i mean dot extend and then we pass in card list now let's just add some code to test out what we have so far so let's create a deck and then we will shuffle the deck deck.shuffle [Music] now we'll create a hand now we can add cards to the hand so hand dot add card and we will deck dot deal we'll deal two cards into the hand and then we'll just print hand cards okay so this is what how it printed out i was expecting this to look a little different because of this function it print it should print like that but i think the reason is because this is a list so it's printing a list not an individual card so let's change this to print an individual card i'll print the first card so put zero in there i'll try it again nine of diamonds and then we can also print the next card three of hearts and then we can also print both cards if we just copy that and do hand that cards zero handout cards one okay ace of hearts and nine of spades so those are the two cards that were dealt to the hand now we'll go back to the hand class and we'll add the ability to calculate the value of a hand so let's add a method called calculate value and inside the method we'll set self.value to zero now we'll take this one step at a time first let's let's make a for loop that's going to go through every single card and inside the for loop we'll just set the value of the card to a variable called card underscore value so i'll do four card and self.cards okay so we're not doing anything with that yet but we're going to in a second here now we want to make sure that this is an integer so let's convert that to an integer if you remember you just use int [Music] and then put it in print int and then inside the parentheses we put this value not just getting the card value for each card is not enough something must be done with the variable so let's add that value to self.value so we'll do self dot value and then if you remember from before we can use the plus equals to add that to the current value those will do a card value so as you may know in blackjack and ace can have the value of either 11 or 1 depending on what is better for the player so there's a few ways to implement that in code so we're going to do one way that's relatively simple first we'll check if the hand has an ace so let's first create a variable that will store whether the hand has an a so just be called hand has underscore ace we'll set to false and we'll put it right under here so we'll do has ace and we'll set to false and since we're only going to be using has ace within this method we don't need to use self that has ace because we're only using it here and now when we're going through the the list of cards let's check if the the rank of a card is an ace and then set has aced equals true so i'll do it if card dot rank the rank is going to be equal double equal sign if it equals ace after this entire for loop we're going to check if the card has an ace and if the value is over 21 if so then we'll just subtract 10 from the value because that'll be the same as setting the ace to equal one instead of 11. so we'll just do if has ace and self.value is greater than 21 to self.value minus equals 10. okay and look at this this is something i don't think i've discussed yet you could say if has equals true and self.value is greater than 21. but you can also it's like a shorthand you don't have to say if has ace equals true if has a because has ace is just going to equal true or false you can just say if has ace so that's just the same as saying if true or if false and so we're seeing if both of these evaluate the true then we will subtract 10 from the value okay now we'll just add another method to get the value of a hand called getvalue and the function will just return self.value so we're going to make sure that we're not we're indented correctly and do def get value return self dot value and then i have to make sure i put the parentheses here and then i have to remember to put self since this is a self.value we could call down here like we could call hand value to get the value but it's generally better to make a function to return the value so i can do get value that way there may be some extra code you want to run in there like depending on different conditions you may want to modify the value before you return it so it's best practice to create a method that will get a value like this for you so currently this value that's returned could be incorrect because if someone's going to get the value the value has to be calculated correctly first and like checking for aces and and other things so let's call let's calculate the value before we return the value so i'm going to do self dot calculate value so this is something that i think is new where to call calculate value from within this we're going to have to call self.calculatevalue and self will refer to the instance that we're working with so we're calling the calculate value on the instance that's that is the the hand instance and we're getting the value and then we're returning the value okay let's create another method called is blackjack and it'll return true if there's a blackjack and false otherwise so it's a blackjack if the value is 21. so i'm gonna do def get or is oh and put self here okay so this is going to evaluate you to either true or false and return true or false depending on whether there's a blackjack now we'll create the final method in the hand class that will display information about the hand so let's create a method called display they'll to start with will just print your hand [Music] okay now let's do a quick refactor instead of saying your hand it should either say dealer's hand or your hand depending on whether self.dealer is true or not so we're going to you to to do this all in one line we're going to use a few things that we learned about earlier including ternary operators f strings and going between double quotes and single quotes and then one other new thing we are going to make this into an f string and then we are going to be using actually single quotes and double quotes within this f string so if you want to use single quotes and double quotes within a string then you can surround it with a triple single quote so i'm going to delete this quote and just do three single quotes and then delete this quote and do three single quotes and so we got the double quote single quote and now this is a triple quote so now we can use the double quote and single quotes within this string so i'm going to um i'm just going to delete your right here and we are going to put a ternary operator to see if it's going to say dealers or yours in the dealer's hand or your hand so to do some code i'm going to put these curly braces here and then to do this ternary operator we're going to put dealer and now here so here's the double quote and here's the single quote so dealers it will return dealers if self.dealer so basically if self.dealer equals true so return dealers if self.dealer else will return your okay that's the line so it's going to be the dealer's hand or your hand and next we will add a for loop that will print out each of the cards so for card and self.cards print card and then finally if the player is not the dealer it should print value and then a colon and then print the value of the cards so to do this we can actually use the the not operator so if not self.dealer [Music] then we will print and we'll print value value and then i can just put a comma to print two different items so the string and it'll print self dot get value and it's gonna when you put a comma and two different things it's gonna put a space in between and then finally we'll just add an empty a print statement that will print a blank line okay let's test this out by instead of printing this we are going to print hand dot display to see if this all works how we thought it was going to work so your hand k of spades two of spades value is 12. so it's actually calculating that correctly because that's 10 plus 2 is 12 and then it's going to print none which indicates that we did something wrong which is that we did not need to print this because hand display display already prints so now just call hand.display okay so now it doesn't put none or doesn't yeah it doesn't put none at the end so that looks right okay when you're playing blackjack you don't get to see everyone else's cards so we're going to update this so when the dealer's cards are printed during the game only the second one should display the first card should display as hidden so in this for loop when we're displaying the cards we're going to need to get access to the card index since that will determine which to display since we're only going to display the second card so let's start by updating this for loop so we can get access to both the card and the card index we briefly touched on this earlier in the course we're going to be using the enumerate function so when it's for card in and now i'm going to type in enumerate and i'm going to pass in self.cards and this is going to return the index and the card for each card so i'm going to type it index comma and so in we're getting the index and the card for all the items in self.cards and so now we just have to update what's in the for loop to print hidden if it's the first card and it's a dealer so we'll do if index equals zero and self.dealer then we will print hidden and then we can use an else any other time and let's make sure this lines up correctly any other time we will print the card so what we did wrong here is this should be double equal sign i did almost did the the main mistake you always have to watch out never use a single equal sign when you're checking equality because that's the single equal sign is the assignment operator so if index equals zero and self and we it is the dealer then we'll print hidden so in our version of the game at the end of the game that all the dealer's cards will be shown so you can see what the dealer had so to do that we're going to create a new parameter in this display method and it's going to be called show all dealer cards with underscores for spaces and we're going to set the default value to false show all dealer cards and when the default value is going to be false now we'll add it to this if statement so we'll add another and not show all dealer cards so it's going to be hidden if we're not showing all the dealer cards but if we are showing all the dealer cards then this whole if statement will be false so we'll just print the card and there's going to be one other scenario where we're not going to print hidden if there's a blackjack then the game is over the person with the blackjack is just going to win and then we'll just print all the cards so we're going to add that to this long if statement here so we'll say and not is black jack and it should be self dot is blackjack to be able to call this method here and since this is such a long line is always going to go to this next line we can do this special thing we can add a slash here and then just go to the next line so this slash or it's a backslash i mean this backslash will indicate that the line continues on the following line okay we're done creating the hand class so we'll delete everything that we were using for testing before okay it's time to code the final and longest class that runs the game so what i want you to do is create a class called game and inside the class create a method called play and inside the method create a variable called gamenumber with the underscore for the space and set that to zero so class game and then we'll create another variable games to play and set that to zero now we're going to set games to play to be whatever the user inputs after they're asked how many games do you want to play so you may remember how to do input from before so we just do input now we want to make sure the games to play is an end so we just need to convert this to an end [Music] okay now let's test things so far so at the end i will put g equals game i'm going to create a new game and then g dot play okay let's test this how many games you want to play five okay well it's not going to play the games yet we still have to create that so there is a potential for an error here if i do this again and i just put how many games i put you or some letter we're going to get an error so basically anytime someone puts something that's not a number is going to be an error so let's create a try accept block to handle the exception and if they put something that's not a number we'll print you must enter a number so let me arrange this and we've already learned a little bit about try except blocks i'm going to put try and it's going to try this and then if that doesn't work if there's an exception [Music] it will print [Music] you must enter a number so currently the user gets only one chance to input a correct value let's make the program keep asking the user for a value until the user enters a number this can be done with a while loop the while loop just keeps looping while something is true so keep looping until the user enters a number by putting the entire tri-catch block into a while loop that keeps looping while the game's a play is less than or equal to zero [Music] oh and i have to make sure i spell while correctly okay now let's create the main game loop this is a new loop that will loop one time per game played it should loop while game number is less than games to play and the first line of loop should increment the game number by one inside the loop we'll create a deck object in a deck variable and shuffle the deck now we'll create a variable called playerhand and set it to a hand object and then we'll create a variable called dealerhand and set it to a hand object but this time we'll make sure to specify that dealer equals true okay this next part will be a little more complicated we'll create a for loop that loops two times and each iteration should add a card to the player's hand that is dealt from the deck and add a card to the dealer's hand that is also dealt from the deck [Music] okay we just dealt two cards each player now information is going to be printed to the console for each game so let's start by printing an empty line now we'll print an asterisk 30 times to make a divider there's a trick to printing something a lot of times so i can put an asterisk in in quotation marks and then just do times 30. so it's going to print it 30 times now we'll print the current game number out of the total number of games so it'll be something like game 4 of 10 and we'll use an f string and then we'll just print 30 more asterisks now we'll display the player's hand and then the dealer's hand at this point in the game someone could already have won if they got a blackjack the code should check if there's a winner let's put the code to check if there's a winner in a separate method of the game class so create a method called check winner for now the method should just return false and just make sure everything's indented correctly this should be less indented than the previous line here the check winner function should take the playerhand and dealer hand as arguments now before this return statement we're going to check if playerhand.getvalue is greater than 21. if so we'll print you busted dealer wins and then return true and remember once the program gets to a return statement none of the following statements in the block are run [Music] now we'll use a few lf statements to check for various other conditions so we'll add an lf statement to see if the dealer got over 21 and then we'll print dealer busted you win and then return true [Music] oh and i just copied all this but this should be an l if not if and then we'll add an lf statement to check if both players have a blackjack and then we'll print both players have a blackjack tie and then return true [Music] and then we'll add an elf statement to check if player hand has a blackjack and then we'll print you have blackjack you win and then return true and then we'll check if the dealer hand has a blackjack and then say dealer has blackjack dealer wins and return true [Music] okay we're done with all the hand when conditions but the game can also end if both players choose not to get more cards so we're going to add a new argument to the check winner method with a default value it's going to be game over equals false so we'll add game over equals false if it's true that means both players have chosen not to get more cards now we'll use the new argument the string of if and lf statements should only be run if it's not a game over and we'll make sure the line returned false is not in the if statement so here we'll say if not game over and then i'll just select all these and put them in here so if game over is true we'll check if the player hand's value is more than the deal hands value and if so we'll print you in so we can do this with an else here else if player [Music] and then we'll do an lf for if it's a tie so this is an lf and we'll say if these are equal to each other and we'll print tie and then make sure we have the correct emoji for a tie [Music] and then else the dealer is one so we'll just do else [Music] and then at the exact same level of indentation as the else we just added we'll add return true this will make the method return true if game over equals true now let's go back to the play method inside the while loop and then we'll do an if statement and we'll do if and then we'll call the check winner function with the player hand and the dealer hand so let's go back up here if self dot check winner and then we'll enter the player hand and the dealer hand [Music] so if this is true that means we should go on to the next game to do that we do continue so continue is going to just go to the next iteration of the loop and the loop we're on is this loop so when we go to the next iteration we start a new game at this point in the game the player will be able to choose hit or stand so inside the while loop but not inside the if statement we just added we'll create a variable called choice and set it to be an empty string the player should be able to keep choosing until the value of their hand is over 21. so right under the choice variable we'll add a while loop that loops while player hand's value is less than 21 and inside the loop we'll add a line to get the choice that's either going to be hit or stand [Music] and then we'll just add this to convert whatever the answer is whatever the user put in we are going to convert it to lowercase the while loop we just added should also stop if the user's choice is stand or or s so we'll update the line that starts the while loop to also stop if the choice isn't s or stand so just do and choice not in and this is there's a few ways to do it but this is kind of a new way that i'm just showing you here [Music] so we are checking if choice is not in this list and inside the list we have two elements s or stand so if choice is not in that if the choice is not s or stand then we'll continue the loop and then after the input we'll print an empty line also we want the program to keep asking the user for a choice until the user enters a valid choice the valid choices are hs hit and stand so right after the last print statement at the same indentation we'll add a while loop that will keep looping until the user enters a valid choice and inside that while loop we'll ask for input again but we'll specify it can be h or s as well [Music] so this is going to look very similar to this line but it's going to kind of clarify things just a little bit and then we'll print another empty line the last while loop we checked if choice was not in a list outside of the recently added a while loop but inside the loop we just added before that one we'll add an if statement to check if choice is in the list hit or h and if so we'll add a card to the player's hand that is dealt from the deck and then right below that will display the player's hand outside all the while loops about the player making a choice we'll check for a winner we'll use the same if statement and continue statement that we use last time we checked for winner so i'll just copy this and then we have to make sure it's lined up correctly okay so this is outside of this while loop so after this all is all done we check for a winner let's just add an empty line there to make it more clear that the while loop is over now we'll store the value of the player's hand in a variable named player hand value with underscores for spaces [Music] and we'll do the same thing with the dealer's hand [Music] remember i could use the command d or control d to select two words at once and change them both at the same time okay the dealer should keep drawing cards until dealer hand value is more than 17 so we'll make this happen with a while loop and inside the loop we'll make sure the dealer is dealt a card from the deck and that dealer hand value is updated so you can try that yourself but i'm going to show you right now while dealer hand value is less than 17. then we will do dealer hand dot add card okay and after this while loop will display the dealer's hand and when we call the display method we'll make sure to set show all dealer cards to true [Music] and since it's the end of the game that's why we're just showing all the cards now we'll check for a winner just like before then we'll print final results then we'll print your hand colon and then the player hand value [Music] and then the dealer's hand now we'll call the check winner function one final time but this time it should not be an if statement and we'll pass in the hands like before but this time we'll add a third argument of true to indicate that the game is over and at this point in the code the game is over so outside the outer while loop and in the play method we'll add the final line of saying thanks for playing so it's going to be outside that while loop and we'll put print and just to demonstrate it i use an escape character to add a new line so this slash in is going to add a new line and then do thanks for playing and when i line this up for with the while loop i realize that this entire function should not be lined up with the while loop sometimes it gets tricky with um figuring out the exact right indentation so if i kind of go up straight up here i should say see that this should be lined up with this play function so i'm going to come back down to this function i'm going to copy this all and i'm just going to do shift tab to indent it all one less this happens sometimes when running python code sometimes the indentation can get all mixed up but that should be correct now and i think the red squiggly lines here on the return true are not a mistake in the code but a mistake in the error checking because it comes after that emoji and it doesn't know how to handle the emoji but it's perfectly fine for code to have emojis okay let's run the program and try it out so i'll press play how many games i want to play i'll do three so game of one of three so i can see i have 17 i don't know what the dealer has but i'm going to s for stand okay it's always good to test so it says deal is missing one required positional argument so let's go up to it says line 139 so this can kind of help us know where to go so let's go up to 139 and yeah i want to deal a single card so i'm going to deal one card here and were there any other times i did use deal i want to deal one card here and yeah i got the deal one up here so i just think i just forgot the deal one in those places so uh thanks to these error messages whenever you have a problem make sure to read the error messages and it can often give you a very good idea of what you need to do wrong because even says deal is missing one required positional argument the number so that can really help figure out what's wrong with your code so let's try that again we'll do three games and then this time i will hit and i'm going to stand okay so now we have another error so it says 173 and oh this i can already see this is spelled wrong so let's go to 173 and make sure i spell that correctly and make sure i spell that correctly okay let's try again how many games you want to play three i'm going to hit and hit okay so the first game you busted dealer wins and now we're on game number two i'll hit and this time i will stand okay dealer busted you win now we're on game three of three and i will hit and i will stand and final results your hand 20 dealer's hand 19 you win thanks for playing we just completed this whole game okay we've reached the end of the course so you've learned the basics of python and if you've been coding along you've written two python programs good luck on your programming journey thanks for watching and remember use your code for good bye bye bye bye bye okay
Info
Channel: freeCodeCamp.org
Views: 2,463,573
Rating: undefined out of 5
Keywords:
Id: eWRfhZUzrAc
Channel Id: undefined
Length: 279min 59sec (16799 seconds)
Published: Tue Aug 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.