Python Tutorial for Beginners | Python 3 Tutorial [2021]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone my name is brian and we're going to learn python 3. this video series is aimed at the complete beginner so if you have zero programming experience this is what you need to watch now we're going to start off in this specific video with how to install configure and test python 3 and i'm going to try to make a video a week so definitely check back often as i'm going to update this series as fast as i can let's dive in okay the first step is very simple check to see if python's already installed now you can and probably should use your operating system's documentation to figure out if it's installed but a very very quick way is simply bring open a command line you don't know how to open a command line i highly suggest you go out to google and learn how to open a command line it's not super hard and once you get to this point type in something like this python 3. if you see this right here where it says python and then some version it's already installed and ready to go and you can simply skip the next step however if you don't see this if you get like command not found or unknown command then you're gonna have to follow the next step and actually install python special note a lot of documentation out there will say type the word python this is the older version of python this is python 2. see right here python 2. we're going to be working with python 3. okay assuming you ran a command line and tried python 3 and got a big fat command not found or command unknown you need to install it go out to python.org and then go to downloads from here you can either click all release or you can go into your specific operating system we're gonna go to all releases it will try to auto detect what you're doing however you may need to pick your operating system the vast majority of you are probably going to be on windows so i'm just going to click on windows then click on python 3 release the latest one notice this is a python 3 not a python 2. and scroll all the way down they've kind of got these jumbled up together you notice how you got you guessed it a tarball something for mac and then stuff for windows windows has the vast majority of the options and this is why it gets a little bit confusing honestly i'd go with this one windows x86-64 executable installer that's going to be an offline installer it's going to have everything you need to run or at least it should you're going to download that executable and run it you may be prompted to run as administrator and you may have to restart your computer when you're done after you're done installing you will definitely need to go back and double check you should be able to open a command line and type python3 if you cannot get to this step you may have to go to google and look for your specific error message to figure out what's going on now that python's installed and configured and we can bring up a command line and type python3 we need to test this thing out make sure it's actually working the way we expect it to first things first i'm just going to drag this up like this to take up the rest of the screen and we're in what's called the interactive shell or interactive mode we are not going to be using this very much because well it's a bit cumbersome if you make a spelling mistake it's impossible to go back and fix it so we're going to use an ide but right now we're just testing i want you to do something like this say x equals five times three now we're going to type the word print and then let's say x notice that's in brackets we're going to cover all this later right now we're just simply testing you should see 15 on the screen to be brutally honest typing python 3 and even seeing the version is really the true test that this is working however i wanted to show you there is an interactive mode if you want it again though it's really hard to go back and edit configure and you're going to make mistakes so we're not going to use this at all we're going to use an ide or an integrated development environment which we're going to cover in the next step when talking about integrated development environments well there are tons and tons of them if you just go out to google and type python ide you're going to get well millions and millions of results because there's just literally thousands upon thousands of ids to be brutally honest you don't need anything fancy you can use a simple text editor really what an ide is is a very fancy text editor with a lot of functionality built on top of it you'll probably find a lot of documentation that says idle comes directly with python that's not really true anymore you can install it a little bit separately and uh personally i don't like it i don't think it's the greatest pycharm is another good one but we're going to be using something called visual studio code and i know a lot of folks really are not microsoft fans you're not forced to use this it's what i'm going to use for this series and without warning i may change ides halfway through just depending on what i feel like coding in because python makes it super easy to do that the reason why i'm using visual studio code is well it's very simple it's very straightforward and this is what it looks like so all i'm going to do here is i'm going to just add a folder i'm going to go into python3 close this out now i need to add in some extensions and this is what i love about visual studio code is you can extend this to work with just about any language so i'm going to say python and you see there are tons and i mean a lot i could just scroll down forever and ever to like infinity and beyond kind of forever i mean there's tons of extensions but it does a good job of putting the best ones right at the top you can see this guy right here from microsoft 26 million views five-star rating you just simply go okay do you actually need it that's a good question because you could go through and spend hours just installing all of these and not know what you really need so we're going to take a short detour go back here this is simply the folder we opened i'm going to say new file and let's call this test dot py and it automatically recommends extensions for us a python file will end in dot p y so it's detecting that extension and saying hey do you want to use the recommended extensions i'm going to say you know what why not and it's going to automatically go out there and install them and that's going to say installed and it's used globally there we go and we can even click this little gear icon and play around with it if we really felt like let's go back to our file or we can use it up here depends on how you want to get there now this is my only real criticism of visual studio code is it does tend to clutter the ui a little bit so occasionally you'll see me closing things out and i'm just going to well start using this bad boy okay to wrap this video up we're going to make what's called hello world this is kind of the obligatory first application you're going to make in any programming language it's actually a rite of passage for programmers and it is very simple it's just printing out the words hello world on the screen and this is where we're going to hit some stumbling blocks if we're not fully configured so what you should see before you is everything we've done so far you should have your ide whatever you're using even if it's just a simple text editor and you should have a blank file called test.py the name's not super important and last but not least you should see the python interpreter i have python369 you can actually switch to different ones if you wanted to just be aware that you can use different versions i'm going to type the word print and then we're going to give it some brackets anything in the brackets it's going to try to print now with python you can use double quotes or single quotes i have a habit of using double quotes but it really doesn't matter which one you choose and then type the words hello and world click save now you should have this little guy right here that says run python file in a terminal if not you can go up here you're gonna have a few options start debugging and run without debugging immediately if you're a newbie you have no idea what this means debugging sounds really really bad so what does this really mean debugging is a special mode in programming where if you have bugs or errors in your code it will walk you through them and help you fix them or more to the point point them out to you so that you can fix them often i'll run without debugging because it is a little bit faster and you should see something like this on the screen hello world all of this stuff looks really nasty but really what's going on here is you have your installation path for python 3 and then you guessed it everything that it's doing in the background it's calling this launcher and it's saying run this script the end result is this now because i'm not a huge fan of hello world because it's so overly simple let's actually get rid of that and we want to go back to what we did the interactive shell where we're going to say x equals 5 times three what we're doing is we're making a variable we're going to talk about variables in the next video but what we want to do now is just simply print this out save this and i'm going to go ahead and run and you see there's 15 right there welcome back my name is brian we're going to continue our conversation about python 3. whatever ide you're using go ahead make a new file and give it some type of name i'm just going to name it playground not really important what you name it you just need some sort of file you can play around in remember these videos assume you have no experience so we're literally starting with a blank slate the first thing you're going to learn is what is a variable i'm going to write this out here well a variable is simply something that will change for example if i declare a variable named x i have to assign this some sort of value let's go ahead and try and print x out see what happens here notice it's going to have some sort of error it's going to say name error name x is not defined what does that mean well clearly we defined it it's right here really what python's trying to tell you is that it doesn't really have any sort of value so i'm going to say 42. now let's go ahead and rerun this notice how suddenly it says 42. so if you get a is not defined really what you're saying is you have not set that value you notice how this is a number and this is what i mean by a variable is something that will change i could have very easily said hats notice how cats is a string a string is just a series of characters but it's not a number is the point i'm driving home here and if we run this it works just fine so under the hood what you have going on here is python knows it's smart enough to know what type of information we're storing in this variable and we can change it at a moment's notice so for example we have x equals cats and let's just grab this little copy and paste action and we'll say x equals i need some sort of number why not and the ide is not happy with me it's saying invalid token i'm just gonna get rid of that zero maybe that'll clear it out nope will not let's go ahead oh there it goes let's run this you notice how it says cats and then it's got a number so we can take this same variable and change it and python is smart enough under the hood to know that x is a string and x is an integer so what we're really diving into and we're going to spend a lot of time talking about this is data types and when i say a lot of time i'm going to break this into multiple videos because each data type whether it's a string or a number like an integer here has different properties that you can access so the short answer to what is a variable is just simply that it's something that will change that's it it's that simple a lot of instructors are going to take like months and months and months to explain what a variable is and how it lives in memory and blah blah blah but as a programmer we don't care about any of that we just want it to work and this is computer programming 101 you declare some type of variable you set the value and that value has some sort of type and with that type you can now work with it interesting note here if you're coming from another language or if you know a little bit about programming python you do not have to declare the data type for example in other languages you may have to say something like int x equals three so what we're really doing here is we're stating or telling the interpreter this is the data type we're going to work with we don't have to do that in python it's smart enough to figure it out on its own okay let's take a little detour down to theory land now what we're going to talk about is dynamic and strong typed python is both and this is often confusing for people especially coming from other languages as you saw we don't have to declare the data type python's smart enough to know in other languages you do have to declare and that gets super confusing to people so we're often asked this question why is python a dynamic language and also a strongly typed language and what do those two things really really mean dynamic means just that it's dynamic you don't have to declare a variable type and you can change that at a moment's notice as you saw right here we went from a string to a variable and it's smart enough to keep track of everything for us and no errors were thrown other languages you're going to get a huge error because we're saying once you declare this as a data type it can never be anything different that gets kind of convoluted best answer here is python is a strongly typed language as interpreter keeps track of all variable types meaning the interpreter python itself is smart enough to know what you want it to do but it is also guaranteeing under the hood that once you assign it it's going to stay that variable type until you overwrite it or change it remember a variable is something that will change and with python that's very very true because you can change it to a completely different data type a lot of other languages you simply can't do that welcome back everybody this is brian we're going to continue our journey with python3 whatever ide you're using create a blank file i've got mine named python3-3 at this point the name's not important just have a blank file ready to go we're going to cover three key things comments booleans and comparisons let's dive right in okay comments you've actually seen them but we haven't really talked about them what is a comment without writing any code go ahead and run your script you see it does absolutely nothing we're going to hit the pound sign and just type something this is a comment so really what does this do well if we run our program you'll see nothing's changed it does absolutely nothing a comment is just that it's a comment on the code it exists solely for you the programmer so you can keep some sort of notes so for example you can say this is our third video and you notice how you can add in letters numbers whatever you want and it's not going to throw any sort of error message when we run it this is strictly for you this is your note now if you're coming from another programming language you're probably hoping there's a multi-line comment meaning if you have a few lines like hello world i like cats you notice how as i was typing it tried to help me out and it put what we call intellisense in there which is code that's already pre-written for us well we really didn't want that so it just caused all sorts of errors now if i were typing in a comment i'd say hello world i like and you notice how intellisense suddenly is not really popping up i can force it pop up by hitting control and space but it doesn't really know what we're doing because we're in a comment multi-line comment would be like if you had and i'm just going to grab some text here this is not a comment even though it says it is a comment it's really not if we try to run it oh you see invalid syntax because it's trying to interpret this as code now we can put a pound sign in front of each one of these for example let's just go this one and this one this one and it's gonna get really dull if you got like a hundred lines you need to do so what a lot of python developers will do is this they'll just have triple quotes and anything inside the triple quotes becomes a string string something we're going to really talk about in depth in another video just know that this is a data type so we're not truly making a comment we're making a string but the string does absolutely nothing so if we run that again there's no error message let's clear that nasty error out just so you can see you can run this all day long and there's no error message but we have created a variable believe it or not so i do not favor this and be a little careful this might cause issues later especially if you get into like doc strings and things like that which we're going to cover later on in this series so you may be asking what is the functional purpose of a comment well it exists solely for you the developer as a note you can also enable and disable code using a comment so for example let's just say x equals one print x you can see it is now printing one we could change this to hello world which we did in the previous video and there's hello world now if we comment this out this x technically no longer exists and you see it's giving us a little red squiggly line it's saying undefined variable and if we try to run this you guessed it boom name x undefined so we can disable this code by commenting it out we can re-enable it by simply deleting that pound sign so let's cover our first real data type here and this is very fundamental it's called the bully some people just call it a bool for short and it is a true or a false think of it like a light switch like physically look at the light switch in your room it's either on or off and that's really what this data type signifies so let's make a few i'm going to actually comment out this code and let's make some i'm going to say x equals true notice how it has a capital t and intellisense is trying to help us out by saying hey it must be capital and y equals false again capital f you may be tempted if you're especially coming from another language to give it a data type like this if you do that bad things are going to happen it's not going to know what you're trying to do we can actually try to run this and you'll see what i mean invalid syntax so it's not understanding what's going on when we get rid of that suddenly magically it works clear that error out so it doesn't confuse anybody again these are case sensitive so if i change that to a lower case you see how intellisense no longer has that as blue and we're going to get a nasty little issue if we try to run this name true is not defined remember when you see is not defined that's the interpreter's way of saying hey i have no idea what you're trying to do here simply because it does not exist let's switch this back to a capital t and life is good so i'm going to just copy and paste some notes in here notice how you can put a comment on its own line or after if you put it before for example if i move this right here it turns everything after it on that line into a comma so be very careful doing that and these comments have absolutely zero impact on our code for example we can run this all day there are no error messages then clear this out now that we have that understand that we want to do some fundamental comparisons which is what we're going to talk about next okay let's talk about comparisons first off what is a comparison well it's a building block towards programming logic so comparison is the building block of logic meaning we want some value take that value and compare it to another value to see what we need to do with the programming logic here for example i'm just going to print out x and y i'm gonna do this a little bit differently i'm gonna put the letter f which stands for formatting and i'm gonna say x equals brackets and then x looks a little confusing but really all we're doing is saying print out x but do it in a fancy manner see x x now i can change this to y and it becomes very simple to understand what's going on x is true y is false we're going to compare these two now so the very first comparison we're going to do is equal and it's actually pretty straightforward so i'm just going to grab this and let's say hmm equal we're going to do our logic here and we're going to say you have to be a little careful when you're doing equals because if you just do this you're actually assigning these are called operators this is the assignment operator we're now saying x equals y we don't want to do that we want to compare it so we're going to say x is equal to y we're simply comparing then let's say the opposite of that i want the not equal notice it's an exclamation whenever you see the exclamation think exact opposite of what you want so we want is this the opposite of equal or not equal let's go ahead and run this see what happens here you can see x is true y is false they are not equal to each other and it is giving us a true when we test for inequality it's actually pretty cool that we can do that we know virtually nothing about programming at this point in this series but we already have the foundations of computer logic true and false and we can test for those conditions let's take this a step further here and what we're going to do is greater than and greater than or equal to so i'm going to just grab one of these and i'm going to say greater than very very simple we're going to say print out is x greater than y now i want to say greater than or equal to very similar syntax to the not equals to we're saying greater than equal to and let's do the exact opposite let's say less than and let's flip these around let's go ahead and run this and you can see there we go greater than true greater than or equal true less than false less than or equal false these admittedly won't make a lot of sense to you right now until we start talking about the numbers which we're going to talk about in the next video but for bulls know that equal and not equal are great and these are the building blocks of logic we can start doing flow control now which would be things like if then for example if you're hungry go eat otherwise go do something else we're going to talk about all this in future videos but really nail down the fundamentals here what we're really talked about is comments they are your buddies they're your friends be kind of careful how you do those comments and booleans these are simply on or off true or false remember these have to be case sensitive and we've covered some foundational comparisons for example we're saying equality inequality greater than greater than or equal to less than and less than or equal to hello again everyone this is brian we're going to continue our journey into python 3. this video we're going to cover numbers the number data type specifically the int the float and the complex data types and we're going to cover some basic numerical operations for example addition subtraction things like that whatever ide you're using go ahead and make a blank file i've got mine titled python3-4.py the name's not important at this point you just need a blank file to start with last video we talked about the bull this video we're going to talk about numbers i know everybody loves numbers so let's go ahead and start off with the integer type and we're going to make a simple variable here and i'm going to call this ival and let's give it a value of 34. really doesn't matter what value we give it though say print and we're just going to print something out here there we go and let's call this ival equals and we just want to print that value out just to see what this looks like they've run this is pretty basic you pretty much guess what it's going to do it's going to say the i val equals 34. very very simple not super hard to wrap your head around now we're going to take this do the magic of copy and paste here and we're going to make a float float sounds really good right about now like a root beer float or something like that but we're talking about numbers not root beer floats unfortunately so we're going to make a floating point value and it's going to be 3.14 save run on the surface what we're doing looks very rudimentary but under the hood python is doing all of this work for us we don't have to worry about what's actually going on so for example there's a fundamental difference between an integer and a floating point number there's a lot of precision that happens in the background and we don't have to even think about that python takes care of it for us i'm going to import the sys module and what this is going to do is allow us to work with other people's code and we're going to talk about that in depth in another video but just right now take a huge leap of faith that we're using someone else's code this is actually part of python but we have to import it it's a little confusing again we'll talk about it in depth in another video usually it's at the top of the file we're just going to put it right here but we want to be able to get some extra information so i'm going to say sys dot load info and let's go ahead and copy and paste some notes in here just so we can see what's going on i'm gonna grab this and voila put that right there that is the official python documents if you want to go out and look at it and see exactly what's going on we can run it and see under the hood this is what python is really keeping track of when it talks about floats so we have the system float info you have a max which is a really really really large number and you can also have a max exp and you could dive into all this stuff now if you're into numbers and math you probably know what all this is but us mere mortals usually don't care basically if you have a number that has a decimal point you're going to use a float otherwise you'll use an int now we're going to talk about another one and it's called complex and it is well complex now when i say complex actually python makes it super simple to work with but the data type itself under the hood you guessed it is not super simple it is complex and it looks something like this a complex number is made up of two numbers a real number and an imaginary number kind of sounds a little messed up but let's take a look so we're gonna say c val equals and let's say three plus six 6j giant leap of faith that i know what i'm doing there what is that really going to do well it's going to make that complex number and let's grab the name here see val c val and let's print it out doesn't really look like we did a whole lot it's just saying c val equals 3 plus 6 j exactly what i typed let's split this apart here what we're going to do is show an alternate way of creating a complex value and you can do this with float in it but it really drives the point home with complex so i'm going to say complex and notice how it wants the float and the image let's go ahead and give them both so i'm going to say 5 3 and let's go ahead and i'm going to just through the magic copy and paste here grab this let's say c val's that now i want to print out the real and we want to go ahead and grab this copy paste and we want the second part of that number just so we can see what it is go ahead and save and run so now you can see the complex number is made up of two parts and that actually would probably be better if i made it the way it was supposed to be there we go real and imaginary two different parts that's what makes that a complex number so the fundamental point we're driving home here is that numbers are very fundamental and simple data types but they can get very complex very quickly python strips a lot of that complexity out if you're coming from python 2 or another language you're going to note this seems overly simplistic and it is by design python 3 pretty much revamped the number system and did away with a lot of the old headaches so it's super simple general rule of thumb no decimal point use an end decimal point use a float if you need something else use complex and there are others that we will cover in future videos but this should get us going for now okay let's talk about basic numerical operations now don't worry we're not going to get super complex we're talking basics python can do some really complex stuff for example you can do calc trig advanced algebra pretty much any type of math you can imagine python's actually used in scientific computations and it can do things like artificial intelligence we are starting at the basics so we need to talk about the basics i'm going to say x equals 3 which is an integer now i'm going to print this out and i'm going to just grab the old print function here save us just a smidge of time nothing super fancy about that but what we're going to do now is we're going to make another variable let's call it y and we're going to say y is equal to x plus 3. so what have we really done here we've done basic addition let's go ahead and grab this and let's call this add and this is going to be y and that's going to be our fundamental pattern here where we're going to do something and then we're going to just display the results and i'm going to say add that way we know what we're doing save and run and sure enough add is equal to 6 because x is 3 and we're adding 3 3 plus 3 is 6. again fundamentals now we're going to start speeding this up because i think you're probably smart enough to understand basic math and we're just going to grab this and you guessed it start plowing through this so if we can add we can also subtract let's go ahead and say we want to minus one run and you can see three minus one is actually two so that works exactly the way you would expect it to let's go ahead and multiply and we're going to say hmm this is something you really can't do very easily in other languages python makes it just beautifully simple so we're going to say 6.846 doesn't really matter what number we do just as long as we have that now if you look x is an int but what are we doing we're multiplying it by a float so what's going to happen under the hood here is python is going to determine what the n value type actually is is it going to become an integer or is it be gonna be a float you notice how it's not really telling us when we hover over intellisense and that's because the interpreter hasn't done the work yet so it simply doesn't know so let's call this multiply and the end result is 20.538 so that is a floating point number now we're going to do some division let's grab this and we want to say x is going to be divided by 0.5 again it's doing all of that hard number crunching in the background what it's actually doing is called casting and when you think of casting think of like a wizard waving a magic wand converting something from one data type to another that is happening automatically for us we don't have to think about it now it's not always going to happen automatically for us but in this specific case it is and it's super super convenient don't worry we're going to talk about casting in depth in another video right now we're still at the fundamentals and let's uh play around a little bit we're going to make a power of so we're going to say that is the power so three to the power of two is nine and one more just to play around here let's do the remainder i think this is called the modulus operator and we're going to get this you don't know what this is this is kind of like the opposite i shouldn't say the opposite it's kind of like taking division and getting the remainder of what's out of that value it's kind of weird so let's take a look here so 0.5 so what we're doing here is we're starting with x is 3 and we're getting the remainder of 2.5 which is actually 0.5 very simple very easy to use so the fundamental concept we're trying to drive home here is there are some number data types int float and complex and you can do some basic numerical operations python makes those numerical operations very simple because it handles all the complexity under the hood for us and we don't even have to think about it welcome back everyone my name is brian and we're going to talk about strings so what is a string that's a very good question we have before you a simple diagram the word hello h-e-l-l-o and there's some numbers here and some numbers here we're gonna explain all this so really a string is a list of you guessed it characters and each character translates to a numerical value so if you look down at your keyboard and look at like the letter h that letter depending on whether the shift key is pressed will be 104. now when i say depending because there's a numerical difference between lowercase and uppercase we're talking about lowercase here some people will say oh that's ascii i've heard about this before this is actually not ascii it's unicode specifically utf-8 i think it's universal text format 8-bit or version 8 i forget but basically python under the hood sees this as utf-8 so it doesn't matter if you're typing in english or korean or spanish or ancient greek or some mathematical algorithm there is a number assigned to each letter computer knows what that is and takes care of all of this for you so you don't have to worry about it the two major things you should focus on is well the letters themselves that form the string and this down here which is the position everything is in a list so when you look at it h-e-l-l-o there are five letters there and there are five numbers starting with zero this is a zero based index zero one two three four so if i say give me the letter at the third position h e l this guy that is actually number two because it's zero based it gets a little confusing if you're new but you're gonna go now wait a minute that's actually number three remember it starts with zero so the first one's always zero we're thinking in terms of computers zero one two is this guy right here once you wrap your head around that you know more than most people walking around and honestly it's not super hard you just have to understand that everything you see on the screen has some sort of number attached to it the computer handles that number you just need to worry about what letter and what position and we're gonna go into that okay let's flip over into visual studio code here and we're just going to copy and paste some code here and this is going to look like absolutely nothing you've seen before don't worry about it just taking a leap of faith we're going to cover this in a future video but really what we're doing is we're saying 4x each letter in the string hello we're going to print out the letter and its numerical value and you can see 104 101 108 108 111 burn those into memory 104 101 108 108 111 if we flip back it's exactly what i told you it was going to be so let's dive in here and figure out what's going on now again we are going to cover loops in a future video that's not this video we are hyper focused on strings so the first thing we need to do is baby steps how to make a string very very simple simply make a variable and assign it let's do that again notice how the first name or the first variable has double quotes where the last name or the second variable has single quotes in python you can do it either way and they do this not so much to confuse you but simply because there are a bunch of little gotchas that you're going to find later on in your life as a programmer and this is super convenient that you can switch it around however you want so the first thing you're going to want to try is just simply to well merge them into one larger string or print them out so we're going to print i'm going to say first plus and last now what do you think is going to happen here you notice how we're using the plus sign if you're a math nerd you're going to say oh this is going to kick out some weird number actually no it's going to say you guessed it it's going to i think the term is called concatenate them it's going to merge them together into one string in memory so it's saying the first brian with a space and last karen's very very simple you can also do something called formatting which we've done before and it really does help you avoid errors in the long term so you can say something like this print f and notice how i've got quotes doesn't matter if you're doing single or double and i'm going to say hello my name is and then let's see here there we go i had to look at my keyboard to figure out where that was and then we just type the variable name first and then last now we tend to use formatting to avoid issues you've seen me do it already but you probably haven't really realized why and we're going to cover that a little bit here so hello my name is brian kearns to kind of compound that in your mind let's make a variable called hers and we're going to say others notice how i'm mixing and matching these i'm using double quotes so python knows hey this is the string but we can also use single quotes so that gets super confusing what it's going to do is take the first one it sees and says up you're using double quotes to make the string so if i were to change this to a single quote notice how this letter suddenly turned white even if i end it in a single quote it's going to get really really annoyed with me see boop syntax error invalid syntax if you ever see a syntax error really what python's telling you is you screwed something up and it'll tell you exactly where in this file on line 11 and hers and then there's a little arrow right here under s it doesn't know what to do with this because it is not in the string change that and put the double quote there and it magically fixes it see it doesn't make a whole lot of sense so let's change that back this is why you can mix and match these it makes it super super simple and we can just print that out and it works as expected there's our little single quote right there and we don't have to worry about any special encoding or formatting or anything like that okay so to solidify this under the hood a string is a unicode series of characters specifically formatted in utf-8 if you want something other than utf-8 you're going to have to go out and google how to do that i'm just saying we haven't covered it yet we may cover in the future but if you need something immediately definitely go out to google a string is a sequence of one or more characters and those characters are numerical values and that's what we're really going to drive home right now so let's make a variable let's call this s1 and we want this to be a character notice how it's looking for an integer return a unicode string of one character with ordinal and then it gives you some examples there and i'm going to say because i have this baked into memory 72 and then we're gonna make another one and this is character and we're going to say 105. now you don't see it but i'm sitting here cheating a little bit i'm looking at the utf specifications and the character tables which you can see definitely by visiting these links and other links and it will give you the numeric values now this is if you wanted to do something like this you really don't need to i'm just demonstrating it can be done so we're going to say s1 plus s2 and let's kick that out and it spells the word high notice it's a capital h lowercase i 72. now lowercase h is 104. uppercase h is 72. this is what i mean by there's a fundamental difference between upper and lower now you may be inclined to say now what about bold and italic no that's actually not part of it those are not letters those are just simply styling and formatting of what you see on the screen so really all we're talking about is upper and lower case it actually goes way way beyond that you can do something like this say print and i'm gonna say character and i really have to cheat and look at my notes for this one eight seven one zero and this goes way beyond ascii let's go ahead and save and run and see what this looks like boom it's this little mathematical symbol right there that's right it's got math symbols baked right into it you can do some really cool things with just simple characters you may have turned the term escape characters now what is an escape character it's not something out of a novel although it could be but basically instead of memorizing all these weird numbers they have it built right into the language and actually most languages and even operating systems they're called escape characters what it means is you can escape a string and print a special character and let's take a look at how this works here so i'm going to say print and we're going to even format this just to show you how this works i'm going to say hello and then world and notice i've got that kind of jumbled together now you can do something like this you can say okay i looked it up and it's you know character 13 for a hard return plus i want to do like a character 10 for a line feed and that will put this on two different lines and i had to go out and look up these numbers because i didn't memorize them but it does work hello world or you can just simply do something like this and we're going to grab it get rid of all that nonsense slash r for return slash n for line feed save run and it does the exact same thing so under the hood this little guy here slash r notice an escape character starts with a backslash here we're saying slash r for return or n for new line does the exact same thing you'll see that out in the real world both ways where some programmers will demand you use the character and some programmers will demand you use the escape character it gets a little confusing until you get used to it but it's super simple and you can do things like this and really all we're going to do is we're going to print out hello world with a tab between them slash t for tab when in doubt you can go up to google and you can type out what is an escape character and it will give you a complete list of them there's tons and tons of them but they're very simple and easy to work with here's hello world with a tab in between you may be wondering why even use escape characters i mean it seems a little rudimentary now let's go back way back to this problem we want to put that in there and it works fine if we do it in double quotes but the minute we change it to single quotes remember we're going to have some sort of issue it's not going to know to do with x and it's going to say you guessed it invalid syntax well instead of going through and re-changing all our strings we can just simply put slash in front of it and most of the time that will work it'll escape it right out go ahead and save to clear that error out let's actually clear this out just to show you it will work no more syntax error and we can print this bad boy out so escaping actually becomes a very convenient way of well breaking out of the constraint of which quote you should use i know i'm going to get that question constantly of should i use single or double and really it does not matter just pick one and roll with it and if you need to switch them around you can always escape out of them it's not super hard you can also do things like this and this is something i get a lot of questions about not just with python but pretty much every language so i'm going to say quote equal you see what we're doing here you can have multiple escapes it doesn't really matter basically what we're saying here is once you do this slash the computer will try to figure out what you're doing and it will roll with it if it can't figure it out it will give you an error message at which point you're going to have to probably do something like this or you're simply using the wrong escape character and when in doubt go google it it's usually pretty easy to work with here so we're gonna go then he said quote unquote hello to me now you may be wondering what's the deal with formatting when you read books or watch videos on python they would go really in depth into formatting and why it's important really you format to avoid errors especially with strings and let me give you a very simple demonstration here let's say name is brian age is 46 and boy i feel 46 today i was raking leaves all day yesterday so wow yeah that sucks all right so we're going to print these out i'm going to say name plus and we want the age oh this will work and it'll work beautifully right well guess what no it does not there's a reason for it it's not very intelligent when you first look at it so we're going to say line 36 in this module print and it doesn't put the little little arrow but it does tell us must be str not int so what it's really talking about is this thing what you're trying to do is take all of this and treat it like a giant number and then add these together we're trying to do basic numerical operations which we already covered and python's not going to let us do that so let's get that out and let's just put a note here now let's show the correct way of getting around this now there's a few different ways we can do the way we've been doing which is we just put an f in front of the string and then we're saying we're now formatting it not very hard we've done this before but if you want a little bit more control there are other ways of doing it we're not going to dive into every single possible way i'm just showing you the two that i use the most and this is the next one we're just going to print and i want to say let's do double quotes why not my name is and here what we're going to do is we're going to say we want sent s and what we're doing here is we're making our own special custom string with formatting baked right in i am and then i want a percent i or integer from here though now we need to do a percent sign and tell it hey we're going to feed you some values those values are going to be name and age now i typically don't like doing this because you have to read this whole thing skip over to this percent sign and then look at this little guy here and figure out what we're sending it okay so name is the first string okay and then age is the first integer all right so let's run that see what that looks like and it says my name is brian i'm 46 years old let's play around with this let's put i and s just to see if we can easily break this and sure enough we've broken it with very minimal effort type error so really i tend to favor just the simple formatting because we don't have to mess around with any of this or worry about screwing this up but if you need special formatting it is super super simple to put it right in there when in doubt google is your friend and there are honestly thousands and thousands of tutorials on how to really learn that in depth we're not going to spend a lot of time on it though welcome back everyone this is brian we're going to continue our journey on python 3 and we're going to continue with basic string operations now when i said strings are complex data types i was not joking and there's no way we can cover everything in these little two videos especially because we haven't even covered the fundamental logic of programming so we have to stick with the basics for now don't worry later on in this series we are going to revisit some of the more advanced things we can do but right now you have to learn to crawl before you can walk so let's start crawling i'm going to say variable str is going to be hello world this is a string very very simple and we're going to start off with here so what we're going to do in this video is we're going to do things like getting the length of the string repeating the string replacing characters and things of that nature and even slicing them and getting the specific indexes or positions within the string let's dive into the basic operations so first things first let's say we want to get the length i'm going to say print we're going to call the len function which is not limited to just strings but it is super super handy for strings and we are going to just just print out a comment here get the length we run this we can see this is 30 characters long now you might be inclined to say now wait a minute it's a zero based index so it's actually 29 no it actually gets the length not the position that's fundamentally different as you're going to see later on so now that we've got the length we can do other things as well let's say we want to repeat a string and this is going to hurt your brain just a little bit here we've talked about how you cannot do mathematical operations with a string remember we were trying to add an integer and a string together well you can do what's called string math and this is what i mean by it's going to hurt your brain we're going to say str times three now i know what you're thinking you're thinking you're going to get some sort of weird thing because you're trying to multiply but actually what you're telling python to do is take the string and you guessed it multiply it by three and return a giant string let's demonstrate hello world hello world hello world so it did exactly what we thought it would do here yes the first time i did that i kind of sat back in my chair and went wait what is that right but it is actually a thing with python if you're coming from another language you're probably sitting there just staring at your screen going what witchcraft is this but it's actually super handy if you need to repeat a string now let's go ahead and let's look at replacing and if you're coming from another language well this is exactly what you think it is it's just dead simple so in python strings are a data type but they're also a first class object meaning they have functions built right into them we haven't really covered functions yet but just know you can say your variable name dot and then call some code and we're going to call the replace function and what this is going to do it's going to take the string and replace a section of it so let's say i want to replace hello with um hola so if you're from mexico or spain or any spanish-speaking country that would be the correct way of saying hello i'm probably mispronouncing that but you get the point you can simply replace it so hola world this is a string makes it super simple to do that you don't have to figure out where things are you can also do something like split a string so if you're coming again from another language you've done this before and i'm going to say sdr i want to split and notice how it's looking for a separator here so let's go ahead and split this on that comma if you're not coming from another language you're like wait wait wait slow down what is splitting so we're going to take this string and turn it into two strings and we're looking for a separator value in this case this comma right here so it's going to say hello world and then this is a string and it's going to give us two strings back here we go hello world and this is a string now you may be going now wait a minute this commas here look at these little brackets you got this in bracket this beginning bracket what it's done is it's created a data type we haven't talked about yet but we will in the next few videos and it's put two strings into that data type and then handed it to us very convenient way of saying hey split those up as you go on programming you're going to actually use that quite a bit now let's say we want to know if this starts with something so i'm going to say str and i want to say starts with does it start with the letter h i'm almost embarrassed to type that comment starts with because it's pretty self-explanatory what it's doing but just in case it's going to return a bool and it's going to tell us hey yes it does if we switch this to like j does it start with the j alts very simple handy way of determining what's going on we can through the magic copy and paste switch this to ends with and let's say we want to make sure this ends with an exclamation true true there we go and let's go ahead and look at uppercase lowercase and capitalization we're just going to say print and we want upper it's going to give us hello world this is string all in upper case you notice how it's got these brackets here and that's because it is a function if we omit those we're going to get a built in upper of string object and then this number you ever see something like this basically what you're trying to do is call a function without with brackets you need those you're wondering what this number is that's a location in memory so an object is simply something that exists in memory and that's its location so admittedly this message is not super helpful for beginners but i just wanted to explain what that was gonna round this out let's say lower and i want to capitalize so now we have all uppercase all lowercase and capitalized the way it should be let's take a look at slicing and when i first heard this term i actually had like this vision of whipping out a lightsaber and slicing something in half and it's actually not far off from what we're talking about we're talking about getting a sub string now when i say a substring remember this string is just a series of characters and each one is at a position so the zero would be here and then one and so on and so on and so on and so on so what we want to do is get a sub string or a slice think of it like you have a pie in front of you and you're going to get a slice of pie you're not taking the whole thing just apart so for example i can say i want the word world or i want just th out of the word this or this specific space or i wanted to get everything in the end up to that point you can do things like that very very rapidly in python and this if you're coming from another language i'm going to tell you is extremely cool once you wrap your head around it so we're going to say print and we're going to take our variable now we're going to put those brackets there that indicates we're getting a slice the format here is very simple we want the start a colon and an end position so the start position in this case we're going to say the zero or the starting position and we're going to end in five and what this is going to do is it's going to get the first five this is a zero based index let's print this out and see what happens here one two three four five hello is five letters there we go so it did exactly what we're trying to do here like i said it looks a little confusing at first but once you start wrapping your head around it it's not super hard now i want to start at the sixth position and i'm going to omit the ending and what we're doing here is we're saying we want to get from the sixth position all the way to the end so when you omit something it automatically defaults to the beginning or the end depending on which one you emit so the sixth position would be you guessed it world all the way over here ta-da works as expected let's go ahead and grab this and let's try something a little bit different we're going to start at negative seven now you may be going wait what negative how can we have a negative seven well when you have a negative you actually start from the end so because we're starting with a negative it's going to start back here and count backwards actually pretty cool how that works so let's run this and the last 7 is string exclamation pretty pretty cool um try doing that with some other languages and some are going to be very cool some are just going to completely infuriate you depending on the language and now let's get a substring we're going to say from 6 to 11 and we want to get 6 to 11 just for our notes here see what that looks like and it is the world world very cool very simple very easy now if you're coming from another language you're probably still stuck on this right here don't worry whenever you see that negative symbol just think you're starting from the end and working backwards now slicing is cool and all but it's not super helpful unless you can actually automate the way of getting the number because no one wants to sit here and count things right so let's look at how to get the index or the position of something what i'm going to do is i'm going to say l equals and we're going to look for the comma now if we look at our original string we've got this comma right here but we don't know the position it's at so i'm going to hide that off the screen and we just want to know hey we want to look for this we're going to do it two different ways we're going to say c equals sdr bind this is what i love about python it's very very intuitive fine does exactly what you think it would it finds something that's going to tell us what we're looking for is the l it's going to tell us where it's at or if it doesn't find it let's say negative one if not bound let's go ahead and say print and i want to say fine return see let's run this see what it does so whoops actually misspelled fine there easy fix so find return c so it is at the 11th position we didn't have to sit here and go one two three four and we'd be here all day doing that instead we want the computer to do the work for us so we know this at the 11th position now if we change this to just something let's just do a single t you see find return negative one so in this case when you see negative one you can say it's just simply not there it's not going to return a zero because remember zero is the starting position so find is really really cool but if you're coming from another language you're probably looking for index of which is something totally different so i'm gonna say i equal sdr index we're going to give it the same thing the l and now we want to this and we're going to say find return i and let's see what this does now remember we have this t in here where is t in here it's well right there but it's a lowercase not an uppercase so it should return a negative one or will it actually no it does not instead it gives you what's called a value error substring not found this is a convenient way of saying hey that must exist or throw an error something we're going to cover in future videos just know that find will not return an error an index will return an error so most of the time you're going to want find but if you're coming from another language you think you want index and you really want find super confusing sometimes fill row and air just want to make sure we put that in there just in case and let's switch this back you can see they both return 11 because we're looking for that comma remember index will throw an error fine we'll just simply return a negative one wrapping this up let's go ahead and say we want to create a new string from the substring how do we do that so we want to say x equals sdr and we're going to slice that string we're going to omit the starting position because we want to go from the beginning and we only want to go to the position of this comma if that seems super confusing let's slow way down so we have a string and it says hello world comma this is a string exclamation so we're looking for this guy right here which we found at the 11th position and we're saying okay so from the very start hello world actually just going to copy this whole thing right down here copy this put it right here as a comment there we go so we're going to say so from the very beginning right here all the way up to the position we find we want to create a string and call it x now we want to take that and just simply print it out hello world super super simple so quick recap strings are first class objects in python they are unicode by default they are utf-8 although you can specify some other way of doing it google's your friend if you need to do that immediately and you can do some really cool things like get the length repeat it replace it split it make sure it starts with ends with upper lower capitalization you can slice it dice it do whatever you want to do and you can search for or find things within the string and if you need to throw an error if it doesn't exist you can use index which i do not recommend because it's not really a good idea to throw an error in your code most of the time and you can create your own strings from sub strings very simply very easily welcome back everyone my name is brian and in this video we're going to cover lists a list is a complex data type compared to what we've been talking about it's very complex so far we've covered bulls numbers and strings but the list is well vastly more complex as we're about to see so first off what is a list well it's an ordered list or collection of data what do i mean by that imagine we add an item that item is going to be at position zero meaning the first item you add is always zero and as we add items you guessed it that index will increment let's go ahead and add an item here so zero one 2 and these items they can be the same they can be different they can be something totally crazy whatever we want to do this is the beauty of python so the list doesn't have to be what's called typed meaning you don't have to have the same data type that's how a lot of lists work in a lot of different programming languages you can intermix strings with numbers and custom data types the main takeaway before we dive in here is that this is an ordered zero-based index meaning it will be added in the order you add them and the first item is always zero from zero it goes to one and two and so on and so on okay let's go ahead and create a list first thing you'll notice in our notes here is i have these square brackets right here what that denotes is that it is a list it's important that you remember that because we're going to talk about other data types that are very similar to a list but they are different and they use a different style so first things first let's create our list remember the square brackets i'm going to say x equals square brackets and anything we put inside these square brackets becomes part of the list for example i'm going to say brian and we're going to add another item by i've seen comma and then whatever we want to put in here so we have two strings in there now really hurts your brain if you're coming from another language i'm going to add a number that's right this is not a typed list you might be used to something like c plus plus where well you have to have a specific type it can only have strings or only have numbers python is not like that at all it makes it very flexible very easy so let's go ahead and put a note in here we can mix data types and let's go ahead and print this out and i want to say list gonna print our list out little copy and paste let's put this down here and let's get the length so you can see right off the bat our list is this right here and it's inside those square brackets always remember square brackets are lists and we can have two strings and a number we can add whatever we want and there are three items in there if you're coming from another language this may actually hurt your brain because you're gonna go wait a minute you can't have multiple types but with python you can it makes it super convenient super easy to create your own data structures on the fly let's make a special note here about indexing and positioning so this really confuses a lot of people we think like well humans the first item is always one well computers don't think that way the first item is always zero because you're starting with nothing so when we talk about lists this is zero based let's go ahead and let's grab our friend print here and let's say we want zero so to grab the first item in that list simply say square brackets and the index now note we are not creating a list we're saying inside of that list get that index in this case it's the zero or the first item i'm going to put that in all caps for you newbies out there the first item is zero remember humans think the first item is one computers think the first item is zero because you're starting with nothing now if you watch the previous video on strings and i hope you did you understand what slicing is but just in case you skipped it a slice is a lot like making a slice of bread you have a nice big loaf of bread in front of you and you don't want the whole loaf you just want a slice of it or a slice of pie is probably a better example so we're going to print this out and we're going to slice this so i'm going to say i want x and then we're going to you guessed it now notice those are square brackets as well we didn't cover this in the last video but yes when you see that square bracket that means we want a piece of this list or in this case a slice of it i'm just gonna put some quotes here there's some quotes some comments slice the list so what this is going to do is it's going to say x and we have a starting position and an ending position we're going to go from the first to the second now remember the first is not the first item it's position 1. remember that gets super confusing as far as zero based indexes to illustrate that one to two position is actually karen's so what we're doing is we're taking this list here ta-da and we're saying 0 1 to two so it's going to stop if we omit the second position we're gonna get the remainder of this we're gonna say we want that whole slice right there so let's demonstrate that tada works as expected slicing is a very convenient way of getting a sub item you may be thinking lists are great but now that i've created the list how do i add items to it that's a common question so that's what we're going to cover in this little section here is how to add the items you can either append or insert and both of them do well exactly what they sound like they do for example x append we are going to say a pen pizza let's go ahead and x dot append i'm doing this twice for a reason and you'll see why here in just a second and add beer because everybody likes pizza and beer right now we want to insert so append will put things at the end in the order you put them notice we did two of pads pizza and beer so it's going to add pizza then it's going to add beer and it's going to do both of those at the end now insert allows you to say i want to put this at a specific position so because we're talking about a specific i need to give it a number and in this case one you notice it wants an index an integer of where you're going to put this in the list so i'm simply going to say 1 and let's add cats so following along what we're doing here is we're adding pizza to the end of this list then we're adding beer then we're going to go to the one position not the beginning the beginning would be zero remember we're going to go to the one position and add cats let's go ahead and add a few notes here that way anybody who downloads this code off github will just have the notes and be able to easily follow along now let's go ahead and do a print and i want to see this list in its entirety and let's see what this looks like okay down here you can see we have our list and we have brian and then cats got inserted in the first position and then my name karen's 46 and then it did pizza and beer very important you understand that a pens will do it in the order you append it so it put pizza at the end of the list then it put beer at the end of the list very simple once you wrap your head around that just trips up a lot of newbies just bear that in mind when you're adding things if you want a specific index you need to do insert if you want to slap it at the end you do append okay now that we've added items let's talk about how we get rid of items we're talking about removing let's remove pop and delete and these do things very differently even though at first glance they may seem very very similar so i'm going to say x dot remove and i want to remove cats i'm not a big fan of removing cats because i happen to love cats but you know what i mean we sometimes you just got to get the cats out so what remove is going to do is go through and remove the first item here let's grab our print statement slap that down here and let's run this all right so you can see brian cats kerins now it's brian kerins we've removed cats so just remove that first item there now let's talk about pop now don't get excited pop is not like coke or pepsi or anything like that but what we want to do is we want to remove an item but at the same time return it meaning we want to be able to work with it here so i'm going to say i equals and we're going to do x dot index because we want to find something here we want to find pizza now this will raise an error if it's not found in there so if you just look for something crazy it's not going to return negative one and there really isn't a find remember we talked about fine in the last video where it returned a negative one this is just gonna say hey there's an error and it's gonna crash your program that sounds really bad until we get into more advanced discussions where we talk about how to get around that and why it even exists in the first place so just big leap of faith at the moment we know that peace is in there because we appended it we're going to get that index because nobody wants to sit here and count and figure out what position this is actually at we're going to say food and we're going to pop now when you think pop think of it like popping the top off of an ice cold soda or beer whatever your favorite beverage is you now have that cap in your hand after you've popped it off that's at least how i learn pop so when you pop off the cap you still have that cap in this case it is the item at index of whatever pizza's at sounds super confusing it really really does but it's really simple once you see it in action so what we're going to do here is i'm going to clear this list just to avoid any confusion and we're going to run this boom so what's going on here we have our list and see there's pizza in there and we're going to pop meaning we're going to pop the cap off that thing that's in our hand and we now have that bottle cap and that bottle cap is pizza so we can now use that but once we've popped it it's no longer in the list see how it removed it very convenient if you want to remove the item but at the same time use the item seems a little confusing but bear with me that is actually used quite a bit when you get in a little bit more advanced programming all right next up we're going to talk about deleting so i want to say i equals say x index and let's get the index of beer because again no one wants to sit here and go zero one two three no one wants to do that we just want the computer to figure out where it's actually at for us so once we get that index and i should put a special note here this will raise an error if not found but once we get that we want to actually just delete it so i'm going to say d e l x and then whatever that position was now this will delete the item without returning it and i'm going to copy and paste some notes in here so delete a specific item without returning it where pop will remove and return the item fundamental difference there which one would you use and why well pop is if you want to actually use it delete is if you want it gone now when you delete this it's gone you cannot use it it doesn't even exist in memory anymore and that's why it's called delete because you're literally deleting that out of memory if you're coming from like c or c plus plus or any other language that does memory management yes you are actually deleting that out of memory now under the hood what's really happening is python's flagging that for garbage collection and all this other fancy stuff that newbies don't really understand but if you're more of an advanced person that's what's going on is python's saying get rid of it out of the python internal list we're just going to let garbage collection wipe it out later on save run this is what's going on here so we found the index of beer and we deleted it pretty cool pretty easy to understand so major takeaway from removing items if remove will remove the first one pop will remove it but let you play with it you can do whatever you want and delete will well actually delete it and get rid of it let's talk about extending or adding elements from another list and this will be a little bit confusing but bear with me here so there's a reason why you would extend rather than just add a list and it's because python you can actually add lists into lists which we're going to cover at the very end of this video but it gets super confusing so let's look at this so we're going to say we're going to make another list and let's call this cats comma dogs comma birds and in case somebody out there is like well how would you actually add a comma you wouldn't add a comma directly at it as string like that but we're just going to add in cats dogs and birds into our list called y now the list we've been working with is called x so we want to take the contents of y and put it inside of x so we're going to say x dot extend sometimes intellisense helps us out sometimes it doesn't and we're going to extend with the y list let's go ahead and print this out notice we're printing x what do you think pop quiz what do you think this is going to look like when we run this well if you said it's going to have the contents of both lists you're absolutely correct now notice how what it's done is it's taken our x and added the elements of y to it so these are now true items inside of x very cool how that works so let's talk about sorting and when i say sorting we mean sorting and reverse sorting meaning doing the exact opposite of like an alphabetical so let's go ahead and say sort and reverse now think of this as like sort ascending sort descending now our list is a mixture right now and what do i mean by a mixture so if we just take this print this out run it you can see how we got string string int string string string we're going to have problems with this integer we're going to have to take that out and i'll demonstrate this really really quickly so i'm going to say x dot sort and this is where a lot of newbies get tripped up and it goes not supported between instances of end and string and it's exactly that so it's saying it knows how to sort strings and it knows how to sort numbers but it doesn't know how to sort the string to a number so think about that let's say you have a table in front of you and i come in and i dump a bunch of potatoes and a bunch of apples and i say sort these well how do you want them sorted do you want the potatoes and the apples sorted or do you want them sorted by color but they're all different colors and this is what i mean python gets really confused and it just says you know what i'm not even going to try and figure this out i'm just going to drop an error let you just figure it out on your own the easiest way to get rid of this at this point is to simply remove it so i'm going to say x dot remove we're going to just remove that int and then we're going to sort so now it's alphabetical because we've removed that it knows exactly how to sort these strings birds brine karen's cats dogs very very simple the polar opposite of course is reverse and we're just going to grab this for the sake of time pretty self-explanatory what's going on there this would be like sort ascending sort descending i almost wish they didn't call it reverse but called it like sort descend or something like that or you know had a parameter inside of sort and we'll talk about parameters later on but it can be a little bit confusing but just think of sort as you're going to sort alphabetical and reverse is the polar opposite of that you notice how when we sorted we had to remove that hint simply because sort will throw some sort of error if there's a mixed type now what if you wanted to do that but you didn't want to really modify the original list well what we're going to do now is called a copy and some people call this cloning widths is a very shallow clone but basically we're just making a copy here so i'm going to say y equals x dot copy does exactly what you think it does it actually makes a new list and copies the elements into it so we're going to say copies the elements into a new list now we can simply say y dot reverse and we could add items remove items do whatever we wanted to do so i could say well i got append let's go ahead and append apples we could do any other thing we really wanted to do here so let's grab this print statement here so x is the original new is our y let's see what these look like here so our original remains unchanged where our new now has apples and it's been reversed pretty cool the way that works and then if you were done with wine you didn't want any more you just simply delete it which is what we're going to talk about next okay so deleting delete the whole thing is really what i'm going to put here why would you want to delete something well in the previous little segment here we said we're going to make y and y is a copy of x now that we're done with y we don't need it anymore we can do one of two things we can either let python garbage collect it meaning it's going to figure out when it's not needed anymore or we can specifically say delete the whole list and yes that deletes the whole thing so if i try to say something like print y it's going to have a bad time here and it's going to say name y is not defined and you remember from a previous video whenever you see is not defined it means it simply does not exist meaning we have now destroyed y and everything in it has been destroyed as well so all that memory for you computer nerds out there is now freed up and gone we can use it for other things this really becomes important when you start talking about embedded systems and things of that nature where memory might be a little bit more constrained than say your desktop or your laptop you got to understand that when you delete something it is gone and i mean gone gone is not defined means you would have to rebuild this entire data structure from scratch there's simply no way to recover it the leading can be a little bit drastic as we saw name y is not defined is well kind of a problem i mean what if you didn't want to delete the entire variable you just want to delete part of it or clear the whole thing off that's what we're going to talk about in this little segment here so we're talking about clearing think of your list like a big table and you've got plates and dishes and all sorts of stuff on there you don't want to throw the whole table out you just want to clear it off and that's exactly what clear does so it's going to clear all of those elements out of the list but the list itself will still exist it will just be blank and demonstrate that let's type cleared so most of the time in programming land you don't actually want to delete you just want to clear it out so our list exists you can see by these brackets there's just no elements in there and we can actually test that let's go ahead and get the length of x so it exists but there's no items in there most of the time if you're confused just think of it this way delete is throwing the entire thing out you're throwing the whole kitchen table out where clear is you're just clearing the dishes off the table usually you want clear not delete but delete exists in case you need to free up that memory you want to do something a little crazy a list can contain other lists and if you look at this it looks kind of weird but just think you have a start bracket and an in bracket followed by start and end start end and start and end so that's right a list can contain other lists if you're coming from another language think of this like an array of arrays it's kind of advanced and it's not something a newbie really understands but in case you're curious this is how you would do it so we're going to say x equals and we're going to turn x into a blank list with nothing in it y equals we're going to create another list we're going to say 1 2 3 and let's go ahead and make another list called z and in here i'm going to say my name you go ahead and put your name or cats dogs birds whatever you want to put in there so now we have three different lists what we want to do is we want to take the contents of z and y and put them in x so i'm going to say x dot append let's go ahead and append y now what i've done is i've taken all of these numbers and put them inside of x let's go ahead and print this out now i'm saying merge but that's not really what we're doing here we're actually merging all these into one giant data structure you notice how we've got these double brackets here so what we're saying is this item this individual element is its own unique list so i'm going to say lis enlist all right now what we want to do is we want to take the contents of z and put them in x but we want to put them before all the other stuff that we put in there say x insert and let's go ahead and put this at the zero index and we're going to put all of z in there let's go ahead and run this and you see now our list actually is made up of two smaller lists newbies may look at this and go well there's five items in here there's really not let's go ahead and test this out here so we're going to say grab this and let's call this our list and let's go lynn and we're gonna get the number of items in here there's only two items in there very simple very easy to understand now let's say we want to grab the first item we want to say zero and we want to go zero let's go ahead and grab that second item so our first item is this list here which is its own little list and second item is this list here and in case you're wondering yes you can get kind of nuts here what we're doing now is we're diving into those lists so in our first list right here we're gonna grab the first item which is brian in our second list we're gonna grab the second item notice that's at the one position which is two seems super confusing but just think of it this way think of it like a stair step every time you see these brackets you're going deeper down a step into the basement so for example we could switch this around here and we can grab the very first item which was one we could switch this around again and say we want the second item which is three seems super confusing if you're a newbie but trust me once you get into more advanced stuff this is a huge huge time saver is just simply putting lists and lists and when you start working with things like web services you're going to find that quite a bit where the data they're going to hand you is basically a list of lists and you just simply have to navigate through it okay a little bit of bonus material here i know i'm going to get the question so i thought i would just add it how do you change an item remember it's positional so for example let's say x equals and let's just make some numbers here one two three four five we want to actually change this when i say change this we don't want to change the whole list just one specific item so what i'm going to do is i'm going to say x and then whatever the item number is so let's say i want to change the item at position 2. and we want to change this to the word test remember this is zero based and this trips up a lot of newbies so we have zero one two so this guy right here we're gonna change that let's go ahead and print this out and let's see it in action there we go zero one two our two position is now test four five so that is very simple how you change something a lot of people especially me take this for granted because it's so simple and easy to work with and if you've worked with other languages you may be looking for like a change element ad or swap element or something like that it's actually very simple you take the list you take the position and then you assign it a value welcome back everyone my name is brian and in this video we're going to talk about the set now the set is a little bit different than the list we spent 30 plus minutes in the last video deep diving into the list if you haven't watched that video i highly encourage you to go back and watch it because we really do dive into the list set however is slightly different that difference though means it is profoundly different under the hood let's take a look at this so a set contains unordered unique and immutable data types in a hash table let's break that down what does that really mean unordered meaning we cannot control the order like in a list you could add or insert meaning we can now control the order can't do that with a set the set determines the order unique meaning you cannot have multiple so if you try to add two cats or two dogs it's just not going to do it and immutable data types what does that mean means that once we add them we cannot change them we can only remove them or add them we cannot change individual items and it's in a hash table hash table well that gets a little bit complex in the computer theory but really when you hear the term hash table think blistering fast read access the set determines the order so that it knows exactly where things are in memory and it makes it very fast so if you want very very quick lookups a set is what you need now that we understand what a set is let's go ahead and let's create one so first things first we'll say s equals and then we want these little curly brackets remember if you do the square brackets that's a list completely different data type you want the curly brackets and in here i'm going to just say one one number two come two come two comma three four and five you may be going now wait a minute i thought it had to be unique well this is one thing i absolutely love about python it automatically strips all that out for you so you don't have to worry about it see one two three four five even though we tried adding multiple twos in here it's smart enough to realize it already exists and says nope can't do it and it doesn't raise an error or anything like that so we don't have to worry about it exploding on us here we can also in case you're wondering convert a list into a set and let's show how to do that let's say here's our list and i'm just going to have my name and my age and now we're going to say s equals and we're going to use the set function and what this does is take any sort of editable data type like the list which we've talked about and convert that does it automatically we don't even have to think about it i'm gonna grab this now notice the order i did brian karen's 46 and in a list it's going to be exactly the way we put it however in the set it's actually 46 brian carrots so the set is now determining the position that's one thing you need to really really drive into your brain about a set is the set is unordered unique and as we're going to see later on immutable data types okay let's see how we would add items to a set it's actually very very simple so i'm going to say s dot add and you can add pretty much any element type you want i'm just going to add the word hello there is another way though and it's called update and it looks a little bit challenging when we look at this it says star s colon iterable t none what does all this mean well when you see this term right here basically we're talking about something like a list i shouldn't say a list but like a list something that you can go through or navigate through like a list or a set or a tuple which we haven't talked about yet you just need some sort of data container that contains multiple items that you can iterate through so in this case we're going to say we want to do this in a list say 123 and i'm going to go ahead and add in hello notice i've got hello twice but we're working with a set which is unique items so what's going to happen under the hood if you're going to guess that the set is going to automatically strip out the second hello you'd be absolutely correct let's see it in action see 123 46 karen's hello brian again unordered and unique items only now that we've added items let's look at how we would go ahead and remove items and it's just as simple s discard and discard does well exactly what you think it would it just takes it and throws it right in the trash however there's a subtle difference between discard and remove pop quiz does anybody know what the difference really is here well one will throw an error and one will not so this guard will not grow in air where removed will throw an error and what do we mean by that if we run it in its current form everything is well just going to work let's go ahead and modify this a little bit and demonstrate this error so in our set we have one two three karen's 46 brian and hello let's go ahead and say some number that we know is not in there 78. run this and uh oh we have a key error 78 which means it knows 78 is not in there in future videos we're going to talk about how to get around that you're going to use the keyword in to determine whether or not it's actually in there but just for our beginner's perspective discard will not throw an error and remove will be very mindful of that as you're moving forward another thing we can really do here is we can pop now top for a set really isn't abundantly useful i'm just going to say it you may be inclined to say hey i want to get like the first item or the second item or the last that you can't do that it's just going to return an arbitrary item you don't control what item it gives you it's just going to give you an item that gets a little frustrating but if you're just using the set as a container and you want to just get each item and remove it pop is actually pretty useful but this is going to be pretty random as far as you're concerned and you're going to have zero control over it now that you've popped it you could do whatever you wanted with b because it still exists in memory however it's no longer in our set one question i'm often asked especially by newbies is well i have a set i want to modify it well unfortunately you can't not only can you not modify it you can't access items based on their index because the set has no concept of this let's go ahead and demonstrate so i'm going to say s and 0 and we're going to change this a go ahead and run this see what happens and object does not support item assignment oh that is super frustrating this is actually by design once you put it in the set it will not change because under the hood it's a hash table it's making a mathematical computation to determine where in memory it needs to go so we can do a fast lookup okay not a huge super deal but i just want to print one item out let's just try to print that first item out and see what happens here uh-oh set object does not support indexing oh my goodness that is so frustrating you may be thinking well this is stupid why even use this let's just use a list and get it over with well you can however a set is designed for a specific reason that is fast lookup think of a set like you would have settings like for example all of your computer settings there's probably thousands and thousands of computer settings if you put that in a list it's going to be hard to really navigate so you would use something like a loop or use the keyword in things that we haven't covered yet and we will cover in future videos but what we're going to talk about is some down and dirty ways you can modify a set so for example let's say um let's run our our code here and see what we got so we've got 346 cairns and brian let's go ahead and say 3 and s let's go ahead and print this out just to see this is in there true so we know that 3 is in s let's go ahead and say s dot remove and we want to remove that 3. now we want to go ahead and turn around and add well so basically what we're doing is we're saying take this set remove this three and change it to a 12. unfortunately we cannot control where it's going to put it in the set let's go ahead and print that out probably a little more helpful there we go so now it's 12 46 karen's a brian honestly dumb luck that it's in the same position don't count on that because the set is unordered now we can do some crazy things here and this is going to really hurt your brain so let's go x equals and we're going to make a set and let's say a b c d and i'm quite literally just restyling this so expect me to make some typing errors here and we're going to say c d e f g so we've got two sets now we want to do some mathematical computations on these and this is kind of the standard way of doing any sort of set modification we're going to do what's called a union so i'm going to say s equals and we want x dot union y and what this is going to do is it's going to and i'm going to see if i got some notes off the screen here all the elements that are in either set and i'm going to a little print statement here so our union is now all the elements that are in either set very rapid modification of that set you don't have to go and remove and add remove and add and check and see if it's in there i'll just grab this whole thing and let's go ahead and do an intersection now an intersection is a little bit different it's going to get all the elements that are in both sets and demonstrate that and what's in both is d and c see pretty simple pretty easy to wrap your head around now let's get a little bit crazy here so we're gonna grab this and we want the difference you ever have somebody say that to you let's you know split the difference so the difference are all the elements that are in x but not in y which in this case is b and a and one more that we're going to cover here and this is the maybe if i get my mouse to work the symmetric difference now this is going to be a little bit different than what you're thinking so this is all the elements that are in one of the sets what does that mean exactly save and run all of the elements that are in one of the sets so it's going to take both of them and basically make a third set in memory and say okay make sure what we're giving back is a unique order of items that exists in at least one of the sets that we've given it and it gets way more complex than that but that's basically what's going on under the hood you can see we have f e b a g so the main takeaway from here is all the way up at the top sets contain unordered unique immutable data types in a blistering fast hash table what is the fundamental difference between a set and a list well the set is well a little bit more challenging to work with and you cannot modify it as easily as you can with the list but it is much much faster which you're really not going to understand how fast that is until you get into more advanced programming right now we're learning the fundamental data types and we just covered the set in depth welcome back everyone this is brian let's continue our journey into python 3 with the tuple kind of a funny name but this is really really cool so a tuple is a fast list that cannot be modified it's read-only once you create it you can make zero changes to it this thing exists solely to exchange data and it's typically used between classes between objects between frameworks and between devices for example let's say somebody made a package that was going to give you the cpu and ram and hardware and all this cool information about your device they don't want you to be able to modify that so it may seem kind of plain and boring on the surface but you can do some really cool tricks as we're about to see first thing we're going to do is create a tuple go ahead and make a variable name t and let's give this an assignment notice how it's got these little curved brackets here when you see these curve brackets think of it like a shield defending it because it's read-only you cannot change this we're just going to give it some information we don't really care what we put in there because we're just testing it out say print and t you guessed it it's got these curved brackets and that is what denotes it's a tuple the major takeaway here is the different style bracket denotes what it's going to be whether it's a tuple a set or a list or a dictionary which we haven't covered yet now that we have a tuple let's look at how to access the elements inside of that tuple it's dead simple we've done this before let's go ahead and say print f and we're going to access via the index give it our index position remember this is a zero based index so zero is actually the first position and then one two and so on and so on run works exactly the way you would expect it to let's go ahead and do a slice because slicing is pretty easy and fun and we're going to grab this and say i want to go from two to the end of the couple there works as expected and clear this out and let's look at a bull operation what we want to do now is we want to look for something specific inside of that tuple i want to say is 3 in t what this is going to do is tell python hey take this value and inside of this tuple and it could be a list or a set or a dictionary we haven't covered dictionaries yet and it's going to search and see if it's actually in there that's a returnable saying yes or no in this case true because 3 is right there this is extremely easy to work with and it's blistering fast okay bonus material let's talk about assignment when i say assignment what are we really talking about i mean tuples are kind of boring you create them and you can access elements other than that you're done well you can do some really cool things not just with tuples with lists and sets but tuples make it really simple to understand so we're going to make a tuple and we're going to put some variables these are not values these are variables remember a variable's something that'll change x comma y comma z now i'm going to make another double and we're going to give it values one two three what are we doing here what we're saying take these variables and give them these values and python under the hood is going to figure out which one needs to be which go and print x let's print y and let's go ahead and print z see this in action one two three beautiful now let's talk about the range function and this is something a lot of people don't really talk about too much you just see it and you expect that it'll just magically work so let's grab this there we go so we've got xyz and we're going to get rid of this right here and we're going to say we want python to do all that work we don't want to say and type out values all day long so i'm going to say range and let's give it a one see what happens here you're expecting an error you got an error not enough values to unpack expected three got one well let's just test this theory and say we want six we're gonna give it more than it needs and of course another error too many values to unpack expected three so it's telling you i demand three where's it getting three from right here under the hood python is making a tuple of variables and we can assign to those variables using the range function now range itself is not returning a tuple we can test this out by just simply grabbing this and print this out we're going to actually print range three notice how we got zero one two so there is our range but then we're printing range three and it's saying range zero to three so what we're really expanding upon here is that the range itself is telling python go through a loop something we're going to talk about in a future video but you have a start and an end we haven't really given it a starting end we just said hey make three values it's going to start at zero go three times what if we don't wanna start at zero we wanna start at one well we give it a start and now we have to give it an end position here four y four because we need a starting position plus a length of how many we need to unpack which is four one plus three equals four now it just works exactly the way you think it would hello again everyone this is brian and in this video we're going to cover the dictionary in python 3. so what is a dictionary it's a key value pair more appropriately it is a list that's indexed by keys if you want to be really specific you notice the brackets this is actually a set index by keys which can be any immutable type what does that mean any immutable type means unchangeable so let's take a look and let's see what it takes to create and work with a dictionary let's take a look and see what it really takes to create a dictionary we're going to do this two different ways we're going to do it the hard way and the easy way first let's do it the hard way i'm going to say b equals we've got our brackets we need a key value pair so let's create the key he is going to be the string pet colon and now we need a value let's say dog that's it that's really all there is to it now if we want to make another one we just separate it by a comma now we need a key let's call this age value is going to be five let's go ahead and make another one let's call it name and its value is going to be spot i'm always bad at picking pet names and print out the dictionary in all of its glory there it is pat to dog h5 name spot now let's do it the easy way i'm going to say d equals and we're going to call the dict function funny name say that real loud in class and watch everybody just kind of look at you but uh we're going to say pet equals dog age equals five and name equals spot so what's really going on here is it's doing all this formatting for you that's why i call it the easy way the end result however is exactly the same they are exactly the same doesn't matter which way you create it just under the hood know that you have to have a key value pair for example pat dog h5 name spot let's take a look at the keys and values and how we get at them there's a third type really and it's called items we're going to work with that one first so we'll say print and we'll go f items and we're going to call the dictionary items function save run and this is going to return a dict underscore items which you guessed it look at this thing this is insane so we have a tuple containing a list containing tuples but what it's really done is it's packaged it into individual items so you can very distinctly see the key value pairs not abundantly useful for us what we really worry about are well the keys and the items so let's go ahead and look at those real quick i'm going to just say keys and values i say items earlier i did all right so we want to look at the keys and the values save and run and voila so we're returning three different things dick underscore items stick underscore keys dick underscore values but what we've got is all of the information in this dictionary right here in these three functions see items returns pretty much everything nice and packaged the keys is going to tell us what keys are available because remember everything's a key value pair so when we go to look something up we can't do it by index we have to do it by key which is why these keys exist you could easily make these keys integers or numbers of some kind but we've done it as a string we can also get the values dog 5 and spot which are abundantly unuseful without the keys so in the next section here we're going to take a look at how you would actually get those let's go ahead and take a look at how we would get a value from a key because these are key value pairs it's called the key because it unlocks the door to the value and let's take a look at what i mean here so i want to format this and i'm going to say name let's capitalize that and we're going to say d and you inclined to do something like this d zero let's run this in key error what does that mean key error it means the key was simply not found we don't have a key named zero we do however have a key named name we also have one called pad and age so you have to use the key to get the value let's demonstrate that name a spot now you notice how i have different quotes i have single quote and double quote there is a very interesting little issue here where if we do a single quote within a single quote bad things happen very quickly we get an invalid syntax you're looking at this going now wait a minute it should treat everything in these brackets as a separate entity but it really doesn't so you do have a quote issue that we've talked about in a previous video all right so now that we've wrapped our head around that let's take a look at the key error in depth and let's call this test and let's just say blah some key we know doesn't exist really what's going on here is it's going out and it's trying to find any key of that value if it doesn't find it it throws a key error at the very end of this we're going to show you a little trick using some simple logic which we haven't covered yet to get around that to determine if the key even exists in the first place but just right now know that you have to have the key otherwise it will throw an error so just put a quick note there we'll throw an error if the key is not found let's go ahead and take a look at how hard is it to add an item to a dictionary well it's not it's ridiculously simple you just simply do something like this there you go it's that simple you just simply say dictionary and then some key that's not in use equals a value and it will add it automatically it's very cool how it does that now you should note and we're just going to copy and paste this what happens if the key already exists so here we're adding and here what's going to happen let's run and find out it's just simply changed it this is what i mean by the key is immutable we cannot change this key we could delete it and re-add it but once that key is in there all we can do is update the value or delete it the key itself cannot change and let's take a look at what it takes to remove an item our good old buddy the delete statement so we're going to delete you guessed it the trick now this is what i mean by this is a key value pair when we run this and we delete a key the value associated with that key is also removed you see right here trick roll over we've deleted it and now it's just simply gone it's not in there very simple to do that but just understand that once you delete the key the value is gone however if you were to try to delete the value the key will be there but you'll have a null value and that could lead to some issues down the road that's a more complex topic we're going to cover in a future video i just want you to be aware of that i've been getting a lot of really good feedback about this video series and some people have said hey dude you're going a little too slow i realize these are for beginners but i want more now so we're gonna give you a little preview of what come so we're gonna test for existence and we're going to do something called a loop and both of these may be a little challenging especially for newbie programmers but if you're an experienced programmer and you just want to learn it now let's just go over it and get it out of the way so we're going to say if and this is basic logic i say name in d colon and hit enter what we've done here is an if statement this is a logic if this key is in the dictionary do something now python has this little guy right here this colon at the end saying hey it's not the end of the statement expect more and then you have to have it's either spaces or a tab it doesn't really matter but it has to be the same amount if you're from another language you're expecting something like this and you may be going why do you need tabs well if you think about it your code is here and if you get rid of the tabs it looks like this so it just makes sense but a lot of people when they're first starting python can't wrap their head around the tabs or the white spaces and it just infuriates them so this is what i was saying earlier about we're going to test to see if that key exists before we try to access it now if the key was not in the dictionary it would throw a key error but we're saying if so only if this exists in the dictionary are we going to run this code we're going to go over all of this in more detail in a future video but i've had a lot of people saying hey they want more now so there's one now let's go over loops this is the other thing that really trips people up especially in newbie land is because they're new they don't understand this stuff nobody's explained it to them what is a loop well have you ever like gotten in trouble as a child and like your mom or dad says you know go do this until i tell you to stop that's basically what you're telling the computer to do you're going to say four a key in the ease and this may look really confusing if you're a complete movie again gotta have that white space we're gonna go ahead and print and let's go ahead and format this and i am gonna explain this but at the moment just take a huge leap of faith with me here so we got our key and then we're going to say dictionary and then the specific key this looks ugly if you're a newbie but let's run it it works so it's saying pet dog h5 name spot that's what we're doing right there so what's going on here is we're saying for every key in there's that in keyword again the dictionary keys remember we talked about this way up here for every key in the dictionary keys go ahead and print out the key and the dictionary value that correlates with that key again you have to have that tab there we're going to cover looping also in a future video but this is just because people have been saying we want more and we want more now so if you're having trouble wrapping your head around these two right here don't worry i'm going to make a future video that's going to cover those in depth and we're going to talk about them and i do mean in depth but if you are a seasoned programmer that's very simply how you do it if you're having trouble wrapping your head around these tabs just think of it like this you have some code and then normally you would do something like this and python's trying to help me out here but you would have something like that strip this out replace it with that and of course you have something here sad code i'm not let's say sad code here but then you strip these out and it becomes that and that's why python is so much smaller than other languages compared to something like java javascript because it takes all those special characters out of there welcome back everyone my name is bryan let's continue our journey with python3 so in this video we're gonna talk about if else and lf what are these three things well it is simple low control when we talk about flow we're talking about the flow of an application and this is the basic building blocks for that flow control before we dive in we need to talk about some basic theory don't worry i'm going to keep it super short we have a variable let's call it x and x is true a very simple bull we can turn it on we can turn it off now we're talking about flow control think of flow control like when you were a child and your parent looked at you and said if you do this then this is going to happen that's essentially what we're talking about it's a decision it's not super hard to wrap your head around but it does take some explanation so x equals true we've got our if statement and if is going to function on some sort of condition a condition most of the time will evaluate to true or false so we're going to say if x equals true then do something we'll have some code that'll run if it's true and we'll have some code that'll run if it's false now this is not always the case what i mean by that is sometimes this over here simply doesn't exist you're only going to evaluate for true but you can do things like say if it's true do this else do that and it can read like a book you can literally say if bob equals happy then do something if bob is not happy do something else it's really that simple however you need to understand this is the fundamental building block of almost all applications this is called flow control you are controlling the flow of the application's logic all right enough theory let's dive right in we're going to look at if conditions so we're going to create a variable called x and we're going to say it is true this is just simply a bull we've seen this before now i'm going to say if you notice how in vs code it gives us these little templates we're just going to do normal if we're going to say if x colon and now we want to print something out let's go ahead and run this and see what happens and it says yes so our programming logic is x is true and if x notice how i just said if x we could have said if x equals true then it's going to print this out but it knows it's smart enough to know you don't really need that also notice this indent we've talked about this a little bit before and this colon so if you're coming from another programming language this is really what it looks like under the hood you have these brackets as everybody loves and you know c plus plus c sharp javascript all the c style languages and the code's pretty much indented well python does away with that so all of this gets converted into that and it's much shorter much easier to read you don't have all these weird squiggly lines you got to worry about now you can continue to execute as long as it's on the same indent for example x is true if x print yes and again see yes and again now we are going to say else and this is where we pop back we need that right there to tell python that we've got more coming and we're going to just simply print oh what's going to happen when we run this well x is true so if x and then it's going to run this else it will run that else is funny because l says hey if this didn't happen then instead run this code here whenever you see these indents think of this as a block of code it's actually called scope so this would be a scope and this would be a scope it's a much more complex topic that we'll cover in a future video but i want you to be aware that exists let's go ahead and run you see yes and again it never printed no i'm gonna say help i mean just to make sure this really stands out on the screen run it again we never see it why because this is true if x then print this out it never jumps to l so let's change this to false and you'll get a feeling for how programming logic takes place x is now false it's going to say if x print these else print that so what's going to happen here is it's going to get to x and say no x is not true so ignore this block code and instead jump down to else and run this block of code see help works as expected so what we've really been talking about is condition evaluations and they're pretty much going to be true or false meaning true run it or false don't run it or just do something completely different let's take a look at some condition evaluations here so i'm going to say x equals 100 y equals 25. so i'm just creating two little variables here and i'll say if and we're going to say y equals x we want to tell python there's more coming and we're going to print this out notice i'm doing this all on one line you don't necessarily need to do these tab indents you can do everything on one line if you want to so we're saying if y is equal to x notice there's two equal signs if you do this you're saying make y the value of x and we don't want that we want to test for equality here we're going to say equal to and we can just through the magical copy and paste speed this up just a little bit here and we're going to look at our condition evaluators here so i'm going to say if y is not equal to and then we can say less than so if y is less than x and i want to say greater than so if y is greater than what we're really getting at here is you can do some really complex decision making based off values and they're very simple very easy to understand all you need to do is understand the symbols for example this guy right here looks super confusing but we're saying if y is less than or equal to notice how you have this compound here so now this gets really complex and you've got it all on one line but it is super convenient to do that and you can do the exact opposite you can say greater than or equal to let's go ahead and test this out here so we're going to run this and you can see it doesn't print everything it says not equal to less than and less than or equal to so what's going on here we're evaluating y versus x so we're saying is y equal to x well it's not they're two different values so it's not going to run this code this is what i mean by the condition evaluations will go to true run it or false not run it there are other ways of doing it but we're keeping things super simple and then we're saying if y is not equal to x which is going to evaluate to true because those two are not equal then print this out and sure enough we see not equal to i'm not going to go through each line but you can kind of view and see which one of these evaluate to true for example is y greater than x well of course it's not 25 is less than 100 so this will never run and we don't see it down here now if we change this value you'll notice the output changes as well now it's not equal but it's greater than and greater than or equal to this is extremely cool and it's extremely flexible now you start to understand how computers make decisions it's based off simple if logic if this statement or this condition evaluates to true then run some specific code all right all of this seems pretty cool but look at this it's kind of a jumbled mess it's just this big wall of if statements it's very hard to read there's no indentation then you got to kind of read through every single one to find the one you're looking for let's talk about elif which is really a switching solution now when i say switching other languages have a concept called a switch which is just like think of a big panel of light switches you can turn them on and off python doesn't really have that concept there's ways around it but it doesn't really have that specific concept so let's look at a way of getting around this so i'm going to say x is 10. now we want a bank of switches we want to be able to turn code on and off at will so i'm going to say if x equals 25 then we're just going to print out x equals 25. now we want to take this and kind of smash it into something without doing a completely new if statement we want this to stay all in one line because believe it or not these are two different statements and they'll execute separately so what we're going to do here is l if x equals 50. so really now it's going to read this as one giant line so it's going to say if x is 25 execute this else if x is 50 execute this and we can just take this concept and keep expanding on it go ahead and say if x is 75 and let's go ahead and say 100. we can end this and say you know what if we didn't find any of these switches using the lf statement we can simply say else and then make what's called a catch all which is going to execute if none of these fired off so it's at 10 let's see what's going to happen here it triggered our catch-all see so it went through and evaluated and says is x25 no is it 50 is it 75 is 100 else fired off let's switch this to 75 see what happens you can see now it just says x is 75. so what's going on here is it says evaluate this evaluate this evaluate this turn to true run this code now we're done so it'll jump all the way out very simple very easy logic and it looks much better than just this giant wall of text super easy to follow as you dive deeper and deeper into program you're going to find there's always another way of doing it if you didn't like l if there is another way and it's called nested or nestled statements and this is basically a statement and a statement in a statement and statement and you can go on forever and ever and ever let's go and take a look so i'm going to say x equals and let's just pick a number random 82 and we're going to say if x is greater than 50 print and let's say over 50. but wrap that in some quotes here and because it's over 50 we want to keep going so i want to say if x is well greater than 60 then and we can use the same logic over and over and over and this now becomes a very repetitious pattern so for example i just say this and we just grab this and keep going notice how the indents get bigger and bigger and bigger you have to do this otherwise python considers that a new statement so for example this would actually create a problem here it's not going to execute the way we want it to so what we need to do is indent indent and and this is what i love about vs code is it puts these lines where the indent is so now you can see this is a statement this is a statement and so on and so on and it gets very very cool very quickly now sometimes pasting betrays you and you just simply gotta tab it over again the lines will be your guide and literally tell you where you need to go so let's say if it's over 90 and i don't want to take this too ridiculous let's go ahead and say if x is greater than or equal to 100 we're just going to end it here print complete let's just say that x stood for some sort of progress now we've got some issues here right off the bat you just saw this little squiggly line here it's saying unexpected indent so we've got to back this out here and fix our indentations uh oh didn't like that so we can just grab this whole thing and indent it should fix it there it goes save and run uh-oh we have another indentation error let's see what's going on here so this is the part of python that will drive you absolutely bonkers if you don't have your indentation right it will let you know and you'll get an indentation error now that all my indentations are fine it should run as expected so which one would you use well it depends so for example in this scenario we have what's called fall through meaning x is 82 so it's going to evaluate true jump to the next one true jump to the next one true and jump to the next one true and then it suddenly falls so it stops executing here even though there's more of the statement and you have these lovely little indents love them or hate them that you have to contend with remember the indentations tell python where you are in the programming logic so some people like alif some people like fall through expect to see both of those out in other people's source code choose the solution that works right for you my personal preference is for elif welcome back everyone my name is brian let's continue our journey into python 3. we're going to talk about the while loop this is basic flow control and it's going to prove a point your computer is very stupid yes i said what i said your computer is just very dumb and we're gonna prove that so a loop is just simply completing code over and over and over again until you tell it to stop because the computer isn't smart enough to know when to quit let's take a look okay a little bit of theory here before we move on we have the entrance of our program and we're going to jump down into some sort of loop let's call this our loop here and it's going to evaluate this and run some type of code now it doesn't really matter what type of code it runs let's get rid of that little guy usually what you're doing is some sort of incremental function for example count something increase a number uh look for data on a socket or something like that so it's going to say okay start the loop i don't want to connect there there we go and do something if you don't exit this loop it just literally goes right back into the loop and your program ends up looking something like this we call this an infinite loop where you will enter the program go into a loop and then you just loop this code over and over and over again until you tell it to well stop and do something else you may be asking yourself why do you even need a loop well think about it you enter your program you come down into your loop and let's say you want to do something a hundred times you need to now increment some sort of counter once you've hit that counter you jump out of this loop and you stop your code there are some loops out there that are intentionally infinite and what i mean is they look like this the program starts you enter your loop and then it just loops forever for example when you in and do graphic user interface programming you have what's called the user interface loop or the event loop which is basically the program will run forever waiting for the user to like click a mouse or move something around that loop just happens forever and ever until the program closes all right now that we understand what a loop is let's take a look at it in practice so i'm going to say x equals 0 and we're going to create our while loop and this is going to look very similar to an if statement because it's going to evaluate it just like an if statement would meaning this loop will execute as long as the condition we're about to give it is true so let's say x is less than 10 and do something and this is going to be a great example of how computers are dumb they do what you tell them to as you tell them to do it a little bit of bonus anybody see a problem with this statement well what we're saying is x is zero while x is less than 10 print this but we're never incrementing x it's always going to be zero so this will always be true and it'll just run forever that's the infinite loop i was telling about see how it just says zero and it's going to run forever and ever and that console is just going crazy so i'm gonna kill it it will just keep going forever and ever until i turn the program off or until i shut the computer down so we need to actually increment x once we do that we have now incremented our counter eventually x will be 10 or greater and this will exit out see 1 through 10 works as expected now so loops can be very powerful and very easy to use but you can very much screw up your application just by creating an infinite loop on accident now in case you're wondering let's go ahead and print this out here and we're going to say test one is done we want to know when this loop is done executing and we use you guessed it the indentations this determines our scope or our block of code so while this condition is true execute this scope or this block of code then when we're done looping we're going to jump right back up here let's see that action i'm going to clear that out sure enough 1 through 10 and then test 1 is done so it works exactly the way you think it would let's take a quick detour and talk about pass you're going to see this quite a bit in python land and a lot of people don't really explain it so let's just say while and let's just take this little template here and it's going to say while expression pass but this is a valid python expression and say zero and let's just give it the same logic here notice how this will run now what's going on under the hood is this is still functioning or is it let's find out here i'm going to kill this terminal just in case we'll say test 2 is done so x0 while x is less than notice how we never increment it like we did in this guy we're going to pass and then eventually print out test two is done save run notice how it says test one is done from up here but it never gets down to test two so what's going on under the hood this script is still running it's just doing an infinite loop right here so whenever you see pass inside of a loop be very careful because you're creating some sort of infinite loop pass is a special keyword in python that tells python take no action and just continue with what you would normally do so be very careful with pass we just covered that pass is well pretty dangerous in a loop simply because you can loop forever on accident well it's not that simple under the hood but we're gonna try and make it simple and we're going to talk about continuing and breaking so we're going to say x equals 0 and let's go ahead and do something really really terrible we're going to say while true do something if you're paying attention you know that while is going to evaluate this much in the way an if statement would and it's going to say if this is true do the loop and keep doing it over and over until this is no longer true however we've used the python true keyword so this will now loop forever and you will actually see this out in code because sometimes people just want to loop until some arbitrary condition is met it could be input from the keyboard it could be some network connection could be anything but you're going to see this a lot so you'll need to know when to break out of the loop or how to handle certain conditions so let's talk about continue first we're going to say x plus equals 1 and if x is less than 5 we want to well just kind of skip over this and we don't really want to do anything so i'm just going to say x is less than 5 whatever the number is and then we're going to continue and what continue does is say go back to the beginning just continue along your merry way and do what you were going to normally do and then we're going to add in some sort of logic so if x was greater than 10 we would do something print that x out and we're going to put a print statement at the very very end of this and notice this is on the same line as well so this will not print out until this loop is complete one thing i love about vs code in most editors you can actually collapse so it actually looks like this so once this loop is done it'll print complete let's go ahead and clear this out see this in action here uh oh you notice how it's working exactly as we expect it would because the computer while very fast is very dumb so what's going on here is it's going and saying if x is less than 5 rent it out and then just go back to the beginning so we're still in continual loop land we need to fix that so our programming logic we want to basically say if it's less than five just go back to the beginning of loop and keep incrementing that counter if it's greater than 5 do something but we also want to stop when we hit 10. so i'm going to say if x is 10 print and then x equals just so we can see that x is actually at that value now we're going to use the break keyword now don't worry we're not breaking anything break is like kind of think of the while loop this guy as a little jail cell and we're going to break out of jail and just jump right to the next line so it's going to pick up code execution right here and then it's going to run this statement go ahead and see this in action okay sure enough we've got x is less than five we got one two three four and then do something six seven eight nine ten and then when we hit ten we're going to exit and we are complete so that is looping in a nutshell so major takeaways from this video is well loops are very very powerful but you need to have some sort of condition to evaluate otherwise you're going to create an infinite loop an easy way to create an infinite loop is just simply pass and it will loop forever and you can say while true which will also create an infinite loop but you can use continue to well continue to use the flow inside of the loop or break to break out of that flow and use the programming logic welcome back everyone this is brian this video we're going to talk about the for loop and the range function the difference from the for loop compared to the while loop which we talked about in the previous video is the for loop has a beginning and an end and the range function helps us create that beginning and end really helps us to just avoid that nasty business of infinite loops let's dive in and take a look all right first things first let's go ahead and look at the for loop on list tuples and sets this is super super ridiculously simple and i'm just going to make a simple list and we're going to say 4 i in notice what we're doing here though we're saying 4 and then we're creating a variable and this variable is named i you could name it x z zebra whatever you wanted to name it i'm just going to say 4i in and now we have to give it some sort of container say x and then the colon this reads just like the while loop but we are now creating the variable in the statement itself what we can do now is just simply say print and let's say i we're going to print out the value of i go ahead and run this you see i is 1 2 three four and it stops we don't have to tell it to break or to return or to do anything like that and we don't have to increment some sort of counter it does it for us under the hood based off you guessed it the length of this list so it's taking this iterable container and it's saying each one of these is now a separate variable and we're going to treat it independently and you can do this ridiculously fast and you can do it across different types of things here so for example i think i made one too many we're going to say list a tuple and a set and we're just going to say this is l this is t and this is x so we've got a bunch of different things here and let's actually one of the little nuances of this is you got to have it in the right style bracket here or this case is the parentheses and the set has a little weird squiggly thing there we go and we can just switch this out so i'm going to do the list works as expected let's switch this out to the tuple works as expected and i know you're already probably rolling your eyes going we know we know the set's going to work just fine and it does everything works as advertised this makes it just ridiculously easy to loop through a container let's take a look at the for loop in regards to dictionaries we're going to treat this a little bit differently here so i'm going to make a dictionary and i'm going to say predict and let's just go ahead and build this out brian i'm going to say my age is 46 say tammy don't tell her i put this in the video she'll get very mad but she's 48 and then heather let's go ahead and say heather is 28 and chris let's just say chris is 30. we could add more if we really wanted to so we have our beautiful dictionary here go ahead and print this out just so we can see what it looks like and it creates a dictionary for us now we're going to work with this in regards to the looping when i say the looping there's a couple different ways we can do this so the first way we're going to say 4k in x dot ease i got to be a little careful here if you forget to call it as a function and we haven't really covered functions yet but trust me on this if you just do this you're going to have a bad time and let's actually see it fail just to prove that hey it is going to fail and we're going to say keys okay equals and then we're going to fill that out later but let's just watch this thing fail see built-in function or method object is not iterable what what is going on here what does this mean plain english built-in function or method well we haven't really covered these yet but basically it's a chunk of code that we can call and to do that you need these parentheses so if you forget those you can have a bad time and it says object is not iterable what does that mean well it needs to be a container of some kind for example a list tuple set or a dictionary so simply by saying hey use those parameters it's now going to return some sort of data that is iterable which we can go through and work with all right let's continue on we're going to say x and we want to get that specific key and i'm gonna just assume you watched the previous videos but just in case you skipped them let's slow this down just a smidge here first things first we need to fix our little error there so what's going on here is we are creating our dictionary the dictionary is just a key value pair p value key value key value and you can see that in the dictionary right here where it's created those key value pairs now we're going to say for each k or each key in our dictionaries keys it's going to return back some sort of list we're going to say for each one of those get the values so we're saying x a so really what we're saying here is x is a dictionary k is the key so we're saying for whatever key for example if it was tammy it's going to say print out tami because that's the key and then print out the actual value here which is that right there so each key is going to correlate to a value so what i'm trying to really drive home here maybe i explain that badly so keys and then you get your key value key value key value there is another way of doing it and i wanted to bring this up simply because you're gonna see people do it both ways so we're gonna say for k comma b this is going to blow your mind if you're coming from another language we're going to say two different variables here key in value in we want to switch this out to items and again we're calling a function so we need those parentheses there if we forget those we're gonna have a bad bad time and because we are now pulling these or unpacking those we don't have to do this little bit here we can just simply swap that out with our variable so what items is doing is well it's actually pulling each e-value pair out and returning it so now it can unpack the key and the value so you have two different variables see that in action here let's save and run and actually let's call this items so we don't get that confused with the keys and sure enough items and it has unpacked them correctly brian 46 tammy 48 heather 28 chris 30. so which way is better well it depends on what you want to do personally i tend to do this method right here that way i don't have to mess around with all these little brackets remembering what does what but each way is perfectly fine let's talk about range and we've touched on it briefly but let's really look at range so let's kind of quick review here we're going to say x equals and we want a range of five and if we print this out this is where you're going to get really confused really really fast so let's go ahead and run this and here's our x right here range zero to five wait what you're thinking this is going to return a list or something like that actually it's going to return a function call so there's range zero to five what is this zero to five where did this come from we said five well we're going to look at that in the next little segment here but just understand what we're really doing is we're saying x is really going to equal a call to that function we're going to color functions in depth in other videos it's actually a large topic so we're going to split it into multiple videos just understand what's going on here you're not actually getting some sort of iterable container that you can go through but what we can do here now is something like this for i in x notice how i don't have these parentheses because we are not calling a function directly we're calling a variable you try to do something like this you're going to have a very bad time just understand the difference between those and then from here just some becomes really ridiculously simple this is what i love about python everything just becomes very simple to the point i'm almost embarrassed to just even talk about it because to me because i'm an old programmer it seems like just common sense and there we go range zero through four so what's happening under the hood here is it's saying for i so we're creating a variable in x and this variable is actually pointing to a function so it's making this function called getting that value back and then it's going through each item now if that last little bit hurt your brain fasten your seatbelt range can get a little complex here so we have a start a stop and a step what does this really mean let's go ahead and do this let's say x equals range and i'm just going to leave it here for now so we can read this and see what's going on we have stop int so that's the default but there's different ways of calling this you can do a start which means the number you're going to start at the stop which means the number you're going to stop at and a step meaning how many numbers in between those two you want to jump let's take a look at this and see what it really looks like under the hood so let's say we want to start at 5 we want to stop when we hit 20 and we want to take three steps at a time all right pop quiz what is this going to look like let's go ahead and print this out if you thought it was going to say range 5 23 you were absolutely right because beginning to understand here that this is pointing to a function not some sort of value but we can actually work with it now that we've assigned it to a variable called x go ahead and say 4i in x remember we're calling a variable not a function go ahead and print okay bonus round who knows what this is going to print out here let's see starts at 5 and then it goes to 8 11 14 17 and it stops at 20. notice how it didn't fire off at 20. if we said 21 let's see what happens now suddenly it includes that so that's the major takeaway from here is it's not going to include that stop it's going to stop when it gets to there remember under the hood this is using some sort of loop it's saying probably something that we've seen before like this while and then x is less than 20. so when it gets to this 20 it's just gonna break out of that loop and stop doing it once you understand how this works it makes life ridiculously simple something like this would require a little bit of math in other languages but python as usual makes it nice and easy welcome back everyone this is brian we're going to create a simple application using everything that we've learned to this point if you're just now tuning in there are 13 other videos in this playlist you need to go back and watch if you don't know python but we're going to make a paint calculator so we're going to determine how much paint is actually needed to paint a room when we run this the user is going to be presented with something like this paint calculator in our wall size as width comma height in feet or press enter to stop for the example would be 12 comma 8 no spaces or anything like that and they can enter as many walls as they want and at the end this is going to magically tell them how many cans or how many gallons of paint they need to go by let's take a look first thing we need to do is well set up some variables so we're going to make a list called walls and this list is going to exist just to hold the measurements second thing we're going to add is gallons this is going to be well how many gallons of paint per square feet and i'm not an expert but i did go out and look this up on google and according to google one gallon of paint covers 350 square feet i question that because every time i have bought paint i have never bought enough and i've had to go back to the store and get it maybe this application will help us and then total is going to be the total number of gallons of paint we need to go buy we're going to use this later little gallons to buy so far our application does absolutely nothing but that's about to change we are going to get the user's input and we haven't talked about this yet but we're going to make a while loop and we're going to say while true and you may be going to whoa whoa whoa you're making an infinite loop that's true we're going to break out of this and i'm going to show you how so we're going to get a variable and we're going to use the built-in input functions there's different ways of doing this but we're going to use input and i'm going to say enter wall size then we're going to break out of this if they don't really enter any data so i'm going to say len of s to zero then we want to just call break if you kind of questioning what any of this is go back and watch the previous 13 videos that i've done on this so let's go ahead and test this out we're going to run this and it says inner wall size you know how our programs just stopped and waiting for us well i'll just enter some garbage i'm gonna say cats and it wants another dogs and another fish and then i'm just gonna hit enter and sure enough it exits out so that is the correct way of using an infinite loop to gather user input and to test when we need to break out of this loop now that we can get the user input we need to actually do something with it and before we try to do anything with it the first thing we should do is well verify that what the user gave us is actually what we're hoping for or we could have a very bad time remember this whole thing started with the example of 12 comma eight well i entered cat's dog's fish i'm not sure how you would calculate the square footage of a cat but i'm sure it would be interesting and probably involve a trip to the vets but anyway so we're going to say sqft equals and we're going to say s dot split because the s is our variable we got from the input function right up here and it's going to be a string so we can treat this as a string and say s split and we want to split this on the comma again if you have not a clue what i'm doing here watch the previous 13 videos but anyways string has a built-in function called split which you can return multiple values based off a character or sequence of character so our square footage is going to be the return value from that split function so first thing we're going to do is make sure we actually have two values in there and if it's less than two well we want to tell the user something bad happened print let's go ahead and just say invalid format and then we're going to break out of here now remember break doesn't really care where it is it's going to break out of this loop let's go ahead and test this out here so we're going to run this and it's going to say inner wall size and i'm going to say okay two comma six uh it's working good five comma seven and let's enter some garbage cats uh oh invalid format and it stops the loop and exits the program so it is actually testing to make sure there are two items that is split on a comma all right we're not done yet we need to now that we've gotten the user input convert it because remember we're working with strings and we want to work with numbers specifically we want to convert from a string to an integer and this could lead to a bad time and we're going to demonstrate that so i'm going to say w equals we're going to call int and we're going to do something called casting and i'm going to do a whole video on this later but when i say casting just think of a wizard with a magic wand who's going to cast a spell and turn something into something else so what we're saying is we want to cast a spell called int which is going to convert whatever we give it into an integer and in this case we are going to get that first value out of square footage go ahead and grab this give it the old copy paste a little too much copy paste and let's get the other dimension so we now we have the width and the height from square foot zero and square foot one interesting bit if we try to do this and it's not actually a number we're going to have a bad time it's going to actually air out and our program's going to stop and die a horrible death and i'm going to cover how to handle all that in another video the whole point of this program is to do a program with what we've learned so far in the 13 videos now i'm going to say item and i want to make a list with the width and the height and we're going to add that to our walls if your case you're wondering where i got walls from remember it's way way way up here in our variables just an empty list so we're going to say walls and let's go ahead and add that item in here so now we have a list holding the wall dimensions for every single wall that they add let's go ahead and just print that out just to verify hey we did something so adding wall go ahead save run and let's test this out so inner wall size all right three by six that's a very small wall and it says adding wall all right great so eight by eight let's go ahead and say nine by twelve now let's test out this conversion right here and watch it die a horrible death so i'm going to say to buy cats oh invalid literal for int with base 10 cats and this looks very ugly and it is it's a value error we're going to talk about errors in a future video i just want you to understand if you get a value error what's going on is we're basically saying we cannot convert this to a number or specifically to an int remember think of a wizard with a magic wand and we are casting a spell called int which is going to convert whatever we cast on to an ant once we've got to this point the only thing that's left is to really just crunch the numbers and tell them how much paint they need so what i like to do is just tell them what they entered so we're gonna say f you entered that way if there's any discrepancy i can say send me a screenshot of the app and i can show oh no no you screwed up you entered the wrong value here and i'm gonna say 4m m is going to be for measurements in walls we're going to say the width is going to be m0 remember it's a zero based index and inside of our walls we have created another list here so we're getting this guy the width and we can say h one remember zero based index that always trips newbies up now we're going to get the square footage so i'm going to make another variable called s i'm going to say that's simply the width times the height now i want to get some sort of value so i'm going to say this is the s or the square footage times the gallons in case you're wondering where gallons magically appeared from remember it's all the way up here in our global variables that we created i did google it one gallon should cover 350 square feet so this value right here is 1 divided by 350. not a clue if that's accurate i highly doubt it even though i do trust google and then we're going to grab our other global variable total i'm going to say plus equals v so we're just incrementing that in case you're wondering plus equal we did cover this in a previous video it's basically we're saying total equals total plus the value but we're just shorthanding it now we're going to drop down and go inward we're going to dent in so we're dropping out of this code block right here and we're going back to the main we're going to say print we're just going to tell them you need to go buy some paint and this is how much paint you need to go buy you need to buy let's go ahead and if we just say total it's going to give us some crazy number so what i like to do is make it a little pretty and i'm going to say round and we're going to round the total by two decimal places we're gonna tell them you need to go buy or many gallons of paint rounded to two decimal places let's go ahead and test this thing out and see if it works so i'm going to say 12 by eight and let's make another one fifteen by nine actually let's make it by eight that'd be weird if the ceiling was different height and let's go ahead and say we have an eight by eight and a four by eight just kind of a weird shape room and then i don't want to enter any more so i'm just going to hit enter and you need to buy one gallon of paint basically it's going to use less than a gallon i should have some left over i don't know how accurate that is and honestly i'm kind of looking at my little office here going i think it's going to take more than a gallon to do this so when in doubt blame google but the major takeaway from this video is even though we're only 13 videos in and we've really just scratched the surface of what python can do you can make some pretty interesting programming logic we just did a simple application which is a paint calculator telling us how much paint we need to buy we're letting the user enter any number of walls they want we are verifying that user input and then we're converting that input into the correct data type and then we're calculating how much they need and giving it back to the end user welcome back everyone this is brian we're going to continue our journey into python 3 with an introduction to functions so first off what is a function it's a block of code which only runs when it is called so far all the code we've written runs immediately i mean as soon as python reads it it runs it this is going to change that we're going to write some code and we are going to decide when it runs this is another fundamental building block of programming and there's a lot of theory attached to it and there's a lot of names in terminology so we are going to split this into multiple videos some key takeaways from this video though is that you can pass data known as a parameter or an argument into a function you're going to hear these two used interchangeably it gets really confusing so down here i put some notes the difference between a parameter and an argument a function parameter is the names listed in the function's definition where an argument is the real value that's just confusing why don't they just call it like a name or a value but instead they've got to call it parameter argument and everyone even myself gets these mixed up you'll hear some videos where i'll call it a parameter in some videos where i'll call it an argument and i've heard people with vastly more programming experience that may switch these around as well it's just that confusing another major takeaway is that a function can return data as a result turn is actually a keyword and we're going to cover that diving into theory land just for a moment here so far we've worked with statements and what do i mean by statements we've done something like this so far we'll have a statement a statement a statement and python just reads it from the top down for example we would like print something maybe do a while loop inside that while loop we could have like an if statement and it's just kind of read like a book straight from the top down but now what we're going to do is introduce a function which is a separate block code it's not going to run unless we specifically tell python go run this code and a function can call other functions and so on and so on the end result now is that we can fundamentally decide how we want our program to run and how we want it to behave we can do some pretty complex programming logic using this another key takeaway here is we are subtly introducing the concept of scope everything that we've done so far has been on what's called the global scope and each function each block of code has its own scope scope is something we're going to dive into detail in a future video but just understand we are subtly introducing this so let's test this let's go ahead and define a function we're going to say def which is shorthand for define or definition and we're going to give it a name and then we have those little parentheses if we forget those we're going to have a bad time we need the parentheses and then in there we would define any parameters we're going to keep this first one very basic and there'll be no parameters but we still need the parentheses in there and then colon and hit enter and notice how most ides will do this automatically where they will drop you down a line and indentate you automatically then we can just fill in our code we can have pretty much anything we want in here i'm just going to put a print statement just for testing and we're just going to say this is a function now we can work with this thing as needed okay this last one was a little bit simplistic let's ramp up the difficulty here so we're going to define a function with parameters and return a value in the last video we made a paint calculator which calculated based off the square footage how much paint we needed we could have very easily used functions in that and most programs would have so we're going to make a function called sqft which is shorthand for square footage parentheses and let's define some parameters i'm going to say w for width and h for height now we can add our programming logic in here so the value we're going to return is going to be simply the width times the height now we're going to use the return keyword to return that value notice how these are both very simple but they're fundamentally very different this first one basically has no parameters and run some code and once it's done it just jumps right back out of here this one however we have to give it two parameters and there's going to be some logic and it's going to return a value it's up to us to decide if we want to actually work with the value that's returned it's not actually mandatory we can just ignore it if we wanted to but this is what i mean by functions can get very complex very very quickly we have two very small functions that act completely differently let's take a look at how this actually works how would we call a function now what do we mean by call a function remember this code is not going to execute until we specifically tell python to run it let's go ahead and run our program as is and see what happens absolutely nothing so what it's doing is it's reading from the top down it's saying define test define sqft and it has this queued up in memory ready to go but it's not actually going to use it until we tell it to so let's tell it to run it most editors are going to be smart enough to tell you hey this is an actual function and in vs code this little block means it's a function notice a block because it's a block of code now if i just hit ok or enter or click on it it does nothing this actually will not run we have to add those parentheses now suddenly see how it says def test and it knows we're trying to call that function let's go ahead and run and ta-dah this is a function so python is reading this from the top down defining test defining sqft getting here and saying oh it wants to actually call this there are no parameters so we don't have to supply any arguments you may be wondering what the big deal here is why would we even mess around with functions i mean we could have just printed this out well let's take a look at a specific situation let's say we wanted to call that function multiple times we're say 4x in range and we're going to say range 4. so we want to call that multiple times now we could just write this out like this four times you could do something like this and you'll see people do that however that's not the best way what if your boss comes and says well i want you to do that twenty thousand times um okay you're gonna have a very big file calling that out it's much simpler way you would say 4x in range and then you would call this so what we've done now is we've created a loop and we have a lower boundary and an upper boundary and it's going to call it so we have not created an infinite loop it will call our function let's see this in action and ta-da there it goes right there so that's the power of a function you can define a block of code and then decide when and how it runs now in typical fashion with these videos i do like to ramp the difficulty up here so we're going to call a function with parameters and this is what i mean by this is going to get confusing fast remember our little buddy the sqft function which we defined which we haven't really worked with yet let's go ahead and say x equals sqft now we have some parameters and it's smart enough to know that it's a param so we have to feed it some information now i'm going to say 12 by eight bonus question here these numbers are these parameters are these arguments well they're arguments so these up here are the parameters they're in the function definition the values we're feeding it are arguments and you're going to get people that will go pun intended argue this all day long because people get it so confused all right let's go ahead and print out the square footage so the square footage is 96. now you see just how powerful this is you can define some sort of logic and then call it on demand when you need it and get the value back from it and use it accordingly just a quick recap what we've talked about in this video is well functions are amazing they're also very complex it reads from the top down you have to use the def or the def keyword to define a function functions can have zero or more parameters those parameters have to be fed arguments hello again everyone this is brian let's continue our journey into python 3 with functions and scope this is a theory heavy video but we're going to try and make it very simple so we're talking about lexical scoping sometimes known as static scoping which is a convention many programming languages use that sets the scope or the range of functionality of a variable so that is only called from within the block of code from which it was defined however scopes can be nested inside of each other so you ever have like a box and a box and a box in a box that's kind of what we're talking about and that's why this really will hurt your brain if you're not paying attention so let's dive in and take a look so let's take a look at lexical scoping and i'm going to just put a square out here i'm going to make it nice and big and let's go ahead and give it a color let's say this is going to be some sort of green doesn't really matter what it is so that would be a block of code and actually you've been working in this this whole time this has been called the global scope everything we've done so far has been in one giant scope called the global scope there's other names for it as well but that's basically what we're talking about now we can actually take another one let's go ahead and bring this all the way to the front and let's set this as a different color say blue and this is a different scope think of this like a function doesn't necessarily have to be a function it could be like a while statement or an if statement something like that so what we're getting at here is you have this big overarching global scope but then you have these sub scopes now to make things a little bit more complex let's say we have this scope here that's inside the global scope let's call this a function for example we're going to go ahead and make another one and let's give this a different color this is what we're talking about so you can have a scope with a scope in a scope like a box in a box in a box and it gets very very confusing now this guy here let's just actually move all of this down here and make it graphically easier to understand you have your global scope you have your function scope and then you have another little like a statement in here you can define something in the global and use it all the way down through here even down into the statement you cannot however do the reverse you can't define something in the statement and use it backwards up in the global scope so this is why it gets very very confusing and i think graphically this is probably one of the better ways of really defining this just understand that you can have a scope with a scope inside of it and another scope inside of it you can define something and as you get more granular you can use whatever you defined however you can't define something at the very granular level and use it higher up all this talk about scope is well confusing so let's just dive in and look first thing we're talking about is the global scope this is probably the easiest concept to understand because we've been using it this entire time that's right so if i say name and then just whatever your name is we have now created a variable on the global scope meaning anything in this application can now use this this is extremely cool and it's extremely easy so let's demonstrate this global scope functions can access the global scope so let's go ahead and define a function let's just call this test1 very descriptive name i know and we are going to use this variable which we created in the global scope in this function and remember this function has its own scope that we're now defining say print and to test this let's go ahead and let's call this function my name is and then the name from the global scope makes it super super convenient however what we're going to show in this video is that this convenience comes with a cost of complexity and there's some issues you can definitely run into let's do the reverse and show some problems we can run into so for example the global scope cannot access a function scope seems absurd we define the function in the global scope we should be able to access it but it doesn't work that way let's say x equals 10. let's go ahead and define a function let's call this test2 very super descriptive name and we're going to say x equals 50. now you may be going wait a minute there's two x's so it's the same x but it's really not let's go ahead and take a look here and we're going to say function scope and then we're just going to print out that value of x go ahead and go down here let's call this function just so it's going to print that out and then we're going to say global scope all right so top quiz x equals 10 x equals 50. what is this going to print out it's going to say function scope x global scope x let's take a look so if you thought both of these would be 50 you are wrong this is what's going on here we have x in the global scope we are now creating a new variable in the function scope and assigning it a value of 50. these are two different variables so it's treating them differently even though they have the same name oh this is confusing but it exists for a reason it's called name collision if you have a variable with the same name you don't want to overwrite that let's say this was some magic number like a password or something and then we went and kind of goofed it up in a function somewhere we don't want to break the functionality of the application so this actually exists to protect us from ourselves okay let's dive deeper and deeper still so we're going to talk about global scope function scope and statement scope all in one and this is going to really really tax your brain here so we're going to make a global variable we'll say x equals 15 and let's go ahead and just put a print statement print globalx just so we can see what's going on here there it is 15. now we're going to define a function so i'm going to say def s3 ever descriptive name i know and i'm going to make x zero what have we done here well we've created two different variables we've talked about that a little bit here and we're saying this variable is 15 and this variable is zero so i'm going to through the magic copy and paste i have some notes off the screen here just to save a smidge of time we're going to print these out let's go ahead and call this just so we can see what's going on and sure enough global's 15 function is zero things are working the way we'd expect them to even though it's a little bit confusing this exists to keep us from hurting ourselves because you have a concept called name collision this were a password or something crazy like that we wouldn't want to overwrite that and then screw something up somewhere else in the code okay now let's take this a bit further and we're going to say 4i in range and we're going to really make some people mad here because we're going to do some things we really should not be doing we're going to say x plus equals 1. now we're going to say y equals x times i so far everything's good but now this x you notice how we're three layers down which x is this really well this is the confusing bit so this x is actually borrowing from our definition it's going a bit higher so think of any time you see a def keyword we're actually putting some sort of wall or a shield here let's actually just draw a line so it's like we're setting a boundary right there saying you will not pass if i've already named that now let's go ahead and do something we probably should not be doing we have statement x statement y this is perfectly fine let's go ahead and run this and see what this looks like sure enough it's working as expected we can see that statement y is actually multiplying everything's working good now let's do something very very horrible we're going to grab these and we're going to go backwards through the scope vs code adds these beautiful little lines to tell us where in the scope we are you can actually see it's like a bubble here so we're at the global we're at the function we're at the statement now we're dropping back to the function scope let's run this and see what happens you notice how it does work and it's because we're in this little boundary here and it thinks it's a safe little playground for us to work at however you can definitely break some things and you can cause some issues i would strongly strongly advise against this future versions of python and even current versions of python you can run into some issues some name collisions and you can break your code now let's go ahead and take this same concept here and try to go backwards still and let's go back up to the global scope so we want to see x and y we've defined y here and we're able to go backwards into the function scope let's see if we can go backwards up to the global scope and sure enough we cannot name error y is not defined why are we getting this what's going on here this definition is a block of code it's its own individual little scope and i've got these arrows here global goes to function function goes to statement you should not go backwards however we've seen you can violate that principle and go backwards even though we really shouldn't be able to or i should say you don't want to because you can cause problems because if you take that logic and try to go backwards all the way up to the global you're going to get a name error y simply does not exist out on the global namespace you need to be a little bit careful when you're working with scope and really wrap your brain around this that will cause problems time and time again i see people constantly doing this going well i defined why why can't i use it and then you have to explain scope to them let's run that again and everything runs beautifully because we've commented this code out now all this talk about scope and functions and all that can get a little bit confusing so one thing you need to really understand is that functions do not share scope with each other let's go ahead and test this out so i'm gonna say cats better name i like cats so i'm going to make a variable called z and i'm going to make this one now what you need to understand i mean really really pound into your brain as this only exists in this function let's grab literally that function make another one and let's call it dogs now z is three what have we done here you see two different functions with two different z's these are individuals they are not the same variable and they cannot talk to each other so for example if i do something like this what's going to happen well we're going to call cats we're going to call dogs and then we're going to get some sort of undefined error and visual studio code is already smart enough to know it's not defined because these only exist up here now to kind of pound that in here let's grab this let's get rid of these guys now we've commented this out let's save that what's going to happen if we call dogs right now let's go ahead and say notice how it's already going uh oh you're going to have an undefined variable and let's test that so sure enough print z name z not defined remember when you see not defined it means it simply doesn't exist even if we were to call cats see does not exist so they do not share scope with each other if you're ever confused about this just simply take your ide and you can collapse the code down if your ide allows it and that's what we're talking about these are individual islands they don't talk to each other at all now to wrap this up you may be asking yourself if functions do not share scope how do you share information between functions well functions can return values and we've talked about this a little bit here so let's go ahead and generate some lucky numbers i'm going to say define a function called numbers and we want actually a parameter of steps let's go ahead and we're going to say l equal range and then we want to go from 1 to 20 using the steps there we go go ahead and print these out we're going to say 4inl and we're going to go ahead and print i this is just so we can see on the screen what's going on now we're going to drop back down and we're going to say return and we want to return that little list that we got from this range here so what's going on under the hood we're saying define this function who has a parameter of steps we're going to say l is range 1 to 20 using steps i to l so we're just going to print those out and then we're going to actually return all of this information we generated now a real word program would have vastly more complex logic but now we're going to use that function and get the information out of it so we're going to make the lotto function everybody wants to win the lotto i know i do and we're going to say z equal and we're going to call that numbers function with a step of 3. you may be going now wait a minute numbers doesn't exist we can't use it if you're ever confused and your ide allows it collapse the code down you can see numbers exist on the global scope therefore we can call it we're going down not up all right so now that we have this we can say four x and z let's go ahead and print out our lucky numbers we're just going to print that out now let's go ahead and call our lotto function notice how we're not calling numbers directly we're calling lotto and lotto is going to call numbers run that code and return the value get the return value and then use it see there's our lucky numbers major takeaway from this we've talked about scope and we've talked about it in depth scope can be a little bit confusing but just remember it's going to go from global to function to statement you should not go backwards and if you do you're probably going to run into some sort of problem although you'll see people do this all the time in python and it drives me bonkers because they're going to eventually run into a problem if they haven't already and a function can call a function and you can get values from those functions and use them locally okay this video we're going to talk about functions in depth specifically we're talking about arguments and parameters and different ways of doing things for example you can have a function inside of a function that's crazy so let's dive in and take a look okay let's start off nice and simple we're talking about no arguments no parameters we're just going to do what we've done before just so we can have a good base to start with we've done this multiple times by now so we're going to just print this out and we're going to say normal function this is kind of our starting point here we're going to go on a little bit of a journey and what we're going to do is we're going to dive into the mouth of madness and just see how crazy this can get so we're now going to just call this you notice how i put this right here these are escape characters return line feed with some dashes and arguments we're going to break this up because we have a lot of output in this video and we want to be able to see what's happening here so i'm going to just copy and paste these as we go we're calling this function and it works as expected if any of this seems unclear at this point you need to stop watching this video and go watch the previous 16 videos to really wrap your head around what we're going to be talking about because we are going to null holds bar just dive right into the deep end let's take the training wheels off we're going to talk about positional and keyword arguments okay this is where it's going to get really confusing really fast so we're going to make a function called message we're going to say name message and then we want an age so we've got a couple different data types we're going to be working with pretty clearly it's going to be like a string string and an int so we're going to say print hello and then we want the name followed by the message you are and then however many years they tell us so fundamentally this doesn't seem like rocket science but we can start doing some really really crazy things so i'm going to just put that out there positional keyword arguments so when we run this we'll see the output broken up let's go ahead and say message and let's call this as you would expect it now what we're doing here is called positional you notice how there is name message and age those are the positions think of this like a list it's zero base so zero one two we don't have to give it an index it's smart enough to know what the index is but i'm gonna say brian let's say good morning and then let's give it an age let's say i'm 22 boy i wish i was 22 i'm really not and that's positional go ahead and run this and we'll see sure enough hello brian good morning you are 22 years old so it looks great let's grab this and let's play around with it a little bit here we're going to use positional but we're going to use the wrong order let's go ahead and screw this up so i'm going to say 22 and good morning so really what we're doing is we're switching these around here the output suddenly makes no sense hello brian 22 you are good morning years old that makes absolutely no sense it's like a a serial killer wrote that or something all right so what we've done here is positional and we've screwed up the order so how do we fix that we use what's called keywords so we're going to do the same thing we're going to say message and here we're going to say msg equals you can see this in visual studio code it's got that parenthesis and little bitty block there it's smart enough to know that we are trying to call the parameter message with the argument of good morning now you notice right off the bat we are completely disregarding the order because message is well the second one and we're giving it first as you're about to see it really does not matter say age equals say 46 and then name equals brian let's go and run this and sure enough it says hello brian good morning you are 46 years old so now it's working as expected we don't have to give it a specific order we are working with e-words and i wish they would have called this parameter arguments or something like that but basically it's keywords so what's happening is python is taking these parameters here and turning them under the hood to keywords and it has some sort of internal list and it's saying hey if you give me a keyword and pump it in there it will just magically know how to line those up and what order they need to go into you can also do both so let's just grab this guy let's grab this and say brian and then let's go ahead and flip these around so you can mix and match these as you want so you can say positional followed by keyword let's run that see it in action it doesn't matter which way you do it it just works extremely cool and i absolutely love that about python let's make this ever complex still we're going to talk about internal or inline functions and there is a subtle difference between internal and inline we're talking about an internal function which is essentially a function inside of a function so we're going to say counter and inside of counter we're going to immediately call another function or create another function called display we want to say count equals zero so really all we're doing is we're saying a function in a function and notice how it's smart enough to drop us down a line so it knows it has its own scope and we're just going to print this out and we're going to say internal that way we know i was going to do it something else but let's just say internal so we know where we are and then print that count out under the hood this is really complex but it's super simple the way we do it we just have a function we've defined another function that function gets its own little scope and we can now drop out here and say something like this four x in range say five nothing too drastic here let's go ahead and call our function display and we're going to call that with x so we're saying 4x in range so it's going to do that five times and it's going to say call display one one two three four five interesting how that works let's see this in action here a little bit of copy and paste action for my notes we're gonna talk about internal functions and we're gonna call the counter function sure enough zero one two three four i always forget that zero base always trips me up okay so what we're doing here is calling a function which has an internal function which is calling it internally and it's just kind of going around inside and doing all this madness for us so let's take this counter grab this internal function called display to try to call it so we're now going up a notch now let's just see if we can call this sure enough we cannot we get a name error display is not defined remember when you see is not defined that means python has no idea what this is because it does not exist in the scope we're working in so you guessed it collapse that down display doesn't exist it's inside of this scope over here it's super cool but it's also super confusing so if you're going to use this be very careful about how you try to call it or you're going to get some sort of error all right let's give you a nightmare scenario boss walks in you're a newbie python programmer and he says i want you to make a function but i'm not going to tell you how many arguments i'm going to give you i want your function to automatically figure it out well what we're talking about here are star args and star stands for wild card this is a positional variable length argument all right so what are we talking about positional well we've talked about this a little bit before up here where you have a position and that's not so much what we're talking about we're talking about this right here we're gonna say death and let's go multiply star args we could name this whatever we wanted now we're gonna feed that a bunch of arguments and they're going to be based in a position so let's go c equals one or num in args let's go ahead and print that out so we can see what's going on now we're just going to multiply that we're going to say z is multiplied by the number now let's go ahead and print this out a little bit of copy and paste action from my notes just so graphically in the output we can see where we are let's go ahead and call this i'm going to say multiply or multiple actually and we're going to say boss gives us three numbers here number one number two number three this is what i mean by positional it's going to take the exact order we give it one two three we could switch this around and say two three one and you'll see the position changes two three one all right very very simple very easy to wrap your head around the major takeaway here is we're not constrained we can take this out to just some ridiculous level we could do something like this see works as expected let's take that same nightmare scenario where our boss is just a complete jerk and we're going to say okay he's going to come in and say i'm going to give you random information i'm not going to tell you how much information may give you and i'm not going to give it to you in a specific order yes that's a nightmare so we're talking about is keyword args which is basically the same thing except for instead of positional we're using a keyword we've talked about keywords before way back up here how we can mix and match and do all this other cool stuff but we're going to try and dumb this down and make it a little bit simple because yes this can get complex fast major thing to note is there are two asterisks here two stars so let's go ahead and say def profile this is what the boss is going to do to us he's going to say i'm going to give you a person the person is just going to be a bunch of data and you need to figure out what to do with it so we're going to print out our person now let's jump out of there for just a moment here and i'm going to say add our little delimiter here so we know we are in our output and let's go ahead and call this so i'm going to say profile now it's smart enough to know it's using keyword args so it gives us that double asterisk and now it's on us to define what information we're going to get and i'm just going to say name and if you're wondering where i'm getting name from i'm literally just randomly grabbing something out of my mind it doesn't matter what we give it here so we'll say brian and then let's go ahead and say age equals 46. let's run this and see what happens we're printing out this person so notice it's now converting that into a dictionary that's right so now we can just use this like a dictionary it's extremely cool the way this works all right let's go ahead and use an internal function i'm going to say f display let's go ahead and display k now we're going to do a little bit of test here we've covered this in our dictionary video here where we'll say if k is in the person keys then we want to print this out and if that's super confusing i would highly encourage you to go back in the playlist and watch the video where we cover dictionaries so now we can just work with this dictionary directly so we have a function in a function this internal function display is just going to say if this keyword is in person keys because remember it's converting it to a dictionary then go ahead and print out the key and print out the value now that we have our little internal function let's go ahead and call it so i'm going to say display and let's give it a keyword name now notice how we're actually hard coding this you can do different things like this so i'm going to say name age and we were in a meeting and they were talking about adding a pet but they didn't actually do it yet which is why we're saying if the keywords in the keys because we've done this if we don't have to worry about not defined it's going to print out name age okay someone in marketing comes back goes wouldn't it be really really cool if they had a pet let's go ahead and add that in there now you can see brian 46 and cat and we have our two different calls here so we have the first one that does not have the pet and the second one which does have the pet and it just works the way you would expect it to and we can now test this for other things so for example let's say food equals pizza what have we done here well we've added a keyword that we're not using it does not crash our application because it's saying if it's in there and we haven't even called it so let's do the opposite here let's go here and let's say some as i don't know what that is we're just scooping around doesn't crash because it's not in there very cool very easy the way this works super simple to wrap your brain around but what we're really trying to drive home here is these are keyword arguments not positional the position simply does not matter okay let's wrap this up with a brief conversation about lambda or anonymous functions you're going to hear them called lambda functions they're actually not lambda functions they're anonymous functions we use lambda to create an anonymous function so let's go ahead and define this real quick here so first things first we're going to make a normal one just as a point of reference so i'm going to say f and let's call this make sqxt so we're making the square footage we're going to say the width the default and the height with the default and we're just going to return the width is height so we're just really getting the square footage here super simple super easy to understand go ahead and print this out i'm gonna say print actually i'm going to pause for just a second and we're going to add in our little delimiter here so we can see it in the output all right back to what we're working on here we are going to print out the square footage and let's go ahead and do this both ways we can say width equals trying to think of a good number here 10 the height anybody out in the audience anybody anybody let's call it eight why not we can also just say print and then make the square footage and let's say 15 by eight we can call it both ways go ahead and run that you see there's our numbers now let's use the lambda keyword to create an anonymous function i intentionally called it a lambda function even though they're anonymous functions because you're going to hear people say well i'm going to create a lambda function we're actually using the lambda keyword sqft equals so what are we doing here we're making a variable we're going to say lambda and let's go ahead and define some things now i want to kind of slow way down and plop a note in here there's a certain format we have to do this in so we have a variable the lambda keyword a list of one or more variables and then some code so we're saying lambda let's go ahead and say width equals and let's say zero height equals zero colon and now we're gonna our code so if you're looking at this really what we're doing is we're saying lambda is going to replace all of this then we have our information and i specifically named these the same so you could see them highlighted on the screen let's do that again so now we have our parameters now we have our code now if we wanted to we could just grab these and through the magic of copy and paste instead of a function call to make square footage we're gonna just call this variable sqft and it functions exactly the same see 8120 8120 this is just witchcraft i mean this is like voodoo magic from old school programmers like me but uh so what's really going on under the hood is when you call lambda python is basically making this but it's doing it all in one line so as a programmer it makes your life a little bit easier because it's all on one line and you just have to remember this variable name and it exists out in the global scope so we can treat it just like a function if we mouse over this you see it's smart enough to know that it is a call to lambda so it is making an anonymous function i personally am not a huge fan of anonymous functions but they do have their place on the programming world especially if you get into like gui programming and socket programming and things like that you'll see people use these very heavily some people love them some people hate them i personal my personal preference is i like to actually define what i'm going to use rather than relying on some crazy witchcraft but i don't want to steer you away from this lambda it's very powerful and very useful welcome back everyone this is brian we're going to talk about packing and unpacking data now what are we really talking about here well we have a problem with arg and keyword arg is that we cannot easily use lists sets tuples and dictionaries instead we have to pack and unpack the data and that's what this video is really going to dive into let's take a look so let's look at packing data and this sounds like it's going to be super complex but actually in the spirit of python it's super super easy so i'm just going to make a function called pac and we're going to make a parameter here called nuns and this is a star arg right here which means one or more variables and in here we're going to say go ahead and print this out just so we can see what we're actually getting now let's go ahead and call this back and i want to pack one two and three let's see what's actually going on here sure enough it has made a tuple from here we can very easily say or x in nums and then do something like this get those individual numbers out of there and see exactly what's going on inside the tuple super super simple to wrap your head around this works as expected however there are some issues here and let's go ahead and take a look at how we would unpack the data okay packing data is well simple and we've done this before but what if we try to do the opposite and unpack the data what are we really talking about here unpacking so let's go ahead and make an example and say f unpack and let's give it three variables a b and c from here i'm just going to print out unpack that way we can see what's going on followed by print and we can just grab those directly super simple probably the simplest function we'll ever write say bc and of course line those up u b and c just looking at that function it's pretty straightforward pretty obvious what's going to happen but now let's introduce a problem i'm going to say num equal and i want to make a list of numbers 1 comma 2 comma 3. if we say unpack just give it our variable what do you think's going to happen well intellisense is already telling us there's going to be a problem here no value for argument and it says uh oh see missing two required optional i'm sorry positional arguments b and c wait what but i gave it a list there's three elements in this list what's really going on well what's happening is we have to tell python specifically take this list and unpack it and we do that just by adding a star right here let's try that again i'm going to clear this out and now it magically works so what we're driving home here is when you see this asterisk this little star no matter what contest with whether you're using args or keyword args or you're using up here as a parameter or you're using it as an argument think of this as telling python you're going to be packing or unpacking data and python i want you to take care of all the messy details so i don't have to as with everything programming related it's not that simple let's look at another issue the dictionary issue let's go ahead and make a dictionary so i'm going to say d equals dictionary and i'm going to say name equals brian age equals 46 and h equals cat feel free to put in whatever values you want you just need a dictionary with three elements now let's go ahead and say print and say packing dictionary let's go ahead and try to pack this so we're going to call our pack function and we're smart enough to know now that we need to put that asterisk there because we're going to tell python you deal with the details and we're going to put our dictionary there go ahead and clear out our results down here and see what happens uh oh we've got a problem it's only getting the keys it did get the key successfully but it's only getting the keys remember a dictionary is a key value pair so ah that is frustrating let's try the opposite let's try to unpack that and let's go ahead and say unpacking handy little function name right there and run again unpack and again abc it's only getting the keys so you're absolutely right we have to do it a special way for dictionaries let's take a look looking at the dictionary issue how it's only getting the keys we have to treat this special so we are going to look at an example of how to pack a dictionary now when you say pack a dictionary i get this image of putting a dictionary in your backpack and going off to school and that's kind of what we're doing here so we're going to say define pack a dictionary and let's go ahead and say we want to do asterisk asterisks numbs notice the double asterisks asterisk stands for wild card so we're telling it we're going to get two things and if this looks eerily familiar it's because we're talking about you guessed it keyword args a dictionary is nothing more than a key value pair so this is exactly what we're talking about keyword args let's go ahead and say print and let's actually print this out i want to see what we're being fed here from python lan nums equals and then let's just print this out now let's go ahead and call this and i want to say let's go ahead and feed it some arbitrary data just make up whatever you want as long as you've got three values it doesn't really care i'm just going to say name brian age equals 46 and pet equal hats run this and sure enough nums is equal to see these little squiggly lines a dictionary object so it's automatically done this for us basically under the hood what it's done is it's called the dick function and converted all those keyword arguments into a dictionary for us from here it is ridiculously simple to work with i'm just going to say print f and let's go ahead and say act and we want actually we're going to do a for loop instead of pulling these out one at a time 4k in nums last minute change of plans here there is our keyword and then we want to say equals and give it our key there we go say run let's see what this looks like sure enough act name age and pet works as expected as long as you have that double asterisks in there you now have access to the entire object as a dictionary just to wrap this whole thing up let's do the polar opposite we are now going to unpack a dictionary so let's go ahead and say def unpack dick and boy that's a funny name i'm probably gonna get some flack in the comments about that one but the name age and pet we're just gonna stick with that in a little paradigm there and let's go ahead and say print we're going to unpack a dictionary object here let's go ahead and say print and you guessed it it is just ridiculously simple to do this do the magic copy and paste i'm going to speed this up just a smidge all right now to call this well how would we actually go about calling this we have a dictionary object out there so let's go ahead and reuse that dictionary object in case you're wondering it's this guy right here and i'll actually just grab him and bring it right here just recreate the wheel it's already set but i'm gonna set it again just so we can see it on the screen and we're going to unpack that dictionary object because we're using a dictionary we need the double asterisks telling it hey we are working under the hood with keyword args and watch this thing in action so it's going to create a dictionary and then we are going to tell python unpack this into these see unpacking a dictionary name brian age 46 pet cats so this video seemingly simple we're actually doing a lot of work under the hood i should say python's doing all the work for us we are packing and unpacking data we've given examples on how to pack and unpack list sets and tuples and how to pack and unpack dictionary objects and some of the issues that arise okay functions and arguments functions are really cool but wouldn't it be cooler if you could use a function in a function's argument what do we mean by that so let's say we were going to do something like this def test and then in here we would do something like death test 2 or test 1 or whatever we wanted to do not exactly how we're going to do it but yes we are going to use functions as arguments let's dive in and take a look let's dive right in here we're going to look at a function in an argument it sounds a little squirrely but let's take a look here so i'm going to say test and we're going to have some parameters here i'm going to say name age and patch we've seen that kind of before in previous video go ahead and print these out some say print do the match copy and paste we can speed this process up just a little bit this can be a super super simple little function here so we're just going to print out name age pet there was vastly easier ways we could have done that but i just want to really print that out one line at a time using the information we've learned so far so from here we're going to make another function called get data and this is pretty common not just in python but pretty much every programming language out there where you'll have one function that returns some type of data and another function that actually does something with the data so here we're going to return a dictionary using the well same kind of data pattern here so i'm going to say brian in or whatever age you want i won't tell anybody if you enter you know something much younger or older if you're into that i don't know so just going to return a dictionary of name age and pet now we have some fundamental problems here for example how do we actually use these two together well there's the standard way as i call it which you would just call this stand alone get data but now you have to feed it in like this test and you have to do this really long annoying you got to get the order right and all this other fun stuff which is really not that fun at all and you could do that all day long and of course if you change one thing you've got to change everything else and it becomes just a royal nightmare but it does work you know we did look at an easier way with packing data or unpacking data i should say and we're going to say test and now we're going to call getdata but there's a fundamental problem here if we call it like this we're actually calling that function we are returning a dictionary but now we need to unpack it example if i just run it it's going to say missing two required positional arguments agent pet so now let's just go ahead and tell python to unpack that save and run now it works and it's very simple very easy you can do it all in one line super cool the way that works okay so we're going to cover something a little different it's a function as an argument we've already covered a function in an argument right here where we said test and then we called get data with these parentheses and we had to unpack it and we've got all these special characters in the special order that we got to get just right or nothing works we're going to do something a little bit easier i'm going to say def and i need a good name let's call it monkey why not i don't know what name to give it so we're going to call it funky and we're going to have a variable called data so far everything's very abstract nothing's really defined we just have a variable called data and we're going to make another variable called d and it's going to be the result of data notice how data is being called like a function even though it's also a variable um other languages you'd call that like a function pointer but basically what's going on is we're saying grab some function and then call it doesn't matter what we name it we could name this kittens and then d is going to be the result of kittens the name really isn't matter what matters is we are going to call this as a function and python is smart enough to know hey that variable is a function pointer under the hood do something with it so i'm going to go ahead and print out d now to do this i'm going to say funky and we're going to reuse our get data function from up here which is just going to return a dictionary object so here is the important bit i'm going to just say this notice there's no stars there's no extra parameters it doesn't look like this it's just the word get data and i'm actually put a special note right there let's go ahead and run this see what it looks like so this is the result right here it is our dictionary and in case we are just super super concerned with that we can say e equals and then d save run just to verify d equals blah blah blah so what's going on under the hood here is we are saying our function is going to have a variable and we're going to take that variable and now treat it like a function and python's smart enough to go out and say okay funky is getting this guy right here and we're now converting that to an argument for our function that is extremely cool as long as everything just works we can then go ahead and do something like this we'll say print and we can do this a number of different ways i'm going to do it the long way just because why not and let's go ahead and go d and we got to worry about those single double quote issues again there are other ways of doing this age in case you're wondering where i'm getting these and typing it horribly it's actually from our dictionary object up here so i know we have a name and age and then a pet so let's go ahead and grab the pet too could have done this a number of different ways we could have done for loop we could have you know tested to see if it was actually in the dictionary keys grab the item however we wanted to do it and ta-da just works main takeaway from here is we can actually use a function as an argument and then use that variable as a function very cool the way that works welcome back everyone my name is brian we're going to continue our journey into python 3 with the global keyword this is extremely cool it's extremely easy and it solves a complex problem for example we've seen this code before x is one we have a function x is six if we run this what's going to happen well let's find out so we have six and one basically x is two different variables and they're being treated different because it's two different scopes remember whenever you're defining a function you're actually defining a scope so what the global keyword allows us to do is actually modify variables at well you guessed it the global scope let's dive in and take a look okay in case you skipped that video on scope what we're really diving into here is well blocks of code we're defining a function which has its own scope the problem is python is lexically or statically scoped which means if we run this we have two different variables however this is frustrating if you comment this out it's going to access the global scope so what we want to do is to be able to access and modify and that's what the global keyword does so first things first now that we understand that basic premise let's go ahead and test this code sure enough one one we can access at a higher scope let's figure out how to modify let's go ahead and make a global variable that's it it's really that easy just because we put it on this very first line there's no padding this is just right at the edge of the file here that is now considered in the global scope let's take a look at the scope issues in depth here so let's say scope issues and let's make a function called count which is going to have some type of maximum number that we're going to count to now without the global keyword python is going to get very very confused very very fast let's go and demonstrate that so i'm going to say counter equals actually let's do plus equals we're just going to increment this right off the bat here and sometimes python will let you do it sometimes it's not other times it's going to just completely freak out and not have a clue what you're doing but before we even run this you can see right now it's saying undefined variable counter and this is perplexing because it's literally right here so remember our conversation we're accessing it but now it's suddenly saying it's not defined oh that is frustrating let's go ahead and try and run that so let's say count and let's just try to count to one just to see what happens here uh oh unbound local variable local error sorry local variable counter reference before assignment referenced before assignment really is our clue as to what's going on here what it's saying is it is now making a new variable and then trying to increment it before we've actually assigned it so remember python types are a little bit well a mystery we don't know if that's a string a bull actually as soon as it's created it's an undefined so if you take undefined and you try to add one to it what is the expected behavior remember undefined is not zero it's just simply there's nothing literally nothing it has no idea what type it is so python is going to get super confused super super fast now let's just continue on with typing away here just to see how bad this can get we're going to say counter is greater than or equal to the max then let's just go ahead and return false otherwise we're just going to return true see same problem so right here it thinks it's just fine it actually knows it's an integer but right here it's saying it's undefined this is what i mean by python gets very confused very very quickly oh that is frustrating so we're going to fix this problem by saying global counter and notice it's got the exact same name so really what we're doing is we're saying use the global variable called counter give it this same name here save that and as soon as you save it you notice intellisense is smart enough to know that hey this is actually defined now and we can start working with it and it knows it's an integer let's go ahead and just see the global keyword in action here i'm going to make a variable called limit it's going to be 5 and i want to increment our counter using that so i'm going to say 4x in range i'm going to use our limit go ahead and get a variable from that function using that limit let's go ahead and print it out and print out our counter and just for giggles let's go ahead and print out just done so we can see it actually worked go ahead and run sure enough boom done so it's working as expected now and it's all because of this simple little keyword right here now standard practice i tend to avoid modifying global variables inside of a function for this very reason for example let's just say i were to grab this and make an entire new function out of it and i go huh i don't need that global i just want a variable called counter now i don't need that now suddenly you guessed it we are right back to the exact same issue so now it gets very confusing about which counter we're talking about and in which function you can very easily fix it by just doing this but then of course now you're going back to modifying a global variable which is not really a good programming practice when in doubt we're going to have a conversation about encapsulation later but you want to encapsulate or use pretty much everything internal to your scope without going out modifying other scopes welcome back everyone in this video we're going to talk about the walrus operator the what that's right the walrus operator it's funny name and it gets it from the syntax it's colon equal and if you look at it like if you like your head sideways it kind of looks like a walrus it's got the little eyes and the tusk and everything that's where it gets its name this is a little bit confusing and this might hurt your brain a little bit and to make it even more complex you have to have the right version this isn't available in python until python 3.8 or higher but what the walrus operator allows us to do is assign a variable from an expression meaning we're going to take some chunk of code and turn the end result of that code into a variable without having to do a whole lot of complex stuff in case you're wondering about versioning remember if you pull up a terminal and there's different ways of doing this you can see down in the corner i'm using python369 there are different versions installed so for example if i type python that's two seven if i type python3 my system's at three six nine so that's not going to work i would have to do three 3.8 i have 3.86 just use whatever you have if you don't have 3.8 or higher installed this will not work and you'll have to go out to python's website and download and install and configure python 3.8 or higher follow the instructions for your operating system google is your best friend if you have a problem or you can visit me in the voidromes facebook group there's details at the end of this video for our purposes here we're just going to go down here and we're going to select python 3 and then select the correct workspace which should be python 3.8 or higher and suddenly everything starts popping up and saying do you want to install this do you want to install that i'm not going to do any of that for this video i'm going to apologize if it keeps popping up though let's dive in let's look at some common issues and i put the parentheses here for a reason because that's going to be your biggest issue when working with the walrus operator for example if i say y and then walrus i'm just going to say walrus len of hello what do you think we're doing here well let's try and print y out uh oh i get no graphical error in the ide because well there's really no pylinter installed i can install kite or something else like that but i just wanted to switch versions and see this thing work and it's saying syntax error invalid syntax what do you mean invalid syntax i'm using the walrus operator and i've got the right version of python this is what i'm talking about let's just grab this guy right here and let's just put that same thing inside of parentheses here and i'm going to put some notes at the end here just for anybody who downloads the code so they know what's going on let's comment this bad boy out put that at the end there didn't i there we go and let's rerun this now suddenly we get the output len 5 it's valid but according to python's website it's not recommended why because it's just confusing to look at what is going on here it's almost like we're calling a function remember in programming and in math anything inside of the parentheses is pretty much done first so what we're really telling python is as you're reading this stop what you're doing brunch all this stuff between these parentheses and then replace all that parentheses with the value which is five so it's just going to really make a variable called five seems confusing and it is nine times out of ten that's going to be your biggest issue it's just you forget to put something in the parentheses so let's go ahead and look at another real world example here i'm gonna say people equals and we're gonna make a list of people so me my wife and family dog big old stinky dumb dog he's probably down there wanting a treat right now but he's not getting one because i'm up here making a video or dog so i'm gonna say if and walrus len and we're going to just get the length of that variable right there and i want to just say less than or equal to 3 then go ahead and print it out we're going to print out n little confusing but what's going on here i'm saying n is walrus or equal to this expression the length of people which in this case should be three because i have three elements we're saying if it's less than or equal to three go ahead and print it out but when we run this we have been betrayed it actually says to what come on why is it true why because we forgot the parentheses let's just take the same thing and let's just go ahead and wrap it in parentheses here re-run it and sure enough we get three so nine times out of ten if you have a problem with the walrus operator it's because you're missing your parentheses i am not a fan of introducing new concepts without some sort of example so let's make this super short but super confusing because the walrus operator is confusing all right so i'm going to say lines equals and we're just going to make a list and we're going to use a function called can add with a maximum of five that's the default which is going to determine whether or not we can add to that list and we're going to say global lines i don't like doing this because what we're saying is now we can modify this but i want to make sure python knows we want this list we're not creating some new variable that gets a little bit cumbersome not a fan doing that when in doubt you should actually send it as a parameter argument let's work with the walrus operator let's unleash our inner walrus i'm going to say allowed equals and notice how allowed is not defined so what we're doing is we're letting the walrus operator define this variable so if you're worried you're going to get an undefined error don't worry it's not going to happen but whenever you see walrus think the walrus needs to open his mouth you should see these parentheses if you don't you're going to have a bad time let's go ahead and say this is going to be the count and again walrus operator so we need some sort of parentheses but we're going to use a function len we're just going to get the length of those lines now we're going to say we want the max and that looks really crazy and confusing but what are we doing here we're creating one two variables and we're saying allowed is going to be this code expression here oops if my mouse ever wants to cooperate this code expression here and count is going to be this code expression here whenever you see these parentheses you are working with some sort of expression or scope but usually both let's go ahead and print and we're going to say f you can enter and we want the max the account more so we want to tell the user in real time how many more they can actually enter we're going to drop back down and say return and we're going to just return whether or not this was even allowed that looks super confusing but the whole point of the walrus operator is we've reduced code we now have a variable that got assigned an expression we didn't have to say something like allowed equals something something something and then put the allowed in the if it just automatically does all of it for us to further make this confusing let's do something that i see people doing all the time i'm going to say while and then a function is going to return a bull and we're just going to loop until that function says we can't do it anymore say lines go ahead and append that and we're going to make another variable called l and we're going to get the input from the user whoa that's crazy all right so we are making yet a third variable here and let's go ahead and just print out that we're done okay highlight the walrus operator you can see just in our little example here we are creating one two three variables whenever you see walrus think immediately to the left is what we're creating immediately to the right whatever's in the walruses mouth is what we're using to create it kind of crazy so if allowed and the count less than max then we're going to go ahead and get the max minus the count blah blah like it's super confusing we're going to return a bull we're going to use that bull and then we're going to get this value from the input all in one line really really reduces our code but it also makes it a little bit harder to read so i'm going to say i'm just going to enter some stuff one we can enter four more three more two more one more and boom you entered and it gives us our nice neat little list major takeaway here walrus operator is super convenient but can be super super confusing whenever you see the walrus operator think immediately under the tusk you need the mouth which are these parentheses and then whatever's in the parenthesis is going to get assigned to the variable because you're really taking an expression and putting it into a variable you also need python 3.8 or higher or you're going to get a whole lot of crazy errors because earlier versions of python have no idea what you're talking about that in a nutshell is the walrus operator welcome back everyone this is brian we're going to talk about navigating folders in python 3. now before we begin spoiler alert there are multiple ways to do something and this is true in every programming language on every computer operating system basically as computers of all so do the programming languages and platforms that people use to create programs they get infinitely more complex behind the scenes and infinitely easier to use up front but they also hide a lot of that complexity which leads to a lot of confusion especially newbies because they say what's the best way to do something the short answer is there isn't one use what works for you we're going to cover a few situations but you're going to see people even in the comments down below say why are you using that way use this other way instead again refer back to the golden rule use what works for you let's dive in and take a look first things first what we're going to do is import a module you may be going now wait a minute i thought we're going to work with navigating folders we'll understand that folders are part of the file system and it can get very very complex and a lot of this is baked right into the core of python but we need to work with someone else's code and some of these the ones we're going to work with are already baked into python we just need to tell python we want to use them so we're going to import the os module in case you're wondering what a module is it is a group of code that we can use someone else has already written this code we can just simply use it however we want so first things first import os so we're importing a module once that module is imported we can start working with it so i'm going to just make a variable called d shorthand for directory and i'm gonna say os dot get current working directory in case you're wondering what that is every single application runs inside of a directory every single one of them they are a file on your system somewhere that file lives inside of a directory if you're on like a linux or unix or mac it's in what's called root which looks like that it's just a slash if you're in windows land it's going to look something like that now that is the root of the os but chances are you're not actually in the route you're buried down deep in the os somewhere so let's figure out where we're actually at so i'm going to say print and let's go ahead and format that and i'm going to say current we just want to know where the heck we are in the os sometimes this could be like you know navigating the deep blue c or something we just don't know where we are so we're going to get that current working directory or we can just use our variable which we've already pulled out i have to put this is the current directory does not mean that every single program runs in this directory it just means what our program is running in all the other programs are running in different directories or even in the same directory it can be either or it's super confusing all right on my little virtual machine we are currently in slash home slash root shell just the account that i'm on here slash code slash python3 so you can see we're not in the root we are in a subfolder several levels down so let's say just for example we don't really like this folder we just want to work with a different folder just to see if we can do it so let's go ahead and change folders so i'm going to say os dot ch der which stands for change dir change directory so get cwd is get the current working directory we're going to ch stir or change directory seems a little confusing to get the terminology down now you can actually hard code this like let's say we could home bob's files something something or if you're on windows it would be like c wackwack you know whatever you wanted or you can use what's called the current path which means you don't have any sort of pathing in there again a little bit advanced and i'm just going to do dot dot if you're wondering what that means that dot dot it actually stands for your current directory and its parent so we're actually going up two levels sounds a little confusing but let's take a look here i'm going to just grab some code here we're going to print the current and we're going to say os get current working directory notice how we're not reaching d and i'm going to just grab that for future reference here let's run this and we've gone up a notch so we were in python three now we're in code so we just simply jumped up to the parent so when you see dot dot that's really all we're doing is jumping up a level now we're going to reuse this variable here and i'm going to say os dot ch dir and we're going to jump back to that string representation of that directory grab that paste it clear this out just for good measure and run so we went from python 3 up to the parent and then back to python 3. so python 3 up to the parent and back to python 3. navigating the folder structures is very very simple if you know the path it's just ridiculous simple but you just hand it a string and boom it just goes now that's assuming it actually exists we're going to cover what to do if it doesn't exist in a future video but just know that if you try to give it something that doesn't exist you're going to have a very bad time remember when i started this video i basically said there are multiple ways to do the same thing we're going to start looking at some of those the first one is list der and this is probably the easiest way to do it so we're going to say 4f in os remember that import that we added and we're going to anybody drum roll lister there you go this is a function so we have to have our parentheses and we can specify directory we can use the current now if we just print this out let's just go ahead and print and see what this does here not a whole lot here it's just got one file plus this little dot vs code dot vs code is this folder right here which has another file in it so we're getting folders and files and if you've got a lot of files in your directory you're going to see them all interesting so how do we actually determine what each one is and let's pretty this up a little bit notice how this is just python 3-22 just the name of the script but we don't get the full path let's go ahead and say print let's format that path and this is where people in the comments below are going to start arguing with each other i'm going to say os path and i want to get the abs or the absolute path this is going to tell us the absolute path that file someone down below is probably going to say why aren't you using real file or something of that nature again personal preference this is what i want let's go ahead and run that uh-oh that's now oh the sensitivity has come back to bite me there we go so now it is working as we expect path and that's giving the full path not just the name of the file so that's the difference here is we've got the file name and then we've got the absolute path here let's go ahead and make this a little bit more complex i'm going to say if and i want os dot path and let's make sure it is a directory then we're just going to print this out and we can take this same pattern and just repeat it so we're going to say if it's a directory just print dir and then whatever it is and then if it is a file it's going to go ahead and print file or whatever it is and let's add one more just for giggles is link you're wondering what a link is it's a special kind of symbol out there in file land which basically says i'm not the right one go to this other location it literally just points to another location you could call them shortcuts or symbolic links it really depends on your operating system notice how this will always return faults for windows prior to 6.0 because windows before 6.0 did not have symbolic links and you may be wondering what's windows 6 did we ever get an advertisement for windows 6 it's just the way windows does versioning microsoft's just kind of dumb sometimes but basically if you've got an older version of windows that's just not going to ever return true let's go ahead save run and you can see that our path it is a file and then our path and have and it is a directory so it's working as expected and we can now determine whether it's a file or directory and we can get the absolute path so lister along with os.path is actually pretty complex and does most of what you may actually need it to do rewind the video a little bit and you'll remember i said hey as computers get more complex the code gets easier but details get kind of murky and this is a perfect example this scander this appears in python 3.5 or higher we've been using lister and you may be asking yourself why do we need scanner lister seems to do just about everything we'd want it to do well skander the big selling point for this is it encapsulated in a class and it is faster although i will just say it unless you're doing some high-end coding you're really not going to see a massive performance boost and you may be scratching your head wondering why you're working with it but when in doubt let's just dive in here and i'm gonna say skander and let's go ahead and print this out notice how i have e in there when i run this you're about to see something magical happen ta-da it says dirt entry and then the name so what does this mean this is a weird little syntax whenever you see something encapsulated in brackets like that it means that python is handing us a class and we're going to talk about classes in a future video but right now major leap of faith a class is just simply a custom data type it's really a blueprint for an object that someone else has defined we're going to learn how to build our own classes and blueprints in the near future but right now all you really need to understand is we have a custom data type called a der entry and we just say data types we're talking about things like strings numbers lists and things like that their entry is just another data type let's go ahead and work with this a little bit here we're going to say print and this is what i mean by you get lost in the complexity a little bit here we're kind of scratching our head figuring out what we would need to print out so you have to actually go out and read the docs or watch the rest of this video go ahead and say name i'm going to say e dot and we want the name go ahead and get the path here so i'm going to grab this so the whole purpose of this is to make life a little bit easier but at the same time scandal does work faster than lister and ta-da it works now name path let's go ahead and run a little bit of an issue now when i say run a little bit of an issue we want to get the directory the file and the symbolic link the bulls kind of how we did before so i'm going to grab this and this is where it's going to get a little mind bending here so if i say e dot is der is file is symbolic link you think it's pretty straightforward you go okay let's try this but what we're doing under the hood is subtly creating an issue and i'm wondering if anybody out there can really spot this let's go ahead and grab this name here now that we've done a little bit of surgery pop quiz can anybody spot the issue raise your hand so what's going on here dirt entry dot vs code we said dot vs code is actually a directory see there it is right there but it is printing out dir file and link wait it can't be all three at once what's going on here is we're actually calling a function or at least we should be i wanted to demonstrate that because somebody out there is going to run into that issue where they forget to put the parentheses and then they have some weird results run that again and you see now it works as expected but it never actually threw any kind of error that's the confusing part so if you ever get some weird kind of results out of scandal just make sure you got those parentheses there okay well let's go ahead and cover glob and i put glob multiple ways because so far we've covered two other ways to do it blob represents a third way and blob although it sounds gross it's actually really cool in short use what's right for you we're covering glob because of this and i put the link here typical stack overflow question which is how do i scan all folders and subfolders or aka a recursive scan and if you're kind of wrapping your head around whatever cursive scan is we're in this python 3 folder we're going to jump up to the parent here and i want to know the contents of all of these folders and if one of these folders has a folder in it i want to go into that folder and so on and so on and we're just going to do a recursive scan now in some languages and frameworks this is not for the faint of heart but glob makes it ridiculously simple so first thing we need to do is we need to import bob i don't know why you'd want a glob but anyways i wish they'd picked a better name for that so we're going to change our directory and we're going to go up to that parent so we're going to go a directory higher now i'm going to say there i'm going to make a variable here this is going to be os and we're going to get the current i'll say get current working directory now we're gonna actually work with glob and i'm gonna say four file name and glob and blobs gonna get really confusing and we're not going to like deep dive into all of the parts of glob but know that you can do a bunch of different things with clap we're really just scratching the surface so we're going to say glob glob sounds like you're talking to a drunk person in a bar glob glob anyways so blob we want to give it a path name we're going to have intellisense help us here so path name i'm going to say is equal to our directory and we're going to give some wild cards here we need to tell glob what to do i'm gonna say anything followed by anything whenever you see star that's our wild card and then we want recursive equals true so we're telling glob not just this directory but all the directories inside of it go ahead and do your magic let's go ahead and print that out with formatted i want to glob this out like stuck in my head now glob anyways you know there was probably like a bunch of programmers sitting around a room going we made this really awesome thing what do we call it let's call it glob and then they kind of took that seriously there you go so glob has gotten a lot of stuff you can see i've got other code from other projects in there including c plus files make files text files other python scripts that i've worked on things like that so blob has gone through and read the contents of all of those now to kind of show that there are multiple ways to do this let's go ahead and do it yet a different way so i'm going to say four let's go current path folders and files in os our good old buddy os dot walk and basically we're going to tell os to go take a walk in our current directory now remember dot dot is the parent dot is the current so we're just going to say os walk the current directory and i'm going to go ahead and say for file in files this is not so much a recursive scan but it gives you a little bit of detail here let's say go ahead and print let's go ahead and work with these i'm going to say os.path dot join so what we're going to do is we're going to join all of this up we want to know the current path and the file and if you're kind of confused about where i got current path and file it's right up here so really what os walk is doing is returning i believe it's a tuple and then we're just pulling those elements out of there and then using os path join to join all that up and make it look something like this pretty interesting pretty easy to understand so to summarize there are well multiple ways to do virtually the same thing each one has its own little pros and cons and little gotchas and different ways of doing it use what's right for you this video covered how to change folders lister scanner glob along with os walk and you're going to see all those out in other people's code and we were talking about recursive and that has its own set of complexities which we're also going to cover in future videos this is the beginner's guide and we're just scratching the surface of what we can do welcome back everyone this is brian we're going to talk about reading a text file the main takeaway from this is it is easy anybody can do it so if you're intimidated with the file system do not worry this is super ridiculously simple let's dive in and take a look first things first let's go ahead and get a file name now your operating system is full of files but we want to read a file and not disrupt any other application so we're going to read ourselves meaning this file right here that you see on the screen we're going to read this so we have to get the file name to the script how do we do that well there's a couple different ways we're going to show how to do a few of them so i'm going to say os and sys we're going to import both those modules you do that just by putting a comma we could have done it one per line with import module import module i'm just going to do it all in one shot let's go ahead and say print and you're going to see this quite a bit out in internet lands where someone is going to say something like this whenever you see the double underscore it's kind of like a built-in little piece of information in python it gets a little more complex than that but just understand that double underscore means built in and you can see ta-da we've got the full path to our script now there is a problem here now the problem is that may not always exist sometimes you're going to get into a situation where this just simply does not work so again going back to our previous conversation there's always multiple ways to do something so we're going to show you what i believe to be a better way we're going to use the arguments now args or arguments are usually not a good thing usually you want to avoid getting into an argument but in this case we want to dive right into them so we're going to just print out the cis and we want the arg b what's going on with this well under the hood when python calls your script this guy python it actually sends you a list of arguments you ever like in your file browser double click a file and your operating system knows what program to open it up in those are arguments so it will call your script and there'll be another it'll be like comma and then whatever you want to work with so just know the first argument python is going to send you is well the name of yourself what you're currently running makes it super easy now let's go ahead and say we want to get the full path here just to be sure we want the os path we want the abs path now a lot of folks in the comments are going to say why are you using the abs path or the absolute path why don't you use this other one we're just doing this for demonstration we haven't really dived in the complexity i'm going to do an entire video on the different types of paths and what they mean and which one's best and so on and so forth but right now we're still in newbie land so we're just going to do the abs path and then we're going to print out reading whatever this file is let's go ahead and run this and there it is so it's just simply handing us back a list of arguments the first one or the zero position is always the script that's currently running one thing i really want to demonstrate is does it exist well if we're running our own file we know it exists if we're going to run this and read it we know it exists because we're currently in there editing it but just for giggles i want to cover how to determine if the file exists i mean that is the existential question does the file exist do we exist interesting so anyways let's say if and let's go ahead say not os dot path exists you may be wondering what not is not is similar to something like not equals to it's kind of short version for that but i'm just going to say if not os path exists and then i want to give it the name of our file which we got up here so if it does not exist then i want to say hey print and let's go ahead and print up file not bound because if we try to work with some file that doesn't exist we are going to get an error message and what we're going to end up getting is something like this where it's just going to say file not found error which would be covered later on so if you're just churning away and you give it the wrong file name you're going to have a bad time but now that we know the file does not exist we don't want to go any further so i'm going to say exit and i have to give it some sort of exit code and i'm just going to say 1. in case you're curious a normal exit is zero and then you would give it some sort of error message like access denied or whatever but usually vendors will have different exit codes so i'm just going to say one just so we can tell the end user hey something bad happened but because we're reading our own file it should work just beautifully so let's run this sure enough works beautifully let's go ahead and take this and let's give it a name i know just simply is not there nope.txt let's run this again see file not found and then it exits out works as expected now comes the confusing bit we're going to actually start working with the file we're going to start with opening the file and if you get a file not found error during this it means you have the wrong file path and you did not follow the directions or something's going horribly wrong with this so what we're going to do is we're going to say f equals and you want to call open sounds ridiculously simple and it is now we're just going to give it a path now comes the confusing bit we have to give it what's called a mode now i'm going to do another video on modes but this one's just going to cover reading text files so i'm going to say r just stands for read and we're just going to read plain text but what this whole thing's going to do is it's going to go out in your operating system make sure that file's there if not you're going to get a file not found error and then it's going to try to open it for reading it's going to put the cursor in the file at the zero position it's going to hand you a file object back so this one little line there is a lot of complexity going on there now that we have the file open let's go ahead and read a line and i'm going to say line equals i'm going to take that file variable and i want to say read and you notice how we get a whole lot of options read read a bowl read line and read lines we want read lines we're just going to read one single line let's go ahead and print that out save run and ta-dah reading a text file so it read the first line out of our file very very cool you also notice how it put this little return down here because guess what there's a return right there at the end of this there is an invisible slash r slash n or slash n depending on your operating system just know that it's also going to include that so when we print this out we're going to have to strip that out but we have successfully read a line now if reading a line was cool you're going to really love this we can actually control this so i'm going to read a number of letters so i'm going to say pairs equals f not read and notice how it wants a number so we're going to read 10. let's go ahead and print this out and i'm going to actually format this say here's and we'll put star star and then what we're actually reading so if you look at our file here it says reading a text file and now the cursor's right here so let's run this and see what happens and you see how it says cares star and then it's got a return line feed get a f i and then star so we've actually controlled how many characters we've read i wanted to do it this way to really show the complexity here notice we've got this hard return line feed here we may not actually want that so if you're using the read function you're going to get some weirdness like that and that's why i tend to use readline when i'm working with a text file now somebody very observant is going to notice as we've been reading things have been moving forward meaning we read a line then we read a number of characters and it said get afi it didn't start back over at reading so what's happening here as we read there's an invisible cursor much like in this text document you see that curse is right there it always starts off at zero so invisibly there's a zero right there and it's just like a list or a tuple or anything like that it's a zero based index and it's going to start at zero and as we read it will move forward so as it says read line it's going to move there and then when we say read 10 it's going to move there so it's going to actually count so this invisible cursor is going to keep moving what i want to do now is just show the position how do we figure out where we actually are in the file this is a bit advanced and it may not make a lot of sense to you in beginner lan but as you get into advanced file processing you're going to need to be able to move back and forth in a file so i want to introduce this concept fairly early let's go ahead and say print and we are going to format this and say position and i wish they had named it position but instead they named it tell so we're going to call the tell function which is going to tell us the position now i want to say of because i want to know how big this file actually is so i'm going to say os and we're going to call the statistics we're going to use our s file variable that we have earlier and i want to know the st underscore size and if that's super confusing sometimes intellisense will help you out if you're working with an advanced teleset system like kite or something like that um but you can dig through the documentation or you can just you know trust me os dot stat file name st underscore size so we're getting back an integer now the size is the size of the file in bytes let's run this so we are position 31 of 529 and as we add more and more to this so you'll see this position change even though it's a comment the file's growing in size let's run that again sure enough 538 remove that and 5 30 because we deleted some stuff so that is how you would determine where you are and the file size major takeaway here is as we're reading that invisible cursor is moving now i want to put it right back at the very beginning so we're going to call seek and again this is more of an advanced function but i want to introduce it very early this is always a zero based remember our conversation about lists and tuples and dictionaries it's always a zero base index so i'm going to say our file object dot seek and we're going to seek to zero now if you caught that as i was typing you see this seekable some files are not going to be seekable so that may break if you're doing some custom work but for our purpose it should work just fine we're just going to tell it where to seek so seek 0 is going to tell this move all the way back up so if we were working and we're just reading reading reading reading reading as seek 0 is going to say go right back up to this zero spot let's run this and graphically it has no effect but if we do another read you'll see it actually start over again as we're about to demonstrate so now that we understand this invisible cursor and positioning and we know how to control where it is and we've set it back to the zero position let's go ahead and read all the lines i'm putting this big long line here we're gonna print this out just to separate all this out so we can see it in action here what i'm gonna say is for l in f dot read i want read lines notice there's read line which will do a single and read lines which will just keep going and going and we're going to read this entire file line by line i want to say print it's going to hand me back a string so i'm going to say l we want to strip that now what strip does it removes any extra white space so those hard returns like right here how we got these little returns it's going to strip that out if we don't do that we're going to get some really funky results and i'll demonstrate that so let's run this see stopped right here so here's the start of our file and it went all the way down to where we are pretty cool huh now if we comment this out and just grab this this is what i mean by you'll get some funky results if you don't strip that out because print automatically puts in the carriage return line feed let's go ahead and clear all of this out you see how now it's got this extra space in between each line so that's why we need to call strip let's go ahead and put this right back the way it was and ta-da it just works okay systems resource 101 anything you open you have to close so we are going to now close that file think of a file like a door on a really cold day you open that door you're letting all that weather in now you want to close it so what close does is a few different things but for our purposes it's very simple it allows other applications to work with it if we have opened this and the underlying operating system has locked the file for reading that means nobody else can make modifications to it don't worry ridiculously simple f close always always always when you open a file close it you don't want what's called a hanging resource now python can and most of the time does close the file automatically when your script's done but don't count on that sometimes you'll see out there if you open a file forget to close it it just stays open forever very very frustrating so close you're not going to see anything graphically change but it is now closing that door so other people can open it and do what they want to do quick recap this video we have covered the complexities of the file system for reading a text file now text file is different than a binary file which we're going to cover in a future video so we're talking about just plain text we talked about importing we talked about getting the current file determining if it exists opening a file reading some lines and letters and all the lines moving around in the positions and how to actually close the file welcome back everyone my name is brian and we're going to continue our journey into python 3 and we're going to talk about how to write a text file this is plain text not binary we're going to talk about writing binary files in a future video we're going to take what we've learned in the previous video and overly simplify it using functions the last video was kind of verbose i want to make life much much simpler our first goal is to simplify mode usage now what are we talking about here we're going to cover two different modes we're going to talk about write and append and they do two totally different things but we can use the same code so let's go ahead and make a function i'm going to say to file and let's go ahead and say file name mode data i hear a lawnmower behind me i apologize if the microphone's picking that up it's just kind of oven 19 nothing you can do about it my neighbor likes to mow his lawn a hundred thousand times a day so i'm gonna say open and we're going to open that file name and we want the mode now remember in the last video we opened it with the read text or the r mode we're going to work with w and a but they can work very very similarly using the same code as we're about to demonstrate i'm say for i in range and we're going to go ahead and say range let's just pick a number five and let's go ahead and write this out and i want to say the string representation of that number you're going to get some sort of error message if you don't do that let's go ahead and a little colon in there along with the data and let's go ahead and add in a carriage return line feed slash r slash n those are our escape characters we talked about that when we're in string land so really all we're going to do is we're going to write out the string representation of the number using str to convert it from an integer to a string and then we're going to add a colon whatever data we're in and then rn data is going to come to our function as an argument now there exists this tendency to do something like this and you're going to see this flush i'm going to comment this out what does flush do and why do people have it in their code when you write to a file you have an invisible buffer in the background i should say python does and that buffer will fill up because you can add more to it faster than it can write down to the disk especially if you've got a slow hardness think about like embedded systems how they get really slow you don't really need to call flush if you're going to close the file when you're done with the file you close it python calls this automatically when it's closed however if you're doing some sort of like sequential writes or something like that and you want to just write to the file in chunks you're going to want to flush it periodically to make sure that data gets flushed down to the disk i wanted to put that there because i know somebody's going to ask why didn't you flush the contents you don't need to because close calls that automatically and i hate that name but at the same time it makes me chuckle because you're going to flush it and i always think about looking down as disgusting as it is looking at a toilet and you're just gonna drop data into the toilet and then flush it down but that's literally what that does is it flushes all of that buffer down into the hard drive so we're gonna cover two modes and the first one is write when you hear the word write write will overwrite meaning it's going to take the existing file completely erase it and start from scratch and you need to be a little bit careful when you do that because if you have something sensitive or something you wanted to save it's just going to obliterate that data it's just gone it will not be in your recycle bin it will be gone forever so you need to be a little bit careful here so we're going to write file and let's go ahead and say i need some special variable name like filename there we go and we're going to call this to file function we have a file name mode the data so let's just go ahead and grab this and we're going to call our function here so we're going to reuse the variable file name mode we're going to switch this to w for right and the data we're going to say hello world remember right will overwrite it will completely destroy that and start over the other mode we're going to talk about is append now append will add so right will overwrite append will add now what this does is it opens the file seeks remember we talked about seeking moving through that file it's going to go to the very end of the file and then it's going to start adding to it now this is what i mean by simplify mode usage we can literally take this and just paste it and then simply change this to an a for append and then let's change this to hello again so what's going to happen here is we're going to call right it's going to obliterate the file start over and then up to five it's gonna say hello world and then we're gonna call append and it's going to add to it all right the immediate goal of this was to write append but i want to read this file back so i want to use an import and i'm going to put it all the way at the top of the file this is not mandatory but it's almost like an industry standard if you will to put your imports at the very top rather than just adding it right here which you actually could but let's put it all the way at the top that way anything that we've just kind of flubbed through and we've used os we'll get it as well and if we decide to go back and modify these functions and use we don't have to accidentally import it multiple times so in short always put your imports at the top of a file we're going to say def and let's go ahead and read file and i need some special variable name something that really stands out like i don't know file name we could name it fuzzy button kitten or whatever we wanted alright so if not we want os and let's go ahead and say path dot exist so we're just gonna make sure the file we're trying to read actually exists otherwise we're gonna get some bad bad errors now instead of exiting i just want to return right out of this function not kill the entire script now i want to say we're going to open this up and this is how just ridiculously simple working with files in python can be give it a mode and because we've opened something let's go ahead and before we do anything else i'll close now in between open and close we can do whatever we want to do for example i could say 4 line in f dot read lines something like this or if we wanted to really really really oversimplify that we could just read the entire file in one line and we're just going to call read now spoiler alert if you do that on a very large file you're going to have a very bad time because you may run out of memory your little app may crash for example if you have three gigs of memory and you try to read a 30 gig file it's just not gonna do it and it'll sit there for three hours before it crashes but it'll eventually crash that's why we use things like four line and read lines because it reads it one line at a time not the entire thing okay our warning about reading all of it in one function if you had a massive file notwithstanding we're going to leave it like this just for demonstration purposes because we're going to work with a very small file we're going to see this in action i'm going to say my file we could name this really anything we want let's name this hello.txt first things first we're going to write this file just going to call our function now let's go ahead and append the file and let's go ahead and read the file there's a reason why we're breaking this up into functions and it's so we can reuse this code you're going to hear that term a lot in programming code reuse rather than hard coding the file name and then calling or i should say rewriting this function for every single file it's just simply to use a variable and reuse the code so let's go ahead and run this and you can see how it says 0 through 4 hello world and then there are append kicks in here hello again now let's demonstrate this so let's get rid of this append and let's just do right notice how we already have a file out there we can actually open it up and this is exactly what it looks like let's go ahead and get rid of that append and let's see what i mean by write file will overwrite this is why it's so dangerous hello world zero through four and if we open our file back up you can see hello world all of that hello again is gone because it obliterated that file and rewrote it now we can do this and it goes right back the way we want it hello again and again major takeaway from this is writing will overwrite append will seek to the end and add to it and we can make reading files ridiculously simple welcome back everyone this is brian this is episode 25 working with binary files so first things first what is binary we've worked with plain text but what's binary it sounds kind of crazy almost like something from the matrix the harsh reality is binary is something you're really not going to want to work with directly and i'll explain why go over to the extensions tab and let's install a hex editor now spoiler alert you do not need this specific hex editor you don't even need this ide i'm running vs code you can just use any old hex editor out there hex is hex does not matter as long as you can view the actual hex representation here once that's installed we're going to flip back over to the files and we're going to take this file that we're in we're going to right click and then from here we're gonna go open with the hex editor we literally just installed you can see we have the hex encoded bytes along with the decoded text this is what i'm talking about here decoded this is what the computer works with this is what the machine reads this over here is what we usually work with the plain text so for example pound is hex 23 then you have 57 which is a capital w 6f i mean imagine trying to type out just like your name in hex that would be long and frustrating so when we're talking about binary we're talking about the raw data the computer works with it's not something we want to work with directly we want to work with a representation of that data so that's really what we're talking about when we say binaries we want to give that computer a representation of binary data and let the computer do all the hard work for us we're not working with plain text we can work with individual bytes that represent plain text but we're not working with the plain text itself all right we need to leave binary land here and we're going to go back to plain text land and this is just the file we've been working with i'm going to plop in some notes and it's going to just say install the microsoft hex editor extension don't really need it to be the microsoft one but then some general instructions on how to work with it in case you're following along with these videos now we're going to add some imports and we need to do this step before we even continue with anything else so i'm going to import random and what i mean by random is we're not just randomly importing something we're importing a module named random which will help us create random numbers and we're going to import the operator module this has a little function here called equals or eq that we're going to use to compare two lists together just to make sure that the information we're generating and the information we're saving and loading all matches up and everything works as expected let's go ahead and work with that random module and we are going to create some random bytes here so let's make a function let's call this random bytes and from here we're going to just have a parameter called size let's go ahead and make a list absolutely nothing in that list now we're going to say 4x and range and we want a range to equal the size we're getting that from our argument let's go ahead and append our list so lights and now we want to actually say random and we want a range so i'm going to say rand range and if you know anything about a byte it typically goes from 0 to 255. you can do some crazy things and we're just going to stick with the norm 0 to 255 here very simple easy for anybody to understand we're not talking about some raising scope encoding schemes or anything like that just 0 to 255. that's all we want from there we're going to go ahead and return the bytes so we're just going to return that list so random here is going to make a random number within a range between 0 and 255 so we can have up to 256 possible numbers now random you can do seeds and all this other fancy stuff and then we're not doing any of that so what it's going to do is it's going to take the current system time and use that as a random number seed if you wanted something super secure you would have to do something different but we're just going to leave everything as default for now now let's go ahead and print that out just to make sure we are getting well you guessed it some sort of random list of numbers so say def and display bytes go ahead and we're going to introduce a few concepts in this video here some things we really haven't talked about so i'm going to just make a string now i want to multiply this so we're going to say times 20. that looks a little funny but what we're going to do is we're going to say take this string and do it 20 times so we're saying this string times 20. now we're going to go ahead and print out our little list of bytes here to do this we're going to use the enumerate functions let's say for index comma item in enumerate and what enumerates going to do is it's going to pull that whole object apart into multiple pieces things that we can use and you see where it says right there enumerate object yields pairs containing a count from start which defaults to zero so we're going to tell it to take that bytes list and enumerate it and we don't want to start at zero we want to start at one because people are not computers we like to start at one not zero we're just going to make this you know human readable now we're going to go ahead and format out a print and let's say index equals and we want the item now we've been working with a hex editor so i want to show you a simple little trick here we can just simply say hex and we want to make a x representation of this item so that we could later compare it to a hex editor make sure that everything lines up exactly the way we would expect it to i'm going to grab that little print function drop back down make sure that lines up so we're not doing it every single for loop but after the for loop is completed and let's test this so i'm going to just grab our function random bytes and whoops grab too much of that apparently there we go and let's just say 10 just for now nothing too crazy now i want to go ahead and display that list let's just see what this looks like so sure enough we are getting a list it is one through ten human readable starting at one under the hood it's actually zero but we're using this little start here to increment it and then we have the decimal and the hex representations of that data okay deleted our little test there and we are going to now move ahead and we're going to write some bytes here now we have to do this a little bit differently we've been working with plain text and we're working with binary files this is not human readable so we have to tell python we don't want humans to work with this we want computers to do it so we're going to say def write bytes we want a file name and the list of bytes now that list is just going to be a list of integers so it's a little misleading where it says bytes this function's going to convert those integers to bytes and store them in the file we're going to introduce something a little bit different here it's going to be the with keyword so we're going to say with width is going to take some code function that returns a variable and use the variable so let's go and demonstrate that so we're going to say with open we're going to open the file name we need to give it a mode and we want to write binary if we just did a w it's going to be plain text so we want that b in there as file so what we're really doing here is we're saying with this function run this function return a variable and call it files so with some function as file kind of reads like a book with this as this variable now that we've got that variable we can just work with it directly i'm going to say 4b in bytes and we can use that variable we got from our with statement file right and we're going to take that individual little number and i'm going to say two underscore bytes it's a little misleading that it's a b representing bytes this is actually a list of integers so i very easily could have said i doesn't really matter what we call it so we're going to convert that to bytes now we want to convert it to one byte and if you're a computer expert and you understand this we're going to give it a big order so i'm going to say byte order equals big you don't know what that is don't worry about it we're just going to use this just for demonstration purposes it really doesn't matter unless you specifically want a big or something else all right that's it we're done now you may be going now wait a minute we have a file object don't we have to close it shouldn't we do something like file close well no that would cause an error and that would not cause an error but it's really not needed because with is going to destroy this when it's done with it and when that variable is destroyed it's going to call close automatically so we're actually done it's you notice as we get more advanced in python even though we're writing more advanced code the code actually gets shorter and shorter and shorter this is one of the really cool things about python and we could shorten this even more if we wanted to but we're still in beginner land so this is about as short as i'm going to make it for this video now that we've written the bytes we want to do the exact opposite we want to read those bytes back and i'm going to intentionally make this function a little bit bigger than it needs to be just because we're still in beginner land and i don't want to confuse anybody so i'm going to say def read bites and i'm i'm saying that because you'll see people down in the comments going well this is very verbose why are you doing this when you could do and they'll put a little one-liner in there and everyone looking at it's gonna just be like i don't understand what they're talking about so i'm going to say bytes we're going to make a blank list we're going to say with open and we're going to get our file name now this is the trick here we need to do the opposite we're going to read bytes not read plain text and i call it bytes but it's read binary as file now i'm going to do a loop and i'm going to say while true loops are big and scary for noobs so don't worry we're going to tell this when to stop looping so it's not going to enter some infinite loop i'm going to say b equal file dot read and we want to read just one now we're not reading the number one we're just reading one byte from that file if not b and i think we've talked about not before it's the same thing as like something like that not equals to but we're just saying not b and we're gonna go ahead and break break will break right out of that loop however if we're still here in loop land we want to say bytes append let's go ahead and take hint from bytes so we're doing the exact opposite here instead of two bytes we're saying from bytes so we're taking a byte and converting it to an integer and it's pretty simple we're just going to take our b that we read from the file and we're going to set the byte order if we really really want to so let's just do that all right now once we're in there we're going to drop back down to this level right here and we are going to return our finished list looks big and scary but really we're just doing the opposite of right bites we're just saying hey make a blank list and then with open get a file and then as long as we can read one byte append that to our list of integer and return it looks big and scary but it's actually pretty simple once you wrap your head around it now that we've got all the pieces together let's see it in action this is what i love about programming it is a lot like working with legos once you get the pieces together you can make something bigger and better so let's see it in action the first thing we're going to do here is create the random bytes so i'm going to say out bytes you can call this whatever you want it doesn't really have to be out bytes and this is going to be our random bytes function and we're going ahead and just let's just keep it at 10. i don't want anything too crazy because we're gonna have to see it on the screen let's go ahead and display that just so we can see the out bytes and i'm gonna walk through this step by step here so let's go ahead and run this and we've seen this before i've got this kind of split up here so every time it displays it'll have this nice neat little bracket there now we're going to write all that to a file so i'm going to say file path and let's call this test dot txt now this will make some people mad because what we're doing is we're violating some fundamental concepts of the operating system people expect that a dot txt file is a plain text and i'm doing this for illustrative purposes to show you that the file name and extension have absolutely nothing to do with the data that goes inside them so now that we've got a file name i'm going to go ahead and say right bytes and we can just simply take that file name along with our out bytes and dump that to a file let's go ahead and run this again uh oh file name is not defined oh i've got file path that's why shockingly the variables have to line up all right let's try that again clear that run it okay doesn't look like anything happen on the screen but over here now we have this little dot txt file and if i open it i get kind of these crazy characters what is this this looks like gibberish did we have a corrupt hard drive no let's go here open with our hex editor and see what's going on here so if we kind of scroll up here you can see how we have one equals 84 but then we go into panic and go it's 54. what's wrong well the hex version of 84 is 54. and then we have f1 f1 or 4. you see what's going on here somebody out there's going to ask well why does it say 0x that's kind of like the universal representation that we're working with hex data so in your mind just kind of blank out that 0x and just pay attention to everything after x so we have 54 f1 4 e1 d3 and you can see it's just working as expected now this is what i mean by a lot of people kind of get into a panic when you tell them you have to work with binary data because they don't really understand this and they think that they have some horribly bad screwed up computer or that their program did not work well because they look at it and go uh oh it says 54 but i should have put 84 and they try to figure out what's actually going on this is what i mean by we're not working with binary directly we're working with a representation of the binary data we let the computer figure it out for us continuing on here almost done now we're just going to take that file and read it back in so i'm going to say in bytes equals and we're going to go ahead and read bytes and we're going to read that file aim there we go once we have that we're going to go ahead and display it and now we need to go all the way back to the beginning of this video when we said we're going to use the operator import and we're going to compare them so i'm going to say print and let's say match i just want to know if they're a match kind of like what is that dating site match.com it's a match all right so i'm going to say operator dot eq and now we need to feed it some lists so i want to say bytes and in bytes again doesn't really matter what you name these now because we are using a random number generator that the seed is based on time these numbers will change every time i run this because time is constantly changing just wanted to be aware so if you're expecting 84 241 4 blah blah blah you're in for a very big surprise here or maybe not now that i've told you what's going to happen let's run this see what happens here it says match true so what happened here and let me scroll this up we have our output and our input and of course they line up every single thing works correctly and the two lists now match so what we've done long-winded version of this scroll all the way up here we've created a list of random integers it says random bytes but it's really integers then we can display those and then we can pump those out to a file and then write them as bytes then we can read them back and read those bytes into integers and put them back into a list or return that and we can actually check to make sure everything matches so what we wrote and what we read now match the big question is how would you modify this information well let's say you wanted to do some sort of work you would do that to your out bytes before you wrote it to the file and all of your changes would be written to it see our file is right there and if we go into open with our hex editor and we get the nice beautiful representation of it welcome back everyone this is brian and this is episode 26 we're continuing our journey into python 3 and we're talking about json files that's a little misleading it doesn't actually have to be a file what we're talking about is data and let me just post some json data here and i've got it in these triple quotes that way the ide doesn't get all mad but really what we're looking at is this bit here everything between the brackets so we have the start and the stop and then we have key value pairs now json can get a lot more complex than that but i wanted to keep it super simple because we're not really trying to learn the complexities of json we're just trying to learn how to use it with python first off why do you even need jason what is this what do you need it for well it is for app to app communications now when i say communications this could be anywhere from network to remote calls to just simply writing and reading files json is meant to be a data format so it's not necessarily a file format you can do all of this virtually across networks across memory however you want to do it but it's an agreed upon format so let's say i write a program and you write a program and you want to be able to read what i'm creating we have to have an agreed-upon format and that's what json really is as you might have guessed jason can get a little bit complex so before we deep dive in we need some imports actually we really only need one we're going to import json makes it ridiculously simple i know it's so complex but we need to import this module because we don't want to reinvent the wheel we want to use code that's already written and we know works let's also go ahead and make a variable and i'll call this file name we're going to use this again and again i'm going to call this json.txt let's start this off super simple here so we're going to put some dictionary to a json formatted string say that five times real fast it's a little confusing but that's what we're going to be doing here i'm going to make a variable called out d you can name it whatever you want but i just want to know that this is the output dictionary this is what we're going to convert so i'm going to say the predict function and i want to make a dictionary that has key value pairs of name brian age 46 and that's say cat so we're going to take this dictionary here and we're going to output that to a json format so let's grab this a little bit of copy action there i'm going to say s equals and we want to use the json module and we want to dump s not just dump now if your ide may show something a little bit different you may see both dump and dumps with an s at the end we want the s which is short version for a string so it's going to dump out a string i'm going to feed it our variable there i'm going to actually do the magic of copy and paste put a little note there just in case somebody's confused about the difference between dump and dump s usually when you get dumped it's a bad thing but in this case it's going to make us very happy all right so that was actually poetically sad but we're going to say the string is going to be our output let's just run that see what it looks like there so sure enough string evils and look it looks like a dictionary this is what i love about dictionaries in python in accord with jason is they look virtually identical it's very easy to see that and see exactly what's going on because we have our key value pairs let's go ahead and take that and push it out to a file now remember i said as we get more complex with python we actually write less code and i found that to be very true it's one of the bizarre things about python so i'm going to say with open and we are going to say file name our little variable there and we're going to write that and we're going to make a variable called now we're going to say jason dump notice how there's two of them there's dump and dump s whenever you see the s it stands for string we want to dump this and what do we want to dump we want to output our dictionary to the file and i'm going to put some notes in here just in case anybody gets a little confused as to what's going on there very very simple very easy to understand let's go ahead and run this and it gives the same output now we have this json.txt and if we open it up it has the string i should say stringified json or our actual dictionary in a json format it may look exactly like a python dictionary and that's why people often get this confused they go you're passing python back and forth actually we're passing json encoded data it just looks very strikingly similar to a dictionary object in python now let's do the exact opposite i want to say from string so we're going to go back up here and we're going to take this s variable right here remember that jason did a dump s or a dump string to this little guy right here so let's take him and i want to do the opposite of a dump which is a load i'm going to say nd equal jason and in case you're wondering about some of the names like dump yes python developers do tend to have a sense of humor so bear with me on some of these video and we're going to load s notice it's not load it's load s for string and we're going to feed it that string and i'm going to put some notes in here just in case anybody gets a little confused so load the dictionary from a string i have this named indie you can name this whatever you want doesn't really matter and i'm going to do the magic copy and paste here let's go ahead and run this and you can see our dictionary is now loaded up very cool the way that works and it looks virtually identical so yes it will confuse a lot of people but rest assured we're working with jason now in the spirit of doing things backwards we are now going to load this from a file so we're back up here where we said with open file in right text as f and then we did a dump and we dumped that dictionary out we're going to do the exact opposite of that i'm going to say with open and i want file name we're going to just read that as plain text as f and then let's make a variable we haven't used before so it's strikingly obvious that this is loading it so i'm going to say file dictionary or fd equals json and we want to load not load s because that would be string we want load which is going to tell it load it from a file source and in case you're really curious no variable name does not matter i could actually name this person or p or brian whatever i wanted to do does not really matter so now that we've loaded that well now comes the complex part we just work with it it's really really that simple i'm gonna say when i say complex i'm joking a little bit this is so ridiculously simple it's almost scary if you're coming from other languages and other frameworks you're kind of like what how is it this simple it's just mortifying so i'm going to call the type function here just so we can see what type what data type p is this is one of my little kind of gripes about python is ides are great but if you just open this up in like a plain text editor and not an ide you may be looking at this trying to figure out what is load really doing what is it returning so the type function is going to print out or i should say give us back the data type there so we can print it out and then let's go ahead and print out the actual variable let's run this again so type class dick so this is a class dictionary remember classes are something we're going to cover in the near future a class is a blueprint for an object so this is a dictionary data type and it is equal to you guessed it the information we just loaded back from the file which is now a dictionary very simple very easy the main takeaway from this is json is a data format used to exchange data between applications this is an app to app communication data standard people all over the world different countries language barriers doesn't matter we'll say hey hand me a json file and it's very easy to work with when you look at it it is a string so it's very simple to just open this up in a notepad or a text editor and just modify it if you need to but it's also extremely easy to work with at a programming level welcome back everyone this is brian and we're talking about imports in this video imports allows our code to be used by by other scripts and it allows us to use other people's scripts but most importantly really what importing allows us to do is simplify things we can actually now structure our code and then import things as we need them now the import system is actually pretty complex so in this video we are just scratching the surface we're going to talk about some real high level issues and i want to show you how to split your code into different files we're going to have to split this into multiple videos throughout the series so we're going to continually go back to the import system and add to the complexity over time let's dive in first things first we want to make a separate file so i'm going to just plop in some notes we're going to create a file and i'm going to leave this comment in there for anybody who just doesn't watch this video and just finds the code out on github it's just going to say go ahead and look at my code dot py and we're gonna go over here and we're gonna actually make a new file we're gonna give it the name my code dot py and inside of this file well we're just gonna add some code here so i'm gonna say name equals whatever your name is but i horribly screwed that up i can't even spell my own name right actually i spelled it right i just had a case sensitivity wrong we're going to make a function called greet and i'm just really freestyling this i don't really have anything in mind we're just going to add a bunch of code and functions here so i'm just going to make a function called greet what's going to print out hello and then whatever the name is notice the scope here name is actually up in the global scope of this file i'm going to say def and let's go ahead and say 2 file we've already learned how to work with the file system in a previous video if you missed it go ahead and go back in the playlist and watch that video i'm going to say file name global name really don't need to say global because we're not trying to modify it we're just trying to read it python's pretty lenient about that but just to be safe we're going to say global and then open file name we want to write to that file again if you completely skip that video i would highly encourage you to go watch it and we're just going to say f right and we're just going to write everything out to the file in this case we're just simply writing the name we take this very simple pattern and just change it around so now we have from file and we are going to open that in read mode and then we're simply going to do the exact opposite here quick refresher when we say with it's going to remove this when we're done with it so it's going to automatically close that file for us so we don't have to worry about any of that complexity okay so our file is all done and it's not super hard it's just got a variable and some functions let's go back to our original python file here it does absolutely nothing actually let's jump back here make sure you save that now what we're going to do is use import as and i think we've touched base on this but we haven't really dove into what's going on here so i'm going to say import and you want my code as and let's just give it a name person could be anything we want we could call ice cream cone kitten code whatever we want but what's really going on here is import is saying import this module now module is a concept we haven't really covered and we are going to cover in a future video but right now when i say the term module just think about external code code that's outside of our file so import is going to look in and invisibly there is a little right there it's going to look in the current directory for something named my code and directory structures with imports gets a little confusing we're going to cover that in a future video so everything right now is in the same folder at the root of your project so import this file there's an invisible dot py at the end of this which is of course my code now if you misspelled this it's simply not going to find it now we're saying as person so what it's doing here is it's importing this entire file this thing that we've already written as one variable so it's now creating a variable called person you can see how person is now my code so that entire file is now sitting in this variable for us to use it gets way more complex than that but that's about as simple as i can explain it basically we're taking this entire file and converting it into a variable now at this point i would highly encourage you to test this just simply run it it should do absolutely nothing but if you had some sort of misspelling or something you're going to get something like this module not found error and then no module named named is your key here the name is misspelled so let's go ahead and fix that just wanted to demonstrate that let's talk about some scope issues we can run this and see that it's working as expected let's go ahead and clear that out let's go ahead and use our global so i'm going to say global aim not name error thank you intellisense global name go ahead and print this out what's happening here name error name name is not defined wait a minute what in our file we have name and we're using it via the global scope so what's really going on here and what we're trying to illustrate is that a module has its own scope so the global scope of the module is not the global scope of your script or your application they're two completely different scopes so even though we can explicitly try to shove this even though it's already a global we can try to shove it in the global it really doesn't help us it's still not defined now if i do something like this comment that out run this what happens same thing name name is not defined so it doesn't really matter which way you try oh that is super super frustrating if you're newbie so how do we get the name out of here well remember we have taken this entire file and converted it into a variable we have made pretty much our own data type so we're gonna go ahead and print person or whatever you name that and now we want the name attribute and it automatically knows it's a string so life is now going to be good let's plop a note in here just so anybody out github land can see easily what's going on clear this out and run oh it's because i still got this in there sorry about that let's try that again all right so there we go brian karen so if you were like me and you forgot to comment that out you're to get that nasty error very good illustration of scope in terms of imports and modules anytime you have a new file think you have a different scope there are ways to jump between them but for realistic purposes they are two different scopes and you should treat them as such last thing we need to do is really just do some testing so we're going to go ahead and test this code i'm going to add some spaces there just get some screen real estate let's go ahead and say person dot name equals and i'm going to switch this to brian instead of brian cairns and then let's go ahead and do person dot greet call that function and let's just do person dot to file let's give this a very simple name test.ext it's just going to dump that name out to a file let's go ahead and say person.name what's tammy go ahead do the greet again just so we can see that we did change that variable let's go ahead and load that file now as long as our file name matches up it's going to load it just fine go ahead and greet again just so we can see that we did actually load that name from the file let's go ahead and run this see what happens so the original name is brian cairns i switched it to brian switched to tammy and then we loaded it from the file we could see we now have this test.txt out here so in a nutshell just to recap imports is a really really great way of structuring your code and it really simplifies things it does have its complexities which we're going to cover in future videos and we've touched upon a little bit here with scoping issues it gets way more complex than that because what we're really touching on with imports is the cornerstone or the foundation of modules and unfortunately before we can dive deep into modules we got to learn other things first like well classes which is coming up very very soon welcome back everyone this is brian we're going to talk about the main function in python now in case you're wondering what a main function is in most programming languages you'll have something like this and all this is is a function literally called main and when your application execute it's going to be the first function or the entry point to run and without a main function your application simply won't work well as we've seen with python you don't need a main function this works just fine so how do you get your code to run automatically that's really what i'm going to be talking about in this video let's go ahead and take a look at this so first thing we need to do is determine how our script is running if you've been following this series in the playlist on youtube you know that you can run your script directly and your script can be imported so we want to make sure we know exactly how the script is being run so let's go ahead and go print and we're going to say f so we're going to format this out say name equals now we're going to use a special variable underscore underscore aim whenever you see that double underscore this is built into python we're going to take this and print this out let's go ahead and change this to file and i stated in a previous video this may or may not work so if you have problems with underscore underscore file you're going to want to watch that previous video where i talked about using the system arguments that are handed to your script this should just work just fine most of the time let's go ahead and run you can see how our name is underscore underscore main so remember double underscore means it's built into python and the file is well the file name that we're currently running this spoiler alert could change so don't depend on this what i mean by that is if we are calling our code based off an import in a special way the file name will not actually be the name of the script we're currently in so you got to be a little bit careful there but i want to highlight those things the big takeaway from this is our name is underscore underscore main which means we know python is running this file directly this is the main script file now let's go ahead and create some code here our script really doesn't do anything so we want to do something we're just going to make a test function i don't really care what it does just as long as it prints something out on the screen so i can see it's running now we're going to make a main function here notice the name is main go ahead and print this out and let's just for giggles go ahead and call our other function here so really what we want to do is we want this script to run automatically run this main so we know what we're doing and then call this other function and start some chain of events do some code processing and things like that so let's go ahead and let's clear all this out and let's see what a lot of people who are new to python make a mistake they go oh i know what i'm doing and they go ahead and run and nothing happens oh that is a bummer so yes in python the main function really isn't called automatically we have to call it specifically now you may be thinking i know what i'll do i'll just go down here and then call main directly and it will work watch we'll run it and ta-da it runs this is the main function this is a test function so we are calling it the problem comes in with this name right here we're going to demonstrate right after this section we're going to show you what happens if we run this from a different script we don't necessarily want this code to execute meaning if we take this file and import it as a variable in another file i don't want this function firing off so we want this to run automatically but only if a certain condition is set let's go ahead and say main and we're going to print this code out automatically this is my id you may have to type this we're going to say if underscore underscore name equals main then and pass is just going to i'll do nothing so i'm going to take this call our main function directly go ahead save and run and sure enough it runs our main function so it's saying the name is equal to main so we know python's running this directly a main go ahead and call this once you've wrapped your head around the difference between underscore underscore name equals underscore underscore main and you know that means that python is running this directly we can do something a little bit different we can actually take this code file let me grab some notes here and we can run this from a different script just to see the difference here so we're going to create a file called test.py and i'm going to make some mistakes just to show you what's going on i often make mistakes but legitimately this time i am trying to show you what's going on so the first thing we're going to do is we're going to import this file here so let's go back here and i want to say import python notice how intellisense is helping us out as code now from our previous video you know that what we're doing is we're taking this file in its entirety and converting it into a variable which we can use before we go any further let's run this notice how we get an invalid syntax it's got this little it's called a carrot right here is pointing up at this bracket so what it's telling us is it doesn't like this it's simply our files naming convention needs to change so what we can do is let's right click this and call this code file dot py the functionality has not changed so for example we'll run code file which used to be the python 3-28 and you see it's working as expected it's just the file name has changed so the functionality hasn't changed just the name we're gonna have to go back in here and change the name clear this out and let's run this test.py you can see how right off the bat what's happening here is name code file file name code file what is going on here we ran test py but it's printing this out so when we hit import it's going to go through and start reading our file from the top down and it's going to actually take some actions so this is a little bit dangerous here and just for illustrative purposes i'm going to grab this go in here and let's say let's call this test name and test file just to separate those out clear this and rerun now you see they're both firing off even though i'm running test.py import is happening first so it's saying import code file it's going over to code file executing this code it's not executing our functions and because the name is different it's not executing this see name is code file so the name is no longer underscore underscore main the name is well simply the short version of the file name code file doesn't have the directory doesn't have the extension of dot py that's why we need this if name equals underscore underscore main so now in here we can actually call this directly save run and see it in action sure enough this is a test function main never fired off this may seem a little bit confusing so quick recap you have to be a little careful how you name your files if you're going to use them as an import some characters are just simply illegal like the dash you saw earlier if you're going to run automatically you want to check the name is equal to underscore underscore main because if we're running this file as an import it's going to give us the name of the file with no underscores in front of it this is not guaranteed to be the name of the file python can send us anything we want the point being underscore underscore main means that python is running this directly and just to illustrate that we're going to run the code file again and see name is underscore underscore main welcome back everyone this is brian we're going to talk about import madness in this video and yes we are going to deep dive into well insanity here so what we're talking about is underscore underscore init what is it and why do we need it first things first we need to make a subfolder and add some code to it so i'm just going to plop some notes in there we're going to make a folder and let's literally call it sub so i'm going to go up here i'm going to say new folder sub and inside of our subfolder got to make sure you got that highlighted your ide may be different depending on what you're working with we're going to add two files the first file we're going to add is going to be called well very simply test dot py and we're going to add some code and just for the sake of time i'm going to copy and paste just a simple function do test which just prints out do something here really not award-winning code by any means let's also add another file and this file has to be named underscore underscore init underscore underscore dot py remember whenever you see the double underscores you're thinking something internal to python now there's a lot of debates out on some forums on whether or not you actually need this and legacy versions of python you actually do more modern versions of python it's debatable but i'm putting it in here just so we understand it i'm going to pay some notes here and it's quite a bit of notes this is needed because we are in a sub folder whenever you see folder i want you to think in terms of modules remember we've talked about modules just a little bit but a module isn't just simply a file it's an entire folder structure and the problem with creating some sort of folder structure is that python needs to understand how to work with that folder structure so in its simplest case init dot py can just be an empty file but it can also execute initialization code for the package that's how complexis can get so if we're working with something like a a socket server or a database or something like that we can actually initialize some code we could say like port equals 80 or the username you'd never do this in production but like the username would be admin or something like that you can actually specify all that right in this file so we are using this very simply because we want to work with this file and we want python to understand how to work with this file so we're going to modify it just a little bit here we're going to say from dot test import star we've seen import before but we haven't seen this what is going on here so what we're doing is saying from dot test import star the from is just basically saying go out and find this and we have this little period here if we omit that we may have some bad things happen it may not actually know what we're trying to do here so we have to put that in there in most cases and then magically it knows this is the directory if you're ever confused dot is the current directory and a dot is the parent so basically what we're saying is from the current directory and then take a file named test there's no dot py at the end of it go ahead and import and then everything so we're saying take the entire contents of this file and put it right into python let's go ahead and play around with the imports a little bit so we're going to flip back to our main file here and we're going to play with imports so let's go ahead and try and import it a couple different ways that we've tried the past we're just going to simply say import sub dot test as code now code dot do test we can actually do this look at this now if we run this everything works just fine but we have skipped over this initialization file uh an older version of python's this may may not work you might run into some little bit of trouble here and if you try saying like from the current directory dot sub dot test you may depending on your python version run into something like this invalid syntax so how do we import this file and if we had other files as well you guessed it we need this initialization file there's a special way we have to do this so what we're going to do is jump right back here get rid of all that and we're gonna say from remember when you see the from keyword we're saying go find a location so from sub sub is the name of the folder so from this folder go ahead and import star so we're saying from this folder import everything now that's big and scary because what if there's thousands of files out here that's right we're going to import thousands of files and that's where this underscore underscore init underscore underscore py really comes in or the initialization file we'll just call it for short because it's going to instruct python on what to do there may be some files we want to import directly and there may be some files we don't want imported automatically we may want to set some variables or some settings or some file structure we would do all of that right here and we could call functions if we had to it goes way way deeper than that again we're still in beginner land and if we really wanted to we could get a little funky with this we could say something like from sub import and then specific file remember that would be test.py but you don't need the dot py as code so we're saying from the folder import a file as this variable looks a little verbose and it seems a little confusing until you really wrap your head around it but it's super super simple once you get it down the major takeaway here is if you have a subfolder you should include this underscore underscore init underscore underscore.py or the initialization file if you skip this step older versions of python will just simply not work and you may have some weird issues and if you want to do any sort of initialization at all this file is pretty much a must okay once we've gotten to this point really there's only one thing left to do is actually see it in action so we're going to call the code here and say d-e-f main and if you are with me here and you try to do something the intellisense in your editor may betray you gotta be a little careful so i'm going to say main and for the moment i'm just going to say pass remember pass in python means do nothing and if name go down here equals equals following along from the previous video we're saying if the name is equal to main go ahead and run this function automatically that way if we were to import this file it's not going to kick off this code let's go ahead and get rid of this and we're going to say print this is the main function and let's call our imports now because we've done from sub import star meaning import everything it's going to go in here and it's going to read this initialization file and say from test import star and it's going to import all of our code we've got this do stuff out here so do the magic of old copy and paste i can grab that jump back out here and say you test and we can just call it directly and it just works see do something here and because we've done from sub import test as code we can take this and we've just basically said do the same thing but put it inside of a variable now i can say code dot do test very simple very easy works as expected so which is the correct way which one of these should you use personally i tend to lean towards a second line here simply because importing from everything what if you have a name collision what if there's like a test2 file that also has the same do test function you want to be able to separate those out into two different variables or two different scopes remember each file is kind of a island in itself as far as scope goes at least that's how you should think about it in your mind so the major takeaway from this is well the initialization file matters and if you omit that you may have a bad time in python land you really need that to initialize how python does things and there are different ways to import further muddying the waters on import madness
Info
Channel: Extern Code
Views: 64,372
Rating: undefined out of 5
Keywords: python 3.9, python 3.9 tutorial, python tutorial 2021, python 2021, python for beginners, python language, learn python, python programming, install python, tuple in python
Id: cBQ4c1IQJSE
Channel Id: undefined
Length: 380min 52sec (22852 seconds)
Published: Thu Mar 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.