Python Full Course 🐍 (𝙁𝙧𝙚𝙚)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on everybody it's bro hope you're doing well and in this video i'm going to help you get started with python so sit back relax and enjoy the show if you wouldn't mind please like comment and subscribe one like equals one prayer for the youtube algorithm i'm gonna tell you why you need to learn python it's the easiest programming language to learn as well as being the most popular in the world right now and according to glassdoor the salary for new python developers in the united states is 64 000 if any of this sounds good to you well then let's get started if you need to download python go to python.org downloads and click this yellow download python button open when done check add python 3.9 or another version to path install now and then give it a little bit it states here that setup was successful so let's close out of this our next step is to download an ide that's an acronym for integrated development environment think of it as software that helps us write other software one ide that i recommend is pycharm you can find it at jetbrains.com pycharm go to download if you would like to pay for a professional version you can click this download button but since i don't like to pay for things i'm going to use the free community version at this point we just have to follow the standard installation procedure click next you can pick a destination folder but i'll keep the default next if you would like a desktop shortcut then check this i would also recommend updating the path variable next install and then give it a minute or two then after finishing i have a desktop shortcut so i can just click on this to run pycharm let's create a new project name this project whatever you like i'm going to name this project hello world and i recommend not creating a main dot pi welcome script right now i'll show you how to do that manually and let's create if you need a python file to work with this is how to create one go to file new python file and i'm going to name this main and then click python file all right ladies and gentlemen we now have an empty python script that we can use to begin coding now if you checked this box create a main.pi welcome script and then created a new project then your main python file will probably look a little something like this but that's completely fine we can just delete this i don't know about you guys but the font is very small for me so let's change that we can change that by going to file settings editor font and you can increase the font size let's say 25 you can also change the font too what's a good one uh how about that then click apply and okay much better we can actually see something to run a python script just click the screen play button in the corner alternatively you can go to the run tab and then go to run okay so this box that appeared at the bottom this is referred to as a terminal window this will display any output that your program has and this line at the end process finished with exit code zero that just means that there were no errors in this program so currently this program doesn't do anything but let's change that let's print something let's print a message so to print a message to the terminal window type print and then add a set of parentheses and then you can type a message but it has to be within quotes either double quotes or single quotes it doesn't matter so let's think of a message i don't know i love pizza then let me run this and in my terminal window it says i love pizza to print another line just add another print statement print and then your message within quotes it's really good and well what do you know it printed i love pizza it's really good so ladies and gentlemen you just wrote your first python program by the way you can change the font as well as the font color of your terminal window by going to file settings then go to editor color scheme console font and console colors let's change the font let's say i would like whatever this font is then click apply let's change the font color too by going to console colors for any output you can click number two and select a color let's say i would like bright green that should be decent and for anything else let's say this will be a dark color so i can barely see it so then let's click apply and okay oh yeah that's much better well everybody that was your very first python program i'll post any useful links and timestamps for this video in the comments section down below but yeah welcome to coding with python hey you yeah i'm talking to you if you learned something new then help me help you in three easy steps by smashing that like button drop a comment down below and subscribe if you'd like to become a fellow bro [Music] hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain how variables work in python so sit back relax and enjoy the show if you find this video helpful please remember to like comment and subscribe your support will help keep this channel running all right let's do this a variable is a container for a value it behaves as the value that it contains it's much like in algebra lessons back in the day where we had to solve for whatever value x was and then we can reuse x and it behaved exactly as that value well with programming we can do that plus we can assign variables of different data types so they are not limited to just numbers we can assign whole words numbers and even these things called booleans which are either true or false but i'll get more in depth into data types a little bit later on in this video so let's create a variable and this is how to do so we need a unique name for this variable let's say name name equals some value now the first data type that we'll cover is strings a string is a series of characters so to create a string we can either use single quotes or double quotes in python and we can assign this a value of whatever your own name is so i will assign this variable name a value of bro now this variable will behave exactly as if it was this value this name and then we can reuse this variable for something so let's print whatever our name is print name and this will print whatever your name is to the console window now when you print your variable make sure you don't put it within quotes because what we're doing then is literally printing the word name as you can see here so if you need to use your variable for something make sure it's not within quotes now we can combine our string variable with another string so within our print statement let's print a string literal such as hello space plus name so we are combining strings and then we're printing the results to the console window so this will print hello bro now you can actually check the data type of a variable so i'm going to turn this line into a comment so what you'll do is take the name of the variable surround this with a set of parentheses and then precede the set of parentheses with the type function and this will print the data type of this variable to the console window and you can see that it says class str short for string a string is a series of characters a name is a good example of a string a series of characters so that is how to check the data type of a variable just use the type function now you can actually combine variables together as long as they're of the same data type so let's change our name to maybe first name and we'll create a second variable called lastname now a common naming convention with variables if it has two words separate each word with an underscore it's not necessary but it's common practice for python and honestly i sometimes forget about that but don't tell anybody so let's create another variable called last name last name equals whatever your last name is and then let's create a third variable called full name full underscore name and let's combine first name plus last name and let us display full name along with hello plus full name now these two names were combined together to create a whole new variable actually what i think i'll do is add a space within my variable so i'm doing a bunch of string concatenation i'm combining the variable first name plus a space character plus last name so the result is hello whatever your first name and last name is so that is a variable of the string data type it is a series of characters now with strings we cannot normally use these for any sort of math that's where the next data type comes in for the time being i just turned all of these lines into comments and we are going to move on to the int data type short for integer this time let's create a variable called age and we will assign this a value of whatever your age is let's just say that i'm 21 now when you assign a value of the int data type make sure that it is not within quotes because then technically it would be a string then and you can see that the color scheme for this number actually changed so if this was a string we would treat it different than an int data type because with strings we cannot normally use them for any sort of math so we now have a variable called edge and we can actually increase or decrease or do whatever we want with the edge let's increase our age by one let's say it's our birthday to do so we would say age equals age plus one and then let's print our edge to the console window print edge and you can see that it says i am 22. now there's a shorthand way of writing this what you'll do is type age plus equals one so that's kind of like a shortcut and this would work the same too now let's print the data type of our inch variable because we can within a print statement i will print the edge and add my edge variable to this type function and this will print the data type of my edge variable to the console window and i will turn this line into a comment just so that it doesn't get in the way now if i were to print the data type of my age variable as you can see it is of the int data type short for integer it only stores a whole integer number now what if this was a string so what i'm going to do is surround my value within a set of quotes and i will turn this line into a comment so that it does not get in the way you can see that the data type of my age variable is now a string and with strings we cannot normally use them for any sort of math so let's attempt to increase our age variable by one and we ran into an error a type air can only concatenate string to string not end now the point being is that it's important to use the appropriate data type because with strings we cannot normally use them for any sort of math you'll want to use a data type of a numeric value an int or a float which we'll discuss a little bit later now here's a situation to consider what if we would like to display our edge variable along with a string literal much like what we did with this line involving a string literal such as hello plus the user's full name so let's attempt to do so and this is not going to work and i'll explain why so within our print statement let's say something such as your age is plus edge now we're going to run into a type error that's because we attempted to use string concatenation with a string literal and a variable of a different data type a variable of the int data type in order to display our edge along with the string we would need to convert our edge variable to the string data type and one way in which we can do that is by type casting and we'll cover this more in the next video so we're going to surround our age variable that is of the in data type with a set of parentheses and precede this with str short for string and this will convert our variable to a string that will allow us to display it with another string now if we were to run this program this way this will now display your age is and in this case 22 so if you need to display a variable of a different data type along with the string you would just need to use a stringcast to convert that data type to a string but we'll cover this more in the next video on typecasting so that is the int data type it stores a whole integer number and the next data type is the float data type and i'm going to turn these lines into comments and we can move on now the float data type is a numeric value that can store a number that includes a decimal portion an int data type cannot store a decimal portion that's why it's in short for integer it only stores a whole number this time let's say we have a height and i will assign this a perfectly normal height of maybe 250.5 centimeters so this decimal portion is important that's indicating that this is a floating point number a float for short so let's print our height to the console window print height and this will print whatever my height is and now let's check the type of our height using the type function so within a print statement i'm going to add my height surround this with another set of parentheses and precede this with the type function and the data type of my variable height is a float short for a floating point number a numeric value that contains a decimal portion and now for practice let's print our height along with a string literal so let's create a string literal such as your height is plus height but guess what we're going to do some type casting so surround height with a set of parentheses and precede this with str so that we convert height to a string so that we can use string concatenation within this print statement and this will print the message your height is 250.5 actually let's add centimeters to the end so plus cm and there we go and that is what a floating point number is float for short it is a numeric value that contains a decimal portion now the last data type that we're going to cover is the boolean data type it is a variable that can only store true or false let's say we have a variable called human if we were to assign this a boolean value this would be either true or false and we can print whatever this value is let's print whatever human is and this will display false now the reason that you may want to use booleans instead of strings even though you can still store a string representation of the word false or true is that these are very useful when we get to if statements we can check to see if some statement is true so that is a good use of boolean values now let's check the data type of my human variable so let's print type human and this will print to the console window bool short for boolean now make sure you're not putting this within quotes because then it's technically a string and they behave differently now the data type is a string and you may have noticed as well that the font color has changed between strings and boolean values so that's another good indicator now what if you need to display your value along with a string using string concatenation well guess what we're going to typecast again so let's print something r u a human so we need to use string concatenation so i will convert my boolean variable of human to a string and i have been programmed to inform you that yes i am in fact a human that is true well everyone that is the basics of variables it is a container for a value and they behave as the value that they contain there are four basic data types strings which store a series of characters inc which store a whole integer floats which are floating point numbers a numeric value with a decimal and booleans which only store true or false and they're very useful with if statements so that is it for variables if you would like a copy of all this code i will copy and paste all of this to the comments section down below but yeah that is how variables work in python hey people what's going on it's bro hope you're doing well and in this video i'm going to explain multiple assignment in python so sit back relax and enjoy the show well then since you clicked on this video i should probably explain what multiple assignment is now multiple assignment allows us to assign multiple variables at the same time using one line of code here's an example of us using standard assignment let's say we have a variable name and i will set this to a value of my name but you can use your name for this example let's say edge equals 21 and how about a variable called attractive i think i'm going to set this to true okay so we have a bunch of variables and then we can print the value of these variables with some print statements so let's print name age and attractive so we have name age attractive and as you would expect this prints bro 21 and true now another way in which we could write the same code is to use multiple assignment and this allows us to assign multiple variables at the same time using one line of code so i'm going to turn all of these lines into comments and this time we will only use one line of code but to do this we're going to list all of our variables separated with a comma so that would be name comma edge comma attractive and we will set them equal to those values but in the same order separated by commas so that would be bro comma 21 comma true and this would do the same thing only using one line of code here's another example let's say we have four variables spongebob patrick sandy and squidward and let's pretend that they're all around maybe 30 years old at least it seems like they're around 30 years old but i could be wrong i'm not too familiar with spongebob lore so let's set them all equal to 30. now we could write this using four lines of code or we could use multiple assignment to write the same thing using one line of code so if all of these variables are all equal to the same value there's a little bit of different syntax here so let's begin with the first variable of spongebob equals patrick equals sandy equals squidward then we're going to set them all equal to 30 and this should work just fine using only one line of code well everybody that's pretty much it for multiple assignment it allows us to assign multiple variables at the same time using one line of code i will post all of this code in the comments section down below and well yeah that's how multiple assignment works in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to demonstrate some useful string methods in python so sit back relax and enjoy the show all right let's do this in this video i'm going to be explaining and demonstrating a few useful methods available to us for strings now let's create a variable called name for this example and you can use your own name if you want so we now have a variable called name and for my first example let's print the length of our name variable so to do that we can surround our name variable with the length method and this will print and return how long the length of our string is and for me the length of my name variable is three for three characters if i were to increase the size of my name well then that's going to change to a so that is the length method and i'm just going to turn this line into a comment and let's move on so next we have the find method i just copy and pasted print name so i can reuse it name dot and actually if you have intellisense setup if you add dot after your variable you'll get a suggestion or a few suggestions of different methods and other features that you have access to so let's find find which is uh screw this i'll just type find find then we can find the first index of where this character is let's say i would like to find where capital b is well that is at index zero because computers always start with zero so this first character would be zero then r would be one and then o would be two for this example all right so that is how to find a character within a string moving on so let's capitalize our name and i should probably make this lowercase so name dot capitalize and this will make my name capitalized but if there's any spaces and then additional words it's not going to capitalize that only the first letter and your string next we have upper this will make your string all uppercase name upper and now it is uppercase guess what's next lower name dot lower and i should probably make this capital again and everything is lowercase we're making some good progress today next we have is digit this will return true or false depending on if our string is a digit which it's not so this will print false if i changed my string to a bunch of numbers like 1 2 3 then this will return true let's change that back and move on next we have is alpha are these alphabetical characters oh make sure you add the parentheses afterwards my bad false because we added a space within here now it's true so you can use is alpha to check to see if your string contains only letters alphabetical letters next we have count we can count how many characters are within our string i would like to count how many o's are in here and this should return two that's right okay we're almost at the end we can replace characters within our string so we use the replace method and we pass in two arguments the character we would like to replace and the character we would like to replace our character with i would like to change all o's to a's and now my name is brock hod oh you guys are gonna like this next one this isn't technically a method but it's a really neat feature so one thing that we can do that's available to us with python is that we can display a string multiple times by multiplying that string by a given number so let's say i would like to display my name three times i can just take my string variable then add times three and this will print my name three times bro bro bro like i said not technically a method but it's a useful feature that you might be interested in that's related all right everybody so that is a few useful methods available to us for strings if you would like a copy of all this code i will post this in the comments section down below but yeah those are a few useful methods available to us for strings hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to teach you guys all about typecasting in python so sit back relax and enjoy the show all right welcome back everybody i have a super quick video for you guys today on the subject of typecasting now typecasting is the ability to convert the data type of a value to another data type here's an example that i've written already i'm just going to paste it i have three variables for this example x y and z x contains one this is a whole integer into for short y contains two point zero this is a floating point number float four short you can tell it's a float because it ends with a decimal portion and z contains a string of three a string is a series of characters and you can tell it's a string because it's surrounded with a set of quotes and remember with strings we cannot normally perform math on strings so i have three print statements for x y and z and as you would expect they contain the values of one two point zero and three now let's begin by converting both y and z to the integer data type via typecasting in order to perform typecasting on a value or variable type that value or variable and surround this with a set of parentheses whoops i missed and then pre-save this with the data type you'd like to convert this value or variable to i would like to convert y to an integer and then you can use this for whatever you need so i'm going to replace y within my print statement with y after we typecast it as an integer and this will display 1 2 not 2.0 it's the whole integer of 2 and then 3. so this is not a permanent change if you need to make this as a permanent change to y you'd have to reassign it so let's say y equals y and then we're going to typecast y so let's round this with a set of parentheses and precede this with the data type we'd like to convert y2 so now y is a whole integer and then we will print y without typecast this time and our result is one two three now z z is storing a string and with strings we cannot normally perform any math on strings for example within my print statement i will state z times three you would think that the result would be nine right well you're wrong it's going to print three three times if you need to convert a string to a int or a float you would just have to typecast it so this time let's type cast z as an integer z int and we will type cast z as an integer so then if we have z times three the result is now 9 instead of 333 so that's the basic formula for type casting now let's convert these to floating point numbers but let's include x as well because x is feeling left out so let's convert x to a floating point number so float parenthesis and we will surround this with x and display x and actually let's convert y and z to floats as well because why not the results are now 1.0 2.0 and 9.0 remember that we multiplied z times three and then if we need to convert these values to a string we would use the string cast so the results now are 1 2.0 and 333 now you might be thinking to yourself when would you need to convert an integer or a float to a string here's a situation let's say within our print statements we need to print these variables along with another string so within our print statement let's say x is plus x we would like to display these together and let me copy this and do the same thing for y we'll say y is plus y you cannot normally display a string along with an integer or a float because we're using some string concatenation so this will result in a compilation error can only concatenate string not int to string so that's a situation in which you might need to use typecasting to convert an integer or float to a string so let's display x and y as strings via typecasting so we'll surround x and y with a set of parentheses and precede this with the data type we'd like to convert these values to we would like to convert x and y to both strings and now this will compile and run just fine well everybody that's the basics of typecasting if you would like a copy of all my code i will post everything in the comments down below if you found this video helpful don't be afraid to help me out by smashing that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's bro hope you're doing well and in this video i'm going to teach you guys how we can accept some user input in python so sit back relax and enjoy the show ladies and gentlemen this is where the fun begins in this video i'm going to explain how we can accept some user input in python and we do so by using the input function and then we type in our input to the console window but it would probably be good practice to let the user know what we want them to type in exactly so let's ask for somebody's name within quotes inside the input function i'm going to type what is your name and now our program will wait for us to enter in some user input so you can use your own name for this example i'm going to type bro now to submit some user input you just type or press enter now you can see that my process finished with exit code zero that means the program is done running so we should probably do something with this value we can actually assign it to a variable so we can use it elsewhere in our program so to do so we precede input with a variable like name works name equals input and when we accept some user input we will assign it to this variable that we called them and now we can do something with it so let's print a message involving our name variable that we have so how about hello plus name now when i run this program we can accept some user input and then do something with that input such as display message that says hello bro and then you can type in whatever you want for your name let's say i'm dude what is your name dude hello dude now this next part is very important when we accept user input it is always of the string data type a series of characters what if we need to accept a number well you can but you can't normally perform any math on it because it's of the string data type we would need to cast it as either of the integer data type or of the float data type so here's an example of why we can't perform any math on a string let's say we have a variable called edge age equals input and let's ask how old somebody is how old are you now i will add one to somebody's age let's pretend it's their birthday age equals age plus one this will add one to their age now let's try and run this what is your name bro how old are you let's say that i'm 21. okay we ran into an error a type error can only concatenate string to string with what i mentioned previously we cannot normally use strings for any sort of mathematical equation or operation we'll want to cast it to the integer or the float data type so let's cast our user input to the integer data type and we will surround our user input with a cast surround your input with a set of parenthesis and precede this with int and now we can use this user input in a mathematical operation so let's try it even though this won't display age yet so what is your name bro 21 and our program finished with an x a code of zero there were no problems now let's attempt to display this edge so i will print u r plus age plus years old we're doing some string concatenation here what is your name bro how old are you 21 all right we ran into a type error again can only concatenate string to string you cannot normally display a variable of the integer data type along with strings because we're doing string concatenation we're adding strings together we would need to convert this variable back to the string data type so we can cast it we'll surround our edge variable with a cast now this is what's going to happen we will accept some user input it will be of the string data type and then we will immediately cast it to be of the integer data type so that we can treat it as a number instead of a character and then if we need to display this edge we will need to convert it back to a string so that we can use some string concatenation and display all of these strings together and now let's try this theory so what is your name bro how old are you let's say i'm 21 hello bro you are 22 years old here's a situation what if we enter a number that contains a decimal portion so let's try this again let's say i'm 21.5 years old well now we ran into a different issue a value error invalid literal for int with base 10 that means if we cast a string as an integer it can only be a whole number a portion that does not contain a decimal and that is where the float data type would come in it is a data type that can contain a decimal portion for this example let's create a third variable called height and we will ask for somebody's height input we'll create a prompt that says how tall are you and we will cast this to be of the float data type so that our string our user input can contain a decimal portion and then we can treat it as a number instead of a series of characters and i think i will delete this line we won't really need it anymore and then let's print their height along with a message u r plus then height but we need to cast this back to being a string so we'll surround our height with a cast plus let's say cm tall all right let's test this what is your name bro how old are you let's say i'm 21 how tall are you let's pretend that i'm 250.5 centimeters tall i'm adding the 0.5 just to test to see if this will accept a floating point number hello bro you are 21 years old you are 250.5 centimeters tall not really all right everybody so that is the basics of user input in python normally with user input it will give you a value of the string data type if you need to use that value for any sort of math you'll probably need to cast it to be of the integer or the float data type so if you would like a copy of this code i will post this in the comment section down below but yeah that's how to accept user input in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to demonstrate a few useful functions related to numbers in python so sit back relax and enjoy the show okay let's begin in this video i'm going to be demonstrating a bunch of useful functions related to numbers and a bunch of these functions are located within the math module now let's create a variable for this example let's say pi equals 3.14 just the first few digits of pi is fine for this example and now here's a bunch of useful functions that you guys would probably be interested in the first is round round is a built-in function and all we do is type round then add a set of parenthesis and then we can pass in a value or a variable as an argument and the round function will round that number for us so pi rounded to the nearest whole integer is you guessed it three now we can round a number up by using the seal function of the math class seal short for ceiling so let's print our result and in order to access this function within the math module we would type the name of the module dot and here's a bunch of functions that we have access to so we are looking for seal and it's actually at the top here for me and at seal we'll round a number up to the nearest whole integer so pi rounded up is four then on the flip side we can round a number down by using floor and that is also located within the math module so let's type math dot floor and pi rounded down would be three up next i have the absolute value function but it's abs for short abs will give you the absolute value of a number so the absolute value of pi actually let's make this negative 3.14 the absolute value will tell you how far a number is away from zero so if you pass in a negative number it will give you a positive number so that is abs short for absolute value next we have the pow function pow will raise a base number to a power let's raise pi to the power of two so we pass in two arguments a base and an exponent pi to the power of two is nine point eight and some change so that is the pow function next we have square root so this is located within the math module we'll type math dot s q r t short for square root and the square root of pi is let's find out oh i guess we can't pass in pi uh let's round a different number like 420 oh i guess that's because i made pi negative okay so the square root of 420 is 20.4 and some change so that is the square root function all right we have two left we have the max function the max function will find the largest of a varying amount of values so let's create three variables for this example let's say x equals one y equals two and z equals three we can use the max function to find the largest of these values so within a print statement let's use the max function and pass in all of the different values or variables that you would like to compare so i would like to find the largest value between x y and z and the result in this example is three now the min function will find the lowest so min and then pass in your values or variables so i would like to find the minimum value between x y and z and in this case it is one well everybody those are a few useful functions that you guys might be interested in if you guys would like a copy of this code i will post this in the comments section down below but yeah those are a few useful functions related to numbers in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain string slicing in python so sit back relax and enjoy the show all right then let's talk about slicing slicing can be used to create a substring by extracting elements from another string the same principle can also be applied to different collections as well but in this video we're going to be focusing on slicing strings now to slice a string we can either use the indexing operator which is a set of square brackets or by use of the slice function to create a slice object this is a little more complex we'll discuss the slice function near the end of this video so with slicing there are three optional arguments three fields that we can fill in depending on where and how we want to slice our string a starting index a stopping index and a step let's begin with the starting index now for this example let's say we have a string variable called name and this will store a value of whatever your own full name is yes i legally change my name to bro code you can use your own name for this if you want so what i would like to do is to create a substring based off a sliced portion of my full name so what i would like to do is create a substring based off of just the first part of my name just bro so let's begin by creating a substring maybe i'll call this first name equals now to slice a string type in a string or the name of a variable that contains your string and follow this with the indexing operator and like i said we'll discuss the slice function a little bit later so we need a starting index and a stopping index but we'll begin with the starting index where do we want to begin our slice so computers they always start with zero so the first character in your string will have an index of zero i would like my slice to begin at index 0 so i'll list that for the starting position the starting index so let's test this just to be sure it works i'll just print first name and let's see if this prints capital b which it does so following that same pattern the next character within my string would have an index of one that would be r then the next index two would be o and three should be an empty space all right so that is the starting index within string slicing if we would like to slice an entire portion of our string not just one letter we need a stopping index as well and both of these fields are separated with a colon so let's say i would like to slice the first three characters of my string so this would have an index of zero one two and this isn't going to work as you would imagine and i'll explain why so you would think that indexes 0 through 2 would give us three letters right but it only gives us two so this first index is inclusive the stopping index is exclusive so if i want the first three characters the first three letters in the string i would need the starting index to be zero and the stopping index to be three and now this should print my first name and not anything else there is a shorthand way of writing this too so if you were to leave this first index blank for start well python is going to assume that this is zero the beginning of your string so this would be no different than what we had previously just having colon three now let's try and create a separate substring for a last name so last name name now we need a starting index and a stopping index so we need the starting index at least so this would be zero one two three four four colon and where do we want this to stop zero one two three four five six seven and remember that this is exclusive so we're going to place eight here and now i would like to display last name and this should just display code and a shortcut is that if you were to leave stop blank but you still have that colon this is a shorthand way of writing i would like every character starting at index four and everything after until the end so there would be no change to this as well you can write it either way okay so we still have to discuss step step is an optional field that we can set a value to so step is how much we're increasing our index by between starting and stopping so it is entirely possible to create a substring that will count only every second character after the first normally step is one by default but if we were to set that to two we're going to count only every second character so let's try this maybe i'll create a new variable called funky name because i really don't know what else to call this for this example let's say funky name equals name and i'm going to count only every second character including the first so the indexes would be zero colon eight for my example but if you're using your own name that's probably going to be something different so the default first step is one and if i were to display funky name as it is currently this will just display my full name but if we set step to two this will only display every second character including the first so funky name is now for me at least b o c d now if step was three this will print only every third character including the first where it's b space d a shorthand way of writing this is that you could leave start and stop empty but the important thing is to have these two colons python is going to assume that if you leave your starting index empty you're referring to index 0 the beginning if your second index your stopping index is empty python will assume this will be the very end of your string so just having two colons and then step three would be no different than what we had previously or this next part i'm going to explain how we can reverse a string in python so let's create a new substring variable called reversed name equals name i would like to use the entire string so i can just use two colons python will fill in the rest so for the step this is going to be negative one it's kind of like we're counting backwards and we're going to create a new sub string based off my name but in reverse so if i were to print my reversed name this is now edok orb i think that's how you pronounce it so that's how to reverse a string in python using slicing now let's move on to part two of this video i'm going to be explaining the slice function and we can use the slice function to create a slice object which is actually reusable so that's somewhat convenient let's take a different scenario this time let's say we have a website url website equals http colon2forwardslashes google.com but use whatever website you want what i would like to do for this program is remove and create a substring based off the website name and not anything else i would like to exclude the http portion as well as the dot-com portion of this website url so let's break it down step by step our first step is to create a slice object so i will name the slice object as slice slice equals and i will invoke the slice function so within the parentheses of the slice function we can add up to three values a start a stop and a step exactly the same as what we did with indexing however with the slice function we separate each of these values with a comma instead of a colon but it works the same way so we would like our substring to begin where the name of the website begins so we would like our start to be zero one two three four five six seven so i will pass in seven for where my substring will begin and now each value within the slice function will be separated with a comma instead of a colon like what we did with the indexing operator now for the stop index that's going to be a little bit tricky and let me explain why one issue that we're going to run into is that not all website names are consistent with their length they can really vary so it is not possible for us to use the same stopping index for each of these website urls so one way in which we can account for that is to use what is called a negative index each character within a string has a positive index as well as a negative index and a negative index works almost exactly the same way except the character most on the right begins with a negative index of minus one and the character on the left of that would be negative two negative three and negative four it's as if you're counting backwards so with indexing we can use some combination of positive and negative indexing so i would like my substring to end where this dot is so this would have a index of minus one minus two minus three minus four and remember that this is exclusive so i would like my slice to begin at index seven and a negative index of four for the stopping position so that will give me just the website name and remove the http portion as well as the dot com portion of my website url and now we have a slice object and we can reuse this so to apply your slice object type in the name your string index operator and place your slice right within here and let's print this so print our website and apply the slice to it and now this should give us just the website name and now let's test this with maybe another website i'll rename this as website one and let's create website2 and let's try a different website name for goodmeasure so let's try wikipedia so we can reuse our slice object and we will apply our slice to website two this time and this should remove the url portions http as well as com all right everybody so that is slicing strings in python you can either use the indexing operator or the slice function to create a slice object if you would like a copy of all this code i will post all of this in the comments section down below but yeah that is how string slicing works in python hey what's going on people it's you bro hope you're doing well and in this video i'm going to explain if statements else if statements and else statements and python so sit back relax and enjoy the show all right people let's talk about if statements an if statement is a block of code that will execute only if its condition is true it's a very basic form of decision making with programming for this example let's create a prompt where we will ask a user for their age and depending on what their age is we will print a response so let's say age equals input and then we will add a prompt how old are you now this will return a string so we should probably cast this as an integer data type so we now have a variable called age where we will accept some user input let's check somebody's age with a variety of if statements so let's check to see if somebody's age is greater than or equal to 18 so to create an if statement type if and then some sort of condition if age is greater than or equal to 18 to finish this if statement add a colon at the end now pay attention to this if i move down to the next line you'll notice that my cursor is now indented any indented code underneath an if statement is the block of code for that if statement so if this condition is true we will execute some block of code if it's false we'll skip over it so if somebody's age is greater than or equal to 18 let's print you are an adult and let's try this program how old are you let's say i'm 21 so my condition when we get to the if statement is going to check to see if this condition is true if it is true we're going to execute this block of code if it's not we skip over it so how old are you let's say i'm 21 i'm going to hit enter and my if statement is true so we execute this block of code which prints you are an adult so what if this condition is false let's say i'm 12. well then we're just going to skip over this block of code and continue on with the rest of the program if you would like your program to take some other course of action if this condition is false we can add an else statement so after the if statement add else make sure you get the indentation right you don't want this within the block of code for the if statement so if this condition is false we can take some other course of action so if somebody's age is less than 18 let's print you are a child so let's try this again i'm going to enter that i am 12 years old not really but let's just pretend i am so this will now print you are a child if this condition is false perform this block of code for the else statement so with if statements we can check more than one condition before reaching the else statement by using an else if statement and we add that after an if statement so it's shortened to e l i f for else if so let's check to see if somebody's age is less than zero for some reason so let's print you haven't been born yet so with if statements we start at the top we first check the if statement if this is false we move down to the next statement to check then we check our else if statement if this is also false then we resort to the else statement the else statement is sort of like a last resort if all conditions evaluate to be false then we execute the else statement so let's try this how old are you let's say i'm negative 1 years old you haven't been born yet so with if statements we always begin with an if statement and we check that condition if that condition evaluates to be false then we will skip this block of code and move down to the else if statement if there is one it's optional if this condition is also false then we will use our else statement as a last resort if there is one if there is no else statement then we just skip over all of this then and continue on with the rest of the program so you can add more than one else if statement so let's check something else let's check to see else if age is equal to 100 so if you need to check to see if a value is equal to a particular value make sure you use double equal signs this is the comparison operator for equality if you use just one equal sign that's the assignment operator and python thinks you're attempting to set age equal to 100 so if you want to check to see if age is equal to 100 then use double equals so let's check to see if somebody's age is equal to 100 so let's print you are a century old now pay attention to this if i were to run this program how old are you let's say i'm 100. so this is printing you are an adult that's because we first check our if statement and well we're 100 years old and 100 is greater than or equal to 18. so we print this block of code we execute this block of code and then we skip everything else even though age is equal to 100 within our else if statement so the order of your if statements does matter so let's change this around let's add this to the very beginning and this will be our if statement and we will set age is greater than or equal to 18 to be an else if statement so we're first going to check to see if age is equal to 100 if not we will check to see if age is greater than or equal to 18 and we just follow that order so let's try this again how old are you i am 100 years old you are a century old so we first check our if statement if this condition is true we will execute this block of code if it's false we just go down the order till we reach our else statement well everybody that is the basics of if statements we have if statements else if statements and else statements so if you would like a copy of this code i will post this in the comments down below but yeah that is how if statements work in python hey what's going on everybody it's bro hope you're doing well in this video i'm going to explain logical operators in python so sit back relax and enjoy the show all right everybody let's talk about logical operators these are used to check if two or more conditional statements are true so we'll be discussing the and as well as the or logical operators there's also a third one called not but that works a little bit different and i'll explain why so let's create a program to demonstrate this let's create a program where we will ask somebody for the temperature outside and then depending on the temperature if it falls within a certain range we will print a message so we'll need to use and as well as or logical operators to do this so here i have a prompt temp for temperature equals input what is the temperature outside so i'm going to cast this as an integer data type so what if we want to check to see if our temperature is within a certain range we can use the and logical operator to check two or more conditional statements this is how we might do that let's check if temp is greater than or equal to zero zero degrees celsius and we can check another condition too if temp is less than or equal to 30 degrees celsius so we need to add a colon at the end to finish this if statement and let me just fix some of the spacing okay so with the and logical operator in order for this entire condition to be true both conditions must be true this needs to be true and this needs to be true so if our temperature is equal to or above 0 as well as being less than or equal to 30 that means our temperature falls within a certain range so let's print a message such as the temperature is good today print go outside all right let's try it so what is the temperature outside let's say it's 20 degrees celsius well the temperature is good today go outside this condition is true 20 is greater than or equal to zero and temperature is less than or equal to 30. let's try a different temperature like negative 20 degrees celsius so it's really freaking cold outside right now as you can see nothing happened because our first condition was false our temperature is not greater than or equal to zero but our temperature is less than or equal to 30 so our second condition is true but our first condition was false and in order for this entire statement to be true since we're using the and logical operator both conditions must be true in order for this statement to be true now let's discuss the or logical operator we can check to see if our temperature is below or above a certain range so let's write else if temp is less than zero or temp is greater than 30. so that means it's going to be either very cold outside or very hot outside so let's print a message the temperature is bad today print stay inside all right let's try this again what is the temperature outside it is negative 20 degrees outside the temperature is bad today stay inside so with the orological operator as long as one of these conditions is true then the entire statement is true it doesn't matter if one of them is false as long as one of them is true then the entire statement is true last but not least we have the not logical operator this works a little bit different from the and as well as the or logical operator because we can check one or more conditional statements instead of two or more conditional statements so what the not logical operator will do is that it'll take a conditional statement if it's true it's going to flip it to false if it's normally false it's going to flip it to true so for this example we have another way in which we could write this although it's a little more complex so if our statement is true what we can do is that we can flip it to false using the not logical operator if it's normally false we can change it to true so what we'll do is surround one or more conditional statements with a set of parentheses and precede everything within the parentheses with the not logical operator so if the statement is normally true it's going to become false using the not logical operator if it's normally false it's going to be true then let's do the same with the else if statement so surround one or more conditional statements with the not logical operator so now these roles are going to be kind of reversed so let's try this again what is the temperature outside it is negative 20 degrees outside the temperature is good today go outside so what we should probably do is kind of reverse these rolls so i'm just going to swap everything within these if statements with each other and now this should work the same as it did before but we just wrote it a little bit different what is the temperature outside it is 15 degrees outside 15 degrees celsius the temperature is good today go outside so with the not logical operator you can surround one or more conditional statements with the not logical operator and what this will do is flip it from being false to true or from true to false well everybody that's the basics of logical operators in python if you would like a copy of all this code i will post this in the comments down below but yeah that's the basics of logical operators in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain while loops in python so sit back relax and enjoy the show so while loops a while loop is a statement that will execute its block of code as long as its condition remains true later on in this video for this example we're going to create a program where we will prompt a user to enter their name if they attempt to skip that prompt then we will continually ask the user to enter their name and they can't continue on with the rest of the program until they do so the key thing to keep in mind with while loops is that you'll want some way to eventually escape the while loop if you don't have any way to escape the while loop that's referred to as an infinite loop so let's create an example of an infinite loop because it's fun so to create a while loop type while and then some sort of condition so for our condition let's say while one is equal to one so this will always be true now what do we want to do when we execute this block of code let's print something print help i'm stuck in a loop all right so let's try this while one is equal to one print this statement and we will just continue on and on within this while loop because we have no way to escape this while loop so now let's use this concept and write a program where we will prompt a user to type in their name if they don't type in anything then we will continue to prompt them to type in at least something so let's say name is equal to and then to just keep this blank we'll just set this to a set of quotes and then let's write a while loop here while name and let's check the length of name if the length of our name is equal to zero then we will ask the user to type in their name name equals input enter your name so then once we escape the while loop let's print something print hello plus name whoops hello plus name alright so when i run this we are giving the user a way to escape the while loop they have to type in something for their name as long as the length of my name is equal to zero keep on printing this prompt enter your name so i'm just going to hit enter a bunch of times enter your name no enter your name no enter your name no so we are stuck within this loop until we enter something for our name so this time let me type in a name then hit enter so therefore our condition is now false the length of my name is now one two three so three is not equal to zero therefore our while statement our while loop is false and we continue on with the rest of the program there are a few variations in which you could write the same program so let's write this a different way what we could do is say name is equal to none while not name and this will pretty much do the same thing it's just another way of writing this well everybody that's the basics of while loops a while loop is a statement that will execute its block of code as long as its condition remains true for our example we asked the user to type in their name if they were to leave it empty or blank we would keep on asking the user to type in their name so if you would like a copy of this code i will post this in the comments section down below but yeah that's the basics of while loops in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain for loops in python and at the end of this video we're going to create a countdown timer so sit back relax and enjoy the show all right guys and gals let's talk about for loops a for loop is a statement that will execute its block of code a limited amount of times it's similar but different from a while loop because a while loop could iterate an unlimited or infinite amount of times depending on the condition a for loop will only iterate a limited amount of times and before we start executing its block of code we already know how many times we're going to repeat this block of code so for this example let's create a for loop that will simply count it to 10 and then we'll create a few more sophisticated examples so to create a for loop that will count up to 10 this is what we'll type four and then we need some sort of counter people usually either write index or they shorten it to just i i for index four i in and we can set a range range ten so we will execute this for loop ten times and to finish this for loop just add a colon at the end so the next line or lines will be indented so that's the block of code for the for loop what do we want to do during each iteration let's just print what i is and let's take a look to see what would happen so we executed this for loop ten times except with computers computers always start with zero so when we said four i in range ten we're counting numbers zero through nine so it's as if this number is exclusive so there's two ways we can change this we could say range ten plus one or what i would do is say print i plus one so this will give us numbers one through ten so that's a for loop it will execute a limited amount of times this time let's count a range between two numbers not necessarily 0 to 10 but something else so let's say 4i in range maybe the numbers 50 through 100 so within my range function i will pass in two numbers the first number will be the starting point and the second number is the ending point this first number is inclusive and the second number is exclusive so let's print this print whatever i is so this will count 50 through 99 actually if you wanted to include this last number since it's exclusive what we could do is just add one to the end so this would give us 50 through 100 except that this will iterate 51 times since we're counting 50. so you just have to pay attention to your range and the numbers that it's counting now one thing that you can do with the range function is that you can add a third argument and this will function as the step how much you want to count up or down by so this time let's count up by two so i'll add comma two we're passing in a third argument this time so this program will now count up by two starting at fifty and go all the way to one hundred a benefit of for loops is that we can iterate through anything that is considered iterable this could include a string the letters in a string or any sort of collection so this time let's create a for loop that will iterate once through each letter in maybe a name so for i in and let's type a name here type in whatever your first name and last name is and then we will print whatever i is for i in whatever your name is print each letter in the string so when i run this each letter within my name will be printed to a new line all right people for my last trick we're going to create a program where we will simulate a countdown starting at 10 and count down to zero and then maybe once we reach zero we can print something such as happy new year so to create this program we'll need an import so at the top we're going to import the time module because we'll be waiting one second after each iteration of this for loop so to create this program let's say four you could say i but you can really write anything here and to demonstrate that let's say four seconds four seconds in range so the starting point is going to be ten the ending point will be zero and we'll add a step what do we want to count up or down by let's set this to negative one so this will be a countdown starting at ten and ending at zero so after each iteration let's print whatever i is or in this case seconds and then we can sleep have our thread sleep for a number of seconds too so after we print seconds type time dot sleep and pass in how long you want to sleep for i would like to sleep for one second and then at the end let's print happy new year make sure this isn't within the for loop print happy new year and well that's it let's test this so we'll begin at 10 and count down to zero and you can see that my thread that is running this program is sleeping for one second after each iteration of this for loop then once we reach zero it will display happy new year well everybody that's the basics of for loops a for loop is a statement that will execute its block of code a limited amount of times it's different from a while loop because a while loop could execute an infinite or unlimited amount of times with for loops they execute limited amounts of times and before we enter the for loop we already know how many times we're going to iterate this for loop if you'd like a copy of all this code i will post this in the comments down below but yeah that's how for loops work in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain nested loops in python so sit back relax and enjoy the show hey all you people let's talk about nested loops a nested loop is a general concept of having one loop inside of another loop and that's really it it doesn't matter if it's a for loop or a while loop so the inner loop will finish all of its iterations before we finish one iteration of the outer loop and to best demonstrate this we're going to create a program where we will draw a rectangle made out of a certain symbol that we choose we need to set a width and a height and to best do this we'll need to use a nested loop we'll create a few prompts one for rows columns and a symbol that we want to make a rectangle of so let's begin with rows rows equals input how many rows and we'll need to cast this as an integer data type because we're working with numbers okay let's do the same thing for columns so replace rows with columns for this next line input how many columns and we'll create a symbol variable symbol equals input and this we don't have to cast enter a symbol to use now it's time for the nested loops we're going to create an outer for loop as well as an inner for loop the outer for loop will be in charge of the rows the inner for loop will be in charge of the columns so let's begin by creating our outer loop so we'll write 4 i in range rows we would like our outer for loop to iterate as many times as we have rows and we're going to create an inner for loop that will iterate as many times as we have columns so within the block of code for the outer for loop we're going to create another for loop this time it'll be four and a common convention for inner loops is to write j as an index because j comes after i i guess so for j in range columns so our inner for loop will iterate for as many times as we have columns all we'll do within the inner for loop is print our symbol that we have except we'll have one issue using a print statement after we use the print statement we will enter a new line character and move down to the next line we can actually prevent that by adding comma and equals quotes so after using a print statement this will prevent our cursor from moving down to the next line so pay attention to the indentation too so there's kind of two levels of indentation we're currently within the inner for loop so that's pretty much it for the inner for loop now we're going to print a new line once we exit the inner for loop and you can see that the indentation is on this line right here we're within the outer for loop now and that's pretty much it so let's try this program how many rows let's say five rows how many columns perhaps six what symbol do we want to use let's say the dollar sign and let's try it there we go there's our rectangle so we have let's see six columns one two three four five six and five rows one two three four five in summary a nested loop is really just this concept of having one loop inside of another loop it doesn't matter if it's a while loop or a for a loop it's really situational the inner loop will finish all of its iterations before finishing one iteration of the outer loop so what we did to demonstrate that is that we had the outer loop in charge the rows and an inner loop in charge of the columns for our rectangle program so if you would like a copy of this program i will post this in the comment section down below but yeah that's the basics of nested loops in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain loop control statements in python so sit back relax and enjoy the show all right ladies and gentlemen let's talk about loop control statements these are used to change a loop's execution from its normal sequence and there are three we're going to discuss break continue and pass let's begin with break break is used to terminate the loop entirely now here's a good example of where a break would be useful let's say while true we're going to continually ask for somebody's name if they don't type in anything then we'll continue the while loop over and over again so let's say name equals input enter your name now if name does not equal a set of quotes that means they don't type in anything then we will break and break out of this while loop and let's test it enter your name nah i don't think so i'm too lazy to enter my name all right i can see that i'm not going to escape this while loop so i'm going to type in my name because i give up and hit enter therefore i will break and exit out of this while loop so a break is used to terminate the loop entirely when it's encountered next we have continue continue skips to the next iteration of the loop now let's say we have a phone number phone underscore number and i will set the sequel to let's say a random phone number including dashes 123-456-7890 what i would like to do is to display this number within the console window without these dashes this is how to do that using a continue control statement for i in phone number so for each character within our string of phone number what we'll do is check to see if we encounter a dash character if i i is our index is equal to a dash then we want to continue and skip over this iteration of the loop so continue then i would like to print whatever our indexes whatever character we're working on so if i were to run this as it is it's going to print each digit on a new line so with print statements they will add a new line character to the end of your string and you can actually change that by adding to the end comma end equals and then a set of quotes so this will print my phone number without any dashes one two three four five six seven eight nine zero so that's a use of the continue control statement it skips to the next iteration of the loop last but not least we have pass pass does nothing it acts as a placeholder let's say that i would like to print the numbers 1 through 20 using a for loop for i in range 1 through 21 and remember that the second digit is exclusive so this will iterate once through the digits of 1 through 20. let's pretend that i'm highly superstitious and i don't want to print the number 13 because 13 is considered an unlucky number if i is equal to 13 what we'll do is pass and pass acts as a placeholder and it won't do anything else print i that's one i there we go this will print the numbers 1 through 20 and skip 13 because we used the past control statement which does nothing it acts as a placeholder so everybody those are loop control statements they change a loop's execution from its normal sequence we have break continue and pass so if you would like a copy of all this code i will post all of this in the comments section down below but yeah those are a few loop control statements in python what's going on everybody it's bro hope you're doing well and in this video i'm going to explain lists in python so sit back relax and enjoy the show all right ladies and gentlemen let's get down to business i got to explain lists to you all now a list is used to store multiple items within a single variable for example let's say we have a variable called food and i will store a string value of pizza because i like pizza what we could do is that we can store multiple items within this variable by turning this variable into a list and in order to do so we're going to surround all of the values that we would like to add to our list with a set of square brackets and boom there you have it we now have a list called food it is no longer a variable so what we could do is add multiple items to this list of food so let's add some other food items that we might like let's see i also like maybe some hamburgers and a hot dog and maybe some spaghetti i think i smelled spaghetti right okay so we now have a list called food now what happens if we attempt to print this list of food so print food so this will print all of the elements found in this list each item in a list is referred to as an element if we need to access a certain element of this list we have to list the index so next to our list we'll add a set of square brackets again and we need to list the numbered index of the element that we're trying to access now computers they always start with zero so the first element in our list would be element number zero the next one would be one two and three so if we need to access element zero which is in the first position we would say food square brackets and then within here list the index so the first position is zero and this will now print the first element of our list which is pizza let's attempt to access some of these other elements so the element at index one would be you guessed it hamburger two would be hot dog and three would be spaghetti now what happens if we attempt to access the element at index four well currently that's out of range because we did not assign a value so we're experiencing an error an index out of range error but if i were to add another element let's say pudding alright well then the element at index 4 would be putting then one important concept with lists is that you can always update and change the elements found within a list later on in the program after you declare one so let's say we would like to immediately change one of these elements let's say food at index zero i want to replace with maybe sushi because sushi is great so if i were to print the element at index 0 this would no longer be pizza because we updated element 0 to be sushi then and this prints sushi now if you need to display all of the elements found within a list you can easily do so with a standard for loop what we'll do is say for x in the name of our list which is food print x and let me turn this line into a comment all right so this for loop will print all of the elements found within our list of food and the results are sushi hamburger hot dog spaghetti and pudding all right people for this next portion i'm going to demonstrate a few useful functions of lists and to access some of these functions type the name of your list dot and there's a bunch to choose from here let's begin with event we can add an element to this list let's say at the end i would like to add ice cream so then if i were to display my list we now have ice cream at the end because we appended this value to my list of food so let's go over a few others so we can also remove a value food dot remove let's say i would like to remove hotdog so i'm going to type that within my function and this will remove hotdog and that is no longer here next we can pop food.pop pop will remove the last element so this will remove pudding we can insert a value at a given index food dot insert we need to list an index let's say zero that would be the first position technically that's where pizza is currently and i would like to add cake and at index 0 we now have cake so next up we have sort food dot sort this will sort a list alphabetically so in the first position we have hamburger hot dog pudding spaghetti then sushi we can also clear a list food dot clear and this will remove all of the elements of a list so this will not print anything because we cleared the list well everyone in conclusion a list is really just a variable that can store multiple values think of it that way so if you would like a copy of all the code that we have written here today i will post all of this in the comments down below but yeah that's how lists work in python how's it going everybody it's bro hope you're doing well and in this video i'm going to explain 2d lists in python so sit back relax and enjoy the show i have a super quick video for you all today on 2d lists also referred to as multi-dimensional lists all it is is a list of separate lists so let's begin by creating a few separate lists let's say we have a list called drinks and let's assign a few values let's say we have coffee as well as soda and maybe some tea all right so we currently have one list let's make maybe two more let's make a list called dinner and maybe in here we'll place pizza then hamburger and hot dog okay then let's create one more for this example let's say dessert and maybe we'll add two items they all don't need the same amount of items or elements so we have cake and ice cream all right so we have three lists one called drinks dinner and dessert so what we can do is add all of these lists to one list and let's create a list called food food equals and for each of these elements we're going to place our lists so we have drinks dinner and dessert check this out what if i were to print my 2d list of food so what ends up happening is that this will print all of the elements found within each individual list and they're all grouped together so this first portion is my drinks list which contains coffee soda tea this next element is my dinner list which contains pizza hamburger hot dog and the last element dessert contains cake and ice cream if i need to access just one of these lists i will add an index after my food 2d list and set an index number so index zero is referring to my first list of drinks and this will display all of the elements found within my first list and if i need just one of these elements i will add a second set of square brackets and list the index of the item that i'm trying to access so this very first item coffee would be index zero and then index zero again so we need two sets of square brackets and if i were to print this this will display coffee so if i go down the list the next element would be soda and then t if i were to change the index within this first set of square brackets well now we're working with a different list this time we're working with our dinner list so the element at index 1 index 2 that would be our dinner list and this will display the element of hot dog if i change this to the next list which would be dessert well we're going to receive an index out of range error because we only have two values within this list cake and ice cream there is no element at index 2 because we only added two elements to this list of dessert all right everybody so that is 2d lists also referred to as multi-dimensional lists it's a list of separate lists if you need to access one of the elements within your 2d list you need two sets of square brackets so if you would like a copy of this code i will post this in the comments down below but yeah that's how 2d lists work in python hey what's going on people it's you bro hope you're doing well and in this video i'm going to explain tuples in python so sit back relax and enjoy the show so tuples they are collections which are ordered and unchangeable they're very similar to lists but they're ordered and we can't change them they're useful for grouping together related data let's say we would like to create some sort of student record so we can create a tuple to take care of that for us so let's say we would like to create a tuple called student the process of creating a tuple is very similar to lists but instead of using a set of square brackets to place all of the values within we're going to use a set of parentheses and now we can add a bunch of values related to this collection of student so let's add some student information let's say that this student's name is bro let's give him an age as well as a gender all right so there you have it we now have a tuple called student and let's take a look at some of the functions related to tuples and you can access them by typing student dot and then there are a few here not as many as lists we have count and we have index so we can find the count of how many times a value appears let's count how many times the value of bro appears so we'll need to put this within a print statement so we can actually see it so bro appears one time within this tuple there is also an index method as well so type the name of your tuple dot and we will use the index method we can find the index of a certain value let's say we would like to find the index of mail and then i will just print this to the console window so the index of the value mail would be at two zero one two that's it for the methods available to tuples a few tricks that you can do with tuples is that you can display all of the contents within a tuple using a for loop let's say 4x in student we will print x so this will iterate once through all the values found within our tuple of student and we can also check to see if a certain value exists within our tuple using an if statement let's say if bro in student if this is true then what do we want to do let's say print bro is here all right so since bro is within here this will be true and this will print our statement of bro is here all right everybody like i said this is a super quick video on tuples they're very similar to lists except they are ordered and unchangeable if you'd like a copy of all this code i will post all of this in the comments down below and don't forget to smash that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain what a set is in python so sit back relax and enjoy the show a set is a collection which is unordered as well as being unindexed they do not allow any duplicate values for example let's create a set of silverware so in order to create a set we need a name for this set let's call it utensils equals and in order to create a set we need to surround all values with a set of curly braces now let's add a few utensils to the set called utensils let's add a fork a spoon and maybe a knife and that should be good and let's display all of the values for x in utensils print x now with sets they're different from lists because they're unordered as well as being unindexed if i were to print all of the elements in utensils they might not necessarily be in the same order in which we placed them for example when we printed all of the elements found within utensils first we had a knife a fork and then a spoon if i were to run this again they might be in a different order kind of like that so a set is actually faster than a list if you need to check to see if something is within a set compared to a list and they do not allow any duplicate values let me add a bunch of knives and let's see what happens so i'll have a total of three knives but when we print all of the elements of the set only one knife appears so here's a few useful methods of sets the first method is that we can add an item to our set so type in the name of the set in this case it's utensils dot and here's a bunch of methods that you can use i am looking for add and we can add an element to the set i would like to add a napkin and then if we were to print the set we do have a napkin within the set we can also remove an element utensils dot remove and i would like to remove the fork and now our fork is gone we can also clear utensils dot clear and all the elements within our set should be gone so let me turn these lines into a comment all right for this next example we'll need a second set let's create a second set called dishes and then we need a set of curly braces and let's add a bowl a plate and a cup our next method is that we're going to add one set to another by using the update method let's say we would like to add our dishes set to our utensil set so let's type utensils dot and use the update method and within this method we will pass in the set that we would like to add so utensils update dishes this will add all of the elements found within dishes to our utensil set and you can see that when we print our utensils we have a bowl a plate and a cup in here as well and then if i were to switch these around let's say dishes update utensils and then i will print everything found within dishes now there's a fork a spoon and a knife in here as well we can also join two sets together and create a new set entirely so let's create a set called dinner table like we're setting up a dinner table and we need a fork a spoon a knife a bowl a plate and a cup so we have a dinner table set we're going to set the sequel to either utensils dot union dishes or we could do dishes union utensils either way would work and let's display all the elements found within dinner table and we should now have elements from both sets utensils and dishes as well there are also some methods in which we can compare the similarities as well as the differences between the elements found within two sets let's say i would like to check to see what utensils has that dishes doesn't and for this example i think i'll add a knife to my dishes set just so that they have at least one thing in common so i would like to see what utensils has that dishes doesn't so we can do so using the difference method and i will print the results with a print statement so i'm going to compare utensils against dishes utensils dishes and this will print what utensils has that dishes doesn't which is a fork as well as a spoon and we can reverse the rolls too we could say dishes difference utensils what do dishes have that utensils doesn't and dishes has a cup a bowl and a plate they both have knives so that's why knife isn't appearing we can also check to see if there's anything that they have in common using the intersection method so i'll turn this line into a comment we'll print utensils dot intersection dishes and this will return whatever element that they have in common which is a knife all right everybody in conclusion a set is a collection which is unordered as well as being unindexed they do not allow any duplicate values and you can do things like compare two sets see if there's anything that they have in common any differences and we can add or remove elements to a set if you'd like a copy of all this code i will post all of this in the comments down below don't be afraid to smash that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain how dictionaries work in python so sit back relax and enjoy the show all right let's get down to business a dictionary is a changeable unordered collection of unique key value pairs they're fast because they use hashing and they allow us to access a value quickly now to create a dictionary it's very similar to creating a set based on the last video except we're going to store unique key value pairs let's create a dictionary of countries and their capitals we can store those as key value pairs so let's call this dictionary capitals capitals equals then we need a set of curly braces much like what we use with sets now we need a key and a value let's say we have the usa as a key and the capital of the usa would be washington dc so in order to associate a value with the key we'll follow the key with a colon and then add some value and the data type really doesn't matter but in this case we're just using strings so the capital of the usa would be washington dc and to add another key value pair we'll separate each with a comma and let's add a few others for good measure so let's say we have india next as a key and the value would be new delhi and we'll add two more let's say we have china and the capital of china is beijing and lastly let's add russia and the capital of russia is moscow and there you have it ladies and gentlemen we now have a dictionary called capitals that has unique key value pairs so remember with dictionaries they are unordered in order to access one of these values instead of using a numbered index we're going to use the associated key with that value here's an example let's say i would like to print the capital of russia so i need to use this key of russia so in order to do this type in the name of the dictionary followed by a set of straight brackets and then instead of an index number like 0 or 1 2 3 i'm going to use the key so i would like to print the value that's stored or associated with the key of russia so when i run this this will print that value which is moscow so this isn't always safe let's say we have a key that doesn't exist like germany germany is not currently within my dictionary so if i were to run this well then my program is going to encounter an error and this will interrupt the normal flow of my program a much safer way to access a key to check to see if it's there or not is to use the get method of dictionaries so i'm going to turn this line into a comment and let's try this again but this time we'll use the get method so type in the name of the dictionary dot get and list the key that you want to use so i would like to see if germany is within my dictionary currently there isn't so this will return none and we will not encounter an error so this is a much safer way of checking to see if there is a key within your dictionary here's a few other useful methods there is a method to print only the keys so we type in the name of the dictionary capitals and here's a listing of all of the methods that we have access to i'm looking for the keys method and this will print only the keys and not the values we can also print just the values and not the keys so type in the name of the dictionary again capitals dot values and this will print only the values or you could print everything both the keys and the values and you do so by using the items method capitals dot items and this will print your entire dictionary one other way in which we can display all of the key value pairs in a dictionary is to use a for loop so at the end let's create a for loop for key comma value in capitals dot items this is going to iterate once for each key value pair in my dictionary for each key value in capitals dot items print key comma value and this will print my entire dictionary a feature of dictionaries is that they are mutable that means we can change them or alter them after the program is already running so one way in which we can do that is to use the update method of dictionaries so let's add germany as a key and give it a value of berlin so type in the name of the dictionary capitals and we'll use the update method and within the parentheses of this method we'll add a set of curly braces and now we can add a new key value pair so let's add germany and a value of berlin so if i were to run this and display all of the key value pairs found within my dictionary we now have germany as a key and berlin as its value not only can you use the update method to add a new key value pair but you can update an existing one let's say we would like to change the capital of usa so capitals dot update parentheses curly braces list the key usa colon and then we can give the usa a new value let's pretend that the united states government has decided to relocate their capital to las vegas so this will now update our key of usa with a new value and if i were to print all of the key value pairs found within my dictionary of capitals the usa has a new value of las vegas so the last two methods i'm going to cover are both pop and clear you can use the pop method to remove a key value pair so capitals dot pop parentheses and list the key of the key value pair that you would like to remove so let's say we would like to remove china so we'll list that key and then when we use the pop method that will remove this key value pair from my dictionary and then of course we have clear as well which will just remove everything capitals dot clear and this will clear my dictionary all right everybody so in conclusion a dictionary is a changeable unordered collection of unique key value pairs they're fast because they use hashing and they allow us to access a value quickly well that's the basics of dictionaries in python if you would like a copy of all this code i will post all of this in the comments down below but yeah that's how dictionaries work in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to teach you guys all about the index operator in python so sit back relax and enjoy the show all right people let's begin i'm going to be explaining the index operator which is represented by a set of square brackets now they give access to a sequences elements they include but are not limited to strings lists and tuples for this example we're going to be working with strings because strings are easy to work with let's say we have a name and name equals whatever your first and last name is we can use the index operator to access an element of the sequence our string so let's check to see if the first letter in our name is lowercase and i should probably change that to lowercase for this example so within an if statement if name and we can add a set of square brackets after our sequence which is a string and we can check a given element of our sequence let's check to see if the first letter is lowercase now with computers they always start at zero if you need to access the first element in a sequence that would be index zero and then the next sequence well the next element in the sequence would be one then two then you followed that pattern so i would like to check to see if name at index zero that would be the first character is lowercase so there is a method to check that dot is lower this will return true or false if the first letter is lowercase then our if statement is going to be resolved to true and what i could do is that i can perhaps change it to uppercase then so let's reassign name to equal name dot and there is a capitalize function here and then let's print our name print name so when we run this the first letter in my name is now capitalized so if you need to access an element within a sequence a string or list or a tuple you would add a set of square brackets afterwards and then you list an integer of the element that you're trying to access so here's a few other examples i'm going to turn this as well as this into a comment and let's say we would like to create some substrings and we can do so using our index operator so i would like to create a substring from the first part of my name so what i'll do is create a new variable first name equals name index operator so you can specify a range for an index operator so you would set the starting position on the left hand side followed by a colon and then your ending position so i would like the substring to begin at index 0 and end at 3 so that would be 0 colon then three all right and then i would like to make this all uppercase for some reason and then let's print my first name so with the index operator we specified a range we would like to access elements 0 through 3. turn them up your case and assign them to a new variable of first name here's a shortcut that you might find useful if the index for your range begins with zero you can actually delete that you don't even necessarily need that zero now we just have a colon three and this would work the same as it did before so that's a useful shortcut and we're going to bring it up later if we need to access the last element in a sequence this time let's create a substring of last name so last name equals name index operator this time i would like to access the element at index let's see 0 1 2 3 4. all right so i'm going to say for colon and we're not really sure where our name our last name is going to end so what you could do is just say colon and then leave the next index blank so that will be the index beginning at four and everything afterwards and let's say two lower to make this all lowercase for some reason so let's print our last name print last name so this should take everything starting at index 4 and after that and turn it into its own substring of last name now you can access the last element in a sequence by using what's called negative indexing so let's add a exclamation point to the end of our name so let's say we have a new variable called last character and i would like to store the last character in my name to this new variable this new substring so to access the last element in a sequence within the index operator we can use negative indexing so the last element would be negative one all right and then let's print whatever our last character is so this should print an exclamation point yep which did so then if this was negative 2 that would be the second to last element in a sequence so now that would be e because e is in the second to last element in my sequence all right everybody so that's the basics of the index operator you can add a set of square brackets after a string a list or a tuple and then list an integer or a range of the elements that you're trying to access so if you would like a copy of all this code i will post everything in the comments down below don't be afraid to help me out and smash that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain how functions work in python so sit back relax and enjoy the show if you find this video helpful please remember to like comment and subscribe your support will help keep this channel running okay let's do this thing a function is a block of code which is executed only when it is called this process is also known as invoking a function with programming we try not to repeat code if we don't have to that's why functions are useful because our function can perform some specific task for us some block of code for us whenever it is called so we only need to write that block of code once and if we need to repeat it we just call this function one more time so let's define and create a function we'll create a function called hello and in order to define a function we'll type def and then a unique function name so let's call this function hello and with functions they always end with a set of parentheses and lastly to finish defining this function we'll add a colon at the end so if you go down to the next line take notice that my cursor is now indented any code underneath a function that is indented belongs to that specific function and will only execute whenever that function is called so for now we need to type in something if you don't know what you want your function to do you can always type pass for now but let's print something print the word hello and in order to call this function all we need to do within our program is type the name of the function which is hello and then add a set of parentheses because functions always end with a set of parentheses so what this will do is execute my function once and perform this block of code whenever it is called if i were to remove this well our program currently isn't going to do anything because functions only execute their block of code only when it is called so this time let's print the word hello three times so i will call this function three separate times hello hello hello so when i run this our hello function will be called three separate times now with functions they are not limited to just one line this is an entire block of code so maybe we can do something else too let's print have a nice day now if i were to run this my hello function is going to execute this entire block of code three separate times hello have a nice day now an important feature of functions is that we can send our function some information and our function can do something with that information that it receives let's say this time i would like to print hello plus somebody's name currently name is an unresolved reference what we can do when we call this function is send our function some information this can be a value a variable a collection all sorts of different things so if you need to send your function some information within the parentheses when you call that function just list the data that you want to send your function so let's say i would like to send my function a string value of bro whatever your first name is when you send information to a function these are called arguments they are the information that you're sending to a function and when you define that function you need a matching set of what is known as parameters so our hello function is going to receive one argument a string value we need a matching number of parameters currently this isn't going to work you can see here that hello takes zero positional arguments but one was given our function needs a matching number of parameters so think of it this way when we receive this value we're going to give a nickname to this value so when we receive the string value what do we want to call it well let's call it name so in order to add parameters to your function just list the parameters within the parentheses of that function and well this should work now we have a matching set of arguments and parameters when we call the hello function this time we are sending one argument over and when our hello function receives this argument we're going to give it a temporary nickname of name or you can call this whatever you want to and then we can use this value for whatever we want within our function now if we were to run this this will print hello bro have a nice day now i can send maybe a different value let's say hello and then i will send a string value of dude hello dude have a nice day so this isn't limited to just values we can send variables to let's say we have a variable called name equals bro and this time i'm going to send this variable over hello and then send name so these don't need to be the exact same let's say this is my name and i'm going to send my name over and i will temporarily give this value a nickname of just name and then i can use this variable for something hello bro have a nice day now with arguments you can send more than one value over let's say this time i would like to send two values over so let's send pro maybe for a first name and code for a second name but you can use your first name and last name so this isn't going to work because we do not have a matching set of arguments and parameters we're sending two arguments over but our function is only designed to accept one argument because we have one parameter so let's rename name as first name and we need two parameters this time so what are we going to call this value when we receive it let's call this last name so this time we are going to receive two values they will be nicknamed first name and last name so this time let's print hello first name maybe i'll add a space plus last name and this is now valid hello bro code have a nice day with arguments you can mix and match the data types that you're sending as arguments so currently we're sending two string values as arguments this time let's send an integer value let's say we would like to send an edge over to our hello function so i'll just send maybe the value of 21. so currently this isn't going to work because the hello function takes two positional arguments but three were given when we call this hello function we're sending this argument over but our function doesn't know what to do with this argument so we need a matching parameter for this value that it receives so let's call this value maybe edge as a temporary nickname and then we can do something with this value when we receive it so let's print an additional message perhaps u r plus age plus years old so if you need to display an integer or number along with the string you do need to convert it to a string so let's just cast our edge as a string when we display this so this should work now we now have a matching number of arguments and parameters so this will display hello bro code you are 21 years old have a nice day so ladies and gentlemen in conclusion a function is a block of code which is executed only when it is called if i were to remove this function call well then our program is just going to completely ignore this function and this block of code would not be executed when we call this function we can pass information known as arguments but we need a matching number of parameters set up to receive these arguments there are a few advanced features of parameters but i'll hopefully get to that in future videos we'll just stick with the basics for now of functions so that's the basics of functions if you would like a copy of this code i will post this in the comments down below but yeah that is how functions work in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain the return statement in python so sit back relax and enjoy the show all right people let's begin the return statement is used within functions to send python values or objects back to the caller these values or objects are known as the function's return value so do you know how with functions we can pass arguments to a function and then our function can do something with those arguments well not only that but our function can pass some value or object back to the caller so what we'll do for this example is create a function that will simply multiply two numbers together and return the result back to the caller so let's define a function called multiply and we'll set up two parameters for this function let's say number one and number two and what we'll do is say result equals number one times number two and then at the end we can return something what do we want to return let's return whatever the result is now when we call this function we will pass in two values as arguments let's say we would like to multiply six times eight so when we run this well we can't actually see anything when we return the result after multiplying numbers one and two it's going to return the result back to the caller in order to see the value that is returned back to the caller one way in which we can do this is to print the value that is returned within a print statement so what we'll do is print the value that is returned after calling the multiply function so 6 times 8 is really great 6 times 8 is 48 now one other thing that we can do is store the returned value within a variable so let's say x equals multiply 6 times 8 and then we will print whatever x is so the result is still the same of 48 now with the return value there is another way in which we could write this that uses less lines of code so we'll delete this first line and instead of returning a variable called result what we'll do is just return number one times number two and this would work the same as it does before but it's written in less lines of code so that's another way in which you could write this all right everybody so that is the return statement functions can send python values or objects back to the caller these values or objects are known as the functions return value you can either print this value directly to the console window or you can store it within a variable or some other location and well ladies and gentlemen that is how the return statement works in python what's going on everybody it's bro hope you're doing well and in this video i'm going to explain keyword arguments in python so sit back relax and enjoy the show all right everybody let's discuss keyword arguments these are arguments that are preceded by an identifier when we pass them to a function the order of the arguments doesn't matter unlike positional arguments which do matter and we've been working with positional arguments already and python knows the names of the arguments that our function receives when we use keyword arguments here's an example of us using positional arguments and then i'll demonstrate the benefits of keyword arguments let's say we have a function called hello that accepts three arguments a first name a middle name and a last name and the output will be hello first name middle name last name so if i were to run this this will display hello bro dude code so we're using positional arguments the order of the arguments does matter what do you think's gonna happen if i were to replace some of these values let's say i will swap the first argument with the third argument so let's try it again hello code dude bro so obviously the order of the arguments matters and now if we were to use keyword arguments then the order of the arguments doesn't matter but with each argument we need to precede each argument with a unique identifier and that identifier is the name of the parameter we want to associate each argument with so for my intended last name i will use an identifier of last to match this parameter so dude will be middle middle equals dude and bro will be first even though they're not in the correct order so let's try this again and my output is hello bro dude code so that's all about keyword arguments they are arguments preceded with an identifier when we pass them to a function the order of the arguments doesn't matter unlike positional arguments which do matter and then python knows the names of the arguments that our function receives when we use keyword arguments so that's it for keyword arguments if you would like a copy of this code i will post this in the comment section down below but yeah that's how keyword arguments work in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain nested function calls in python so sit back relax and enjoy the show all right people nested function calls these are function calls inside of other function calls and this is possible because certain functions will return a value and we can immediately use that value as an argument for the next function so here's an example let's say that we have the small program where we will ask a user to type in a whole positive number and let's say i don't let's say i type in negative 3.14 and then i'm storing that value within a variable named num what i'm going to do is convert that number to a floating point number because currently it's a string when you accept user input i will find the absolute value of num and then round it to the nearest whole number and then print the value so we can actually do this using less lines of code with nested function calls so let's start with the first function which will be accepting some user input the input function so this will be in the very center of our nested function calls and then the next function we would like to apply to the variable that is returned the value that is returned we will pass in as an argument to our next function of casting this data type to a float so we'll surround our function with another function and use the float function and then we'll just keep on adding layers to this so we have the absolute value function next so we'll add another layer and we have the round function so we'll add a layer to that and lastly we're going to print and that'll be the outermost layer so this program will do the exact same thing let's say negative 3.14 except we've written this with one line of code so basically we start with the innermost function and resolve that first whatever value is returned we use as an argument to the next outermost function and in this case it would be float then we resolve that then move on to absolute value then round and then print so it's just another way of writing code that takes up less lines but this is more of an extreme example you probably won't see like four or five nested functions well everybody those are nested function calls if you would like a copy of this code i will post all of this to the comment section down below but yeah those are nested function calls in python hey what's going on people it's your bro hope you're doing well and in this video i'm going to show you how variable scope works in python so sit back relax and enjoy the show all right let's do a thing people let's discuss the scope of a variable now the scope of a variable is the region that a variable is recognized a variable is only available from inside the region that it is created let's say that we have a function and i just gave this function a name of display name i created a variable inside of this function named name and you can assign this a value of whatever your name is preferably a last name for this example and what i'll do is just print whatever my name is so this variable is known to have a local scope because it's declared inside of a function and a variable is only recognized inside of the region that it is created this variable of name since it's created inside of this function it is known as a local variable that has a local scope it's only available inside of this function that it's created now let's attempt to access this variable from outside of our function so i'm going to print my name variable but we'll have an issue though so name name is not defined so local variables are declared inside of a function and they have a local scope they are only available inside of this function in which they're created on the other hand a global variable is a variable that is declared outside of any function but within your module that you're working with a global variable is known to have a global scope they are available inside and outside of any functions now if i was to print my name variable this is going to print bro or whatever your first name is and it is entirely possible to have both a global and local version of the same named variable so we have both a global version of name as well as a local version of name if i was to print my name variable from outside of this function it's going to print my global version however if i print my version of name inside of that function in which it's created we're going to first use the local version before the global version of name and let's try that so i'm going to call my display name function and this will print my last name code and then my first name of bro so it is possible to have a global and local version of the same named variable now if i was to remove this line where we declare a local version of name well then the next best available name to us would be the global version of name so if you use a variable inside of a function you'll first use a local version of that variable if it's available if not you'll use a global version instead and python will follow this rule known as the legb rule you use any local variables first then enclosed variables then global and then any built-in variables in that order so that's the main difference between local scope and global scope the scope of a variable is the region in which it's available and it's limited to the region in which it's created a local scope is available only inside of the function in which that variable is created a global scoped variable is a variable that is available inside and outside of any functions but within your module that you're working with so that's variable scope in python if you would like a copy of this code i will post this code to the comment section down below and well yeah that's how variable scope works in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain the arcs parameter in python so sit back relax and enjoy the show all right guys and gals let's talk about args now args is a parameter that will pack all arguments into a tuple it's useful so that a function can accept a varying amount of arguments here's an example of why it would be useful let's say we have a function called add that will accept two numbers as arguments and add them together and return the sum so this works as intended right as long as we pass in only two numbers but what if we need to pass in three numbers as arguments well we can no longer use this add function because we have two parameters set up but we're passing in three arguments you can see here within my console window that we have a type error add takes two positional arguments but three were given and one way in which we can solve this issue is to use this args parameter so what we're going to do is replace all of our parameters with asterisk args and actually the args portion isn't as important as the asterisk args is short for arguments and you can really name this whatever you want just be sure that you have this asterisk because with this asterisk we're doing a form of packing what we're doing is passing all of these arguments and packing them into a tuple so let's rewrite this program so let's say maybe sum equals zero and then we will need to iterate through all of the items within our tuple because tuples are iterable so let's say for i in args what we'll do is say sum plus equals whatever i is and at the end when we escape the for loop we will return our sum so let's try it again and see if it works well would you look at that it works let's pass in a few other arguments for good measure let's pass in six arguments this time all right look at that this does in fact work so you can actually name this whatever you want the important thing is to have this asterisk so let's rename this as i don't know stuff and let's try this again yep it still works with tuples they are ordered and unchangeable let's attempt to edit one of these values so let's say stuff at index zero is equal to zero and let's try and change it so you can see that tuple object does not support item assignment if you need to change one of the values within your tuple after you pack all of these arguments you might need to convert this to a different collection one way in which we can do that is to cast it let's say stuff equals and we'll cast our tuple as a list because a list can be changeable it's mutable so let's attempt this again we'll cast our tuple as a list and then edit one of the values and then add all the values together so to change one of the values say the name your collection stuff in this case let's say at index zero this now equals zero so now if we were to add all these items together they should equal 20. there we go so yeah that's basically the args parameter the name isn't as important as the asterisk because you can really name it whatever you want a common convention is to just name this args it's a parameter that will pack all arguments into a tuple it's useful so that a function can accept a varying amount of arguments well that is all about args if you would like a copy of this code i will post this in the comments section down below but yeah that is how the args parameter works in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to be explaining quarks in python so sit back relax and enjoy the show all right everybody let's talk about quarkx now this is a parameter that will pack all arguments into a dictionary it's useful so that a function can accept a varying amount of keyword arguments it's identical to args except with args args will accept a varying amount of positional arguments and pack them into a tuple with quarks this will accept a varying amount of keyword arguments and pack them into a dictionary so here's an example of why this would be useful let's say we have a function called hello that accepts two keyword arguments a first name and a last name all this will do is output hello your first name and last name but what if somebody has more than two names let's say somebody has a middle name and for this example i'll just say my middle name is dude so if i were to run this well this hello function is no longer going to work as you can see in the console window we have a type error the hello function got an unexpected keyword argument middle one way in which we can solve this we can use this quark's parameter so we can accept a varying amount of keyword arguments so what we'll do is replace our parameters with two asterisks then quarks now if i would like the same output as i had before i'm going to need to change a few things around in order to access a value within a dictionary you type the name of the dictionary square brackets and then within quotes list your key so i would like to access the value at this key of first and let's repeat the process for last name so the key is going to be last we'll access this value at this key and this should work the same as it did before now let's take this a step further let's say we would like to display somebody's full name based on the amount of keyword arguments that they pass into this function well there's a few different ways in which we could do this one easy way is that we could write our program like this let's print the word hello and we will need to iterate once through each key value pair within this dictionary and we can use a for loop to do that so to iterate once through each key value pair in your dictionary we'll type for key value in the name of our dictionary quarks in this case dot items and then we will print each value so there's one more thing that we need to do this kind of works as intended but it's going to print each value including our word hello on a new line so with a standard print statement this will print a new line character after each print statement as if we're hitting enter we can actually change that so after your string add and equals and we can replace that new line character with something else maybe a space and let's do the same thing for our for loop so value comma end and then just add space now this will print all of your names on the same line hello bro dude code and now we can pass in a varying amount of keyword arguments based on how long our name is perhaps we have like a title title equals mr and we can print that as well hello mr bro dude code here's a fun fact of the day you don't necessarily need to name this parameter as quarks the important thing is to have these double asterisks that precede it quarks is just a common naming convention it's short for keyword arguments you could name this as something else perhaps something more descriptive like names since we're passing in a bunch of names so the name of our dictionary is now names and this would work the same as it did before the important thing is to have these double asterisks that precede the name of your dictionary but quarks is the common naming convention well everybody that's all about quarkx it's a parameter that will pack a varying amount of keyword arguments into a dictionary if you would like a copy of all this code i will post this in the comments section down below but yeah that is how quarkx works in python hey what's going on everybody it's your bro hope you're doing well and in this video i'm going to teach you guys all about the format method in python so sit back relax and enjoy the show okay ladies and gentlemen let's begin the format method is a method available to strings it's optional and it gives users more control when displaying output to best demonstrate this i'm going to use a line from a popular nursery rhyme titled hey diddle diddle because well you know i'm a mature adult like that i'll be printing this line to my console window the cow jumped over the moon let's do so using a standard print statement and then i'll show you the benefits of using the format method later for this example i have two variables a variable called animal and i'm going to store a string of cow and item and i'll be storing an item name which is moon when we compile and run this as you would expect the output is the cow jumped over the moon there's a more elegant way of writing this line of code and that is by using the format method available to strings i'm going to turn this line into a comment and we're instead going to produce the same output but use the format method instead so we need a standard print statement like usual and then a string that we would like to format so we're going to write the same thing but in place of the variables we're going to add a placeholder the instead of the variable name or value name i'm going to add a set of curly braces so that functions as a placeholder for a value or a variable the this should be cow jumped over the and i'm going to insert another placeholder now this is a string we can format the string by following this string with dot format parenthesis and within the parentheses of the format method we can insert some values or variables let's begin with some values i would like to insert cow as well as moon so this will produce the same output but it's written a little more elegantly we can also replace these with variables because they store these values so i'm going to replace cow with animal and moon with item and this will create the same output as it did before these curly braces are what's known as format fields they function as a placeholder for a value or a variable and they work in order the first format field will insert the first value at this location if you have another set or more sets of this format field you'll insert the next value that's listed within the format method so if we were to switch these around we'll switch the position of animal with item well then the first format field is going to insert our item and the second format field will insert our animal this time the moon jumped over the cow an additional way of inserting values at a given place holder would be to use what's referred to as a positional argument within these format fields we will list the index of the value that we would like to insert at this location if you need to insert the first value well that has an index of zero because computers always start with zero and following that pattern the next index would be one if you had let's say three values that you need to insert if you had another placeholder that would be two then so you would just follow that pattern so there's going to be no visible change but what we could do is reverse the positional arguments of these placeholders so what do you think would happen if i switched one with zero at these locations well this format field is going to insert the value found at index one this first value is index zero and the second one is index one so now the roles are reversed this time the moon jumped over the cow our last way of inserting some values at a given format field would be to use what's referred to as a keyword argument within the format method we're going to list some keyword argument pairs we need a keyword name followed by a value so let's say animal is going to be the keyword we're going to say equals some value animal equals cow and item equals moon and you may have noticed that the color of your text might have changed so we no longer need these variables actually um but i'm going to comment out these two print statements because we will get an error then so these are in keyword argument pairs and within our format field instead of keeping these empty or using an index we can use the keyword name at my first format field i'm going to insert my keyword of animal and at my second format field i would like to insert the item keyword so the result is going to be the cow jumped over the moon so let's reverse these now we'll place our item keyword here and then at the second format field we will insert our animal and this time the moon jumped over the cow here's an important concept that i'd like to bring to your attention with these values found within the format method you can actually reuse some of these more than once so let's say we would like to state the animal jumped over the animal we're going to use this animal keyword twice and our output is going to be the cow jumped over the cow if we're doing the same thing with positional arguments we can reuse the same index this time let's say that the moon jumped over the moon so our item has an index of one so within our first format field we'll state the index will be one and our second format field will also be one so our output's going to be the moon jumped over the moon all right let's take things up a level there's an even more elegant way in which we could write all of this what we'll do is store our string that we would like to format within a variable let's turn this line into a comment and let's create a variable called text text equals the string that we would like to format which is the format field jumped over the format field and if we need to format this variable we can just call the format method on it so within a print statement let's say text dot and then use the format method and pass in the values that we would like to insert at these placeholders so we're going to insert animal as well as item so our result as you would imagine is the cow jumped over the moon this next section i'm going to explain how we can add some padding to a string when we display it using the format method let's say we have a name variable and assign this a value of whatever your name is so i would like to display my name along with the custom message let's say hello my name is and then i'll use a format field here so let's follow this string by using the format method and i would like to insert my name at this location so currently this will display hello my name is bro or whatever else your name is so we can add some padding either before our name after or we can add some padding to the left and the right hand side of our value that we have so what we'll do to begin is let's add some padding to the right hand side of our name that we have so within our format field if we need to add some padding within the format field add a colon and then the amount of space you would like to allocate to displaying your value so let's say 10 so i'm going to allocate 10 spaces worth of room to display my name you can't really see it right now but let's take a look so i can't move my cursor past this line at the end of my name but with my second line i have all of this room to work with so if i were to change my string that i have let's say nice to meet you well then all of this padding that i have is going to be more evident so we can add a number preceding with a colon to add some padding to a value and then you can left align this right align it or center align it so what i'll do is copy this line that i have if you need to left align it you use the less than sign but there's going to be no visible change because that's already the default if you need to write a line precede your number with a greater than sign so your value is going to be right aligned if you need to center this value then use the carrot so this will center align your value within the padding that you have allotted one question that you might have for me and i'll try and answer that now because it's relevant what if we need to add a positional argument or a keyword argument to our format field if there's already some text within here so what you would do before the colon you would just precede the colon with either your positional argument or your keyword argument followed by colon and then whatever you want to add afterwards to format your value that you have alright ladies and gentlemen we are near the end and i promise that this is the last section how can we format some numbers let's say we have a number variable and this will equal the first few digits of pi 3.14159 let's pretend that we would like to display only the first two digits after the decimal so we can do so using the format method let's print the number pi is and then i'll use a format field here and we will call the format method and insert our number that we have so if i need to display only the first two digits after the decimal within the format field i will add colon dot to f f is for floating point numbers that's anything with a decimal portion so the result is that this will display only the first two digits after my decimal because we placed two within the format field so if this was three point three f this would display three digits after the decimal portion oh and apparently this will round your number so that's something that you should keep in mind so this time let's change our number to something larger like 1000 and i will copy this line and make a few changes let's say the number is and i would like to add a comma at the thousands place so after the colon within the format field i will add a comma so this will automatically add a comma to all 1000s places another cool thing that you can do is that you can display your number as binary so within the format field add colon b this will display a binary representation of your number you can do the same thing with octal by adding colon o so our number is now being displayed as an octal number and you can do the same thing with hexadecimal lowercase x for lowercase or uppercase x for all uppercase so my number 1000 is now in hexadecimal and lastly we can display this number in scientific notation using either lowercase e for lowercase or capital e for uppercase and mynumber 1000 is now in scientific notation all right everybody so that's a few things that you can do with the format method it's an optional method that gives users more control when displaying output if you would like a copy of all the code that we've written here today i will post everything in the comments down below don't be afraid to smash that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain a few useful methods of the random module so sit back relax and enjoy the show okay people in this video i'm going to explain how we can generate some random numbers as well as a few other useful methods of the random module now we're not going to be creating true random numbers but something called pseudorandom numbers which are fairly darn close so the first step is to import the random module at the top import random we now have access to everything that the random module has to offer let's begin by generating a random number between one and six like we're rolling a dice so what i'm going to do is say x equals random dot rand and we can generate a random integer between a certain range if i want one through six i will state one comma six and then we can generate a random number between one and six like we're rolling a dice so if i were to print the value of x then we will get a random number between one and six for example i just got a one a two a three and a six all right we can also generate a random floating point number two let's say y equals random dot random so this will give us a random number between 0 and 1. this time i'm going to print y so we have 0.49 and some change 0.145 and 0.858 we can also generate a random choice from a list or other collection let's say we're playing a game of rock paper scissors so let's create a list i'll just call this my list equals square brackets and we will have three choices rock paper and scissors so let's say z will be the random string that we generate z equals random dot choice and we will pass in my list and let's print z so this will generate a random choice from my list called my list so we got scissors paper and rock we can also use the shuffle method of the random module to shuffle a list or other collection let's say we're working with a deck of cards cards equals let's say one through nine and we have a jack a queen a king and an ace this won't be a full deck of cards it'll just be one suit so we can actually shuffle this list by using the shuffle method random dot shuffle what do we want to shuffle we want to shuffle our cards and i will display my cards with a print statement so the shuffle method will shuffle a list or other collection for you well everybody that's a few useful methods of the random module if you would like a copy of all this code i will post this in the comments down below don't be afraid to smash that like button drop a comment down below and subscribe if you'd like to become a fellow bro hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain exception handling in python so sit back relax and enjoy the show well everyone let's talk about exceptions an exception is an event detected during execution that interrupts the normal flow of a program here's a program that i've written and we're intentionally going to cause an exception so this program that i've written we will accept a numerator and a denominator from the user we'll divide the numerator by the denominator we'll get a result and print the result so what if i were to divide a number such as 5 divided by 0 which we cannot mathematically do well this will cause an exception an event detected during execution that interrupts the flow of a program so our program was interrupted and within our console window we have this traceback message which states what went wrong and a name for this exception that occurred this specific exception that occurred is a zero division error so this video is all about handling these exceptions so they do not interrupt the normal flow of a program now a very basic form of exception handling is to surround any code that is considered dangerous as in it might cause an exception within a try block anytime you accept user input would be a good indicator too so this code is considered dangerous because we don't know what the user is going to type in so we will try all of this code if an exception occurs we can catch it and handle it so to do that we'll add an accept block accept and then we will catch exception normally having this block by itself isn't considered good practice but i'll explain why later so this accept exception block will catch all sorts of different exceptions and it will prevent our program from being interrupted and we can do something else entirely such as print a message something went wrong so let's try this again we will divide five by zero which we cannot do we no longer have that traceback message within our console window we caught the exception and we did something else we printed something went wrong like i said before it's not considered good practice to have a single accept block that will handle all exceptions it's much better to first handle specific exceptions when they occur and we can do so by writing additional accept blocks so let's create an additional accept block that will catch any zero division error exceptions that occurs when somebody attempts to divide by zero so if this exception occurs how do we want to handle it let's just print the message let's print you can't divide by zero idiot and let's try this again so five divided by zero you can't divide by zero idiot here's another one i'm going to turn this accept block into a comment so we can take a look at something what if i divide by something that's not a number like we take 5 and divide it by the word pizza well pizza is not a number and we ran into a value error exception so we should probably handle this too so let's create another accept block that will handle that accept value error and how do we want to handle this let's print something enter only numbers please okay let's try this again and see if this exception is caught five divided by the word pizza enter only numbers please not only that but you can also add the accept exception block at the very end just in case there's something you won't anticipate but it's always considered good practice to first catch any specific exceptions and let the user know exactly what went wrong an additional way in which we can handle these exceptions is that we could display the exception that occurs although it is completely optional so to do that what we'll do is that after each of these accept block definitions let's add as e so we're calling the exception as e that's just standard practice although it's not necessary so let's do that for each of these except blocks and then we can print whatever e is so let's add that to each of these blocks so it should now look something like this so when we encounter an exception we can display what exception occurred too as well so let's divide five by pizza invalid literal for int with base 10 pizza enter only numbers please so like i said this is an additional way in which you could handle an exception although it's entirely optional another thing that you can do is that you can add an else statement to the end of your accept blocks so what's happening here is that we're going to try all of this code if an exception happens then catch it and handle it if not then do something else so why don't we print our result only if there are no exceptions that occur so if there are no exceptions we will execute this else statement if not then we won't so let's divide five by an actual number this time like two so there are no exceptions that occurred so we executed this else statement whatever code is within our else block and this printed the result of 2.5 but if an exception were to occur like we divide 5 by 0 then we will catch our exception and handle it and we do not execute whatever block of code is within our else statement there is one other clause that you should be aware of that is the final clause this is always at the end how this works is that whether or not we catch an exception we will always execute any code that is within the block of code for our final clause so this is a good opportunity if you open files to close them within the finally block but we haven't dealt with opening files yet so we won't do that all we'll do is just print something print this will always execute so whether or not we encounter an exception this finally block will always execute at the end so let's try this again so this time let's cause an exception let's divide five by zero you can't divide by zero this will always execute and this time let's take this seriously and divide five by another number such as three so this will give us a result and like i said the finally clause the code within the finally clause will always execute but we won't really be working with this until we get to the section on file handling well everybody those are exceptions in python they are events detected during execution that interrupt the flow of a program and we can handle these exceptions by using try and accept blocks so if you would like a copy of all this code i will post all of this in the comments down below but yeah that is how exceptions work in python hey what's going on everybody it's bro hope you're doing well and in this video we're going to be covering some basic file detection using python so sit back relax and enjoy the show welcome ladies and gentlemen to the beginning of a mini series involving doing stuff with files using python and in this video we're going to be doing some basic file detection and in order to do so i recommend importing the os module it's already included with the standard python library all you need to do is import it all we'll be doing is checking to see if a file exists someplace on our computer so we'll probably need a file to work with what i'm going to do is go to my desktop for convenience and just create a new text document i will call this test.txt now i probably need the file location so i'm going to copy that and then we can use this so let's create a variable called path that will include the path to the file that i would like to detect so that was test.txt now if you have backslashes in your file path you'll probably need double backslashes because that's the escape sequence for a backslash within a string so we now have this variable path that we can work with now i would like to check to see if this location exists on my computer so if os dot path dot exists and you can see that we can pass in our path as an argument so i will pass in my path and if this returns true if that location exists i will print that location exists so this will not tell me if this is a file or not we'll be covering that later else let's print that location doesn't exist all right so if this location exists this will return true if not this will execute our else statement that location exists so what if i were to delete this file and we run this program again that location doesn't exist now this won't tell you if the location you're dealing with is a file or not there is a separate function for that it is if os dot path dot is file what we'll do is pass in our path and print that is a file all right so let's create another file because i deleted the previous one test.txt it's in the same location let's run this again that location exists that is a file now what if this was a folder so i'm going to create a new folder i will call this folder i will delete my test document and let's change the location to folder that location exists but it is not a file you can check to see if a location is a directory so let's write an else if statement os dot path dot is directory and we will pass in our path and let's print that is a directory all right so we have our folder we're going to check to see if this location exists and if it's a file or a directory that location exists that is a directory well everyone that is the basics of file detection we'll be building upon this concept in future videos so if you would like a copy of this code i will post this in the comment section down below but yeah that is the basics of simple file detection using python hey what's going on everybody it's bro hope you're doing well and in this video we're going to be reading a file in python so sit back relax and enjoy the show welcome back guys and gals in this video i'm going to explain how we can read the contents of a file using python so we'll probably need some sort of file to work with i created a plain text file called test.txt it's a plain text file and all this says is omg you can read this have a nice day like comment and subscribe so what i would like to do is to read the contents of that file line by line and print it to the console window and here's how and honestly we only need two lines of code to do this so what we'll do is type with open then within the open function list the name of your file or the file path this file of mine is within my project folder so i only need to list the file name if this was someplace else you'll probably need the file path so let's say this was on my desktop well i'll probably need to list the file path of where that file is located and i'll need to use double backslashes because that's the escape sequence for a backslash but since this file is within my project folder i only need to list the file name so with open then the name your file or the file path as file then what we're going to do is print file dot read and that is it so let's test it and it works omg you can read this have a nice day like comment and subscribe so this will actually close files automatically after opening them so that's kind of convenient and let's just test that theory so i'm going to print file dot closed if my file is in fact closed this will print true if it's still open this will print false so normally when you read a file it's normally open and you need to close it manually but if you write your program this way with open this will close the file automatically for you so using with open will close any files automatically for you after they've been opened however this does not catch and handle any exceptions that might occur like if we cannot locate this file so let's say that i mistyped the extension for this file let's say that i type in test.tx that's kind of funny because tx is the abbreviation for texas it's a texas file so this will cause a file not found error and this will interrupt the flow of our program and we would probably like to prevent that so what we could do is write a try and an accept block so we will try all of this code if we cannot find this file we can handle this exception file not found error so we'll place all of this code within the try block then if an exception happens we will catch that exception except we would like to catch any file not found air exceptions and let's handle this by printing that file was not found so if i were to run this again we will catch and handle this exception and this will not interrupt the normal flow of our program well everybody that's how to open and read a file in python if you'd like a copy of all this code i will post this in the comment section down below but yeah that's how to open and read a file using python hey what's going on everybody it's bro hope you're doing well and in this video we're going to be writing files in python so sit back relax and enjoy the show so to begin it's kind of similar to the last video on reading files with open within the open function list the file name or the file path so what do you want to call this file i will call this file test dot txt now normally with the open function there is a mode and you can actually change that there's a second argument that you can pass in by default this is r for read but if you want to write a file this would be w so now we're going to write a file called test.txt so to finish with open as file what are we going to do file dot write and within the write function we can write some text so let's create a text variable and we will add a string so let's say text equals yo and if you need to go down to a new line be sure to use the new line character so after this new line character the text that comes after is going to be on the next line as if we're hitting enter so yo this is some text have a good one all right so after i run this program we should have a file a text file within our project folder that appears and it is right here and it says yo this is some text have a good one now this is in write mode if this text was something else it will actually overwrite your current file so if i were to change this to uh oh this text has been over written well then this will overwrite the text that we have uh oh this text has been overwritten so you can actually append a file by changing the mode to a for append so let me change this back we will rewrite this this will save over our current file now we can append some text so let's add maybe a new line uh have a nice day see ya so i would like to append some text to this file i'm going to change the mode to a for append and we can now append some text onto the end of this file well everybody that's how to write to a file and or append a file if you would like a copy of this code i will post this in the comment section down below but yeah that's how to write to and or append a file in python hey what's going on everybody it's bro hope you're doing well and in this video we're going to be copying files in python so sit back relax and enjoy the show welcome back to another video regarding doing stuff with files using python and in this video we're going to be copying some files and in order to do so i recommend importing the shuttle module there's other ways of doing this too but i tend to like using the shuttle module now with this module there are three basic functions to copy a file starting at the top they are copy file copy and copy to so copy file is what we'll be working with this will copy the contents of a file copy will do everything that copy file does plus copy the permissions mode and the destination can be a directory and lastly copy 2 this will do everything that copy does plus it copies the metadata of that file including the files creation and modification times so depending on the project or the program you're working with you may need to use copy or copy too but in this video we're going to be using copy file just to copy the contents of a file now after you import the shuttle module this is all you need to do to copy a file shuttle dot then use the appropriate function that you need to copy your file we're going to be using copy file copy file and within this function there are two arguments a source and a destination so within my project folder i have a plain text file called test test.txt all this says is yo this is some text see ya what i would like to do is copy this file because it's cool now since this file is within my project folder i only have to list the file name otherwise if this is someplace else i would list the file path here so this file is test.txt this is the source file and now i need a destination so the second argument will be separated with the comma i'm going to list a destination so you can actually rename this to i would like to name this as copy.txt so the destination is my project folder so when i create a copy of this file test.txt this copy will appear in my project folder and say the same thing so after running this we now have a file named copy.txt that says the same thing as my test file and remember what i said you can copy this file to a different location on your computer so you could list the file path so this file path would go to my desktop and then when i run this this will copy my original file my source and then copy it to wherever my destination is oh and i almost forgot so if you need to use copy or copy 2 the arguments are exactly the same so if you needed to use copy this would be a shuttle dot copy instead of copy file then copy 2 is shuttle dot copy 2. the arguments are exactly the same but each of these functions will copy different things depending on what you need for your own program or project all right everybody so that's the basics of copying files and python i will post this in the comment section down below but yeah that is how to copy files using python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain how we can move files using python so sit back relax and enjoy the show welcome back everybody to another video regarding that thing that we do called programming and in this video we're going to be moving files using python and in order to do so i recommend importing the os module this is included with the standard python library all you need to do is import it and now let's create two variables a variable called source that will hold the location of where our source file is located as well as a variable called destination to function as well the destination now for this video i'm going to move a file within my project folder to my desktop so to do so i'm going to create a new file i will name this test.txt but take the liberty to name this whatever you want so i'm going to list the location of where my test file is located since this is within my project folder i only need the file name if this was someplace else on your computer you would probably need the file path and now where would i like to move this file to i would like to move this file to my desktop so i just need the file path so i'm going to go to my desktop right click go to properties i'm going to copy this location and paste it within my destination and i will add slash desktop slash test.txt you can also rename this too if you want i will just keep it the same now if you have single backslashes you'll likely need to change these to double backslashes because that is the escape sequence to print a backslash within a string so we have a source location as well as a destination location now we can begin i would recommend writing our code within a try and accept block to handle any exceptions so i would like to handle any file not found error exceptions just in case our program cannot locate our source file so let's print a message if that is the case perhaps source plus was not found now within our try block let's check to see if there is already a file at this destination because i would not like to save over it if there's already a file there so let's do some basic file detection if os dot path dot exists and i will pass in my destination as an argument to the exists function so if there is already a file here i should probably let the user know print there is already a file there else we can replace our files honestly if you do not care about saving over any files you can omit this part so else os dot replace and we will pass in our source and our destination as arguments and let's print a message to the console window to let the user know that source plus was moved all right let's try this oh i accidentally deleted my file test.txt all right now this should disappear in three two one and it's gone test.txt was moved and it should now be on my desktop which it is now you can also use this to move a directory as well i'm going to create a new directory i will name this folder and i will change source to folder and the destination from test.txt to folder and now this should move my folder there is already a file there oh let's delete that okay folder was moved all right everybody so that is how to move a file and or directory using python if you would like a copy of this code i will post this in the comment section down below but yeah that is how to move a file and or directory using python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to teach you guys how we can delete files using python so sit back relax and enjoy the show all right everybody so in this video we're going to be deleting files using python and in order to do so i recommend importing the os module this is already included with the standard python library all you need to do is import it and now we need a file to work with so let's right click on our projects folder and go to new file i will name this test.txt and we now have a file that we can work with but you know what i would like to delete this file because it's lame so let's do that in order to delete this file let's type os dot remove and we're going to list the file path here since this file is within my project folder i only need to list the file path test.txt if this was someplace else on my computer i would probably need the file path like that but since this file is within my project folder i only need the file name another thing that you can do too at least what i like to do is that i like to pass in a variable called path i will make this a variable and assign it a string value of whatever the path to my file is so i will assign path the name to my file test.txt now when i run this this will delete my file test.txt and you can see that it's no longer there now what if we attempt to delete a file that doesn't exist well we'll encounter an exception so if you want this is optional we can do some exception handling so let's write the remove function within a try block and we will catch this exception file not found error and let's print something print that file was not found now if you attempt to delete a file that doesn't exist your program will not be interrupted and instead you'll print something that file was not found now this function does not remove empty folders this is how to do so and actually let's test that so let's create a new directory i'll call this empty underscore folder now i will attempt to delete this empty folder empty folder we encountered a permission error access is denied so let's create an accept block for that accept permission error print i don't know you do not have permission to delete that right to delete an empty folder there is a different function os dot rmdir short for remove directory we're going to list the file path and pass that in as an argument and let's create an else block as well because we can else if there are no exceptions let's print path plus was deleted all right so rmdir remove directory will delete an empty directory empty folder was deleted now this function will not delete a folder that contains files and let's try that so let's create a new directory i'll just call this folder and within this folder i will create a new file test.txt all right let's attempt to delete this folder i will probably need to change the file name let's change that to folder and we encountered an os error that directory is not empty so let's handle this exception we don't need to but i like to accept os air print you cannot delete that using that function okay to delete a folder that contains files we'll need the shuttle module import shuttle and the function that we're looking for is shuttle dot rm tree short for remove tree and we will pass in our path now be careful with this function it is considered dangerous because it will delete a directory and all files contained within so now we can delete a folder that contains files folder was deleted in conclusion these are three basic functions to delete a file or directory they are remove which deletes a file rmdir which is an abbreviation for remove directory which will delete an empty directory and lastly rmtree which is an abbreviation for remove tree and this is of the shuttle module and this will delete a directory containing files so if you would like a copy of all this code i will post this in the comments section down below but yeah that is how to delete files and or directories using python yo what's going on everybody it's you bro hope you're doing well and in today's video i'm going to be discussing modules in python so sit back relax and enjoy the show all right well welcome back we're talking about modules today a module is a file containing python code it may contain functions classes etc it's used with modular programming which is this concept of separating a program into useful different parts we're currently working within our main module and mine is named hello youtube this is how to create a separate module right click on your project folder go to new python file i think i'll create a module filled with maybe message functions so i'll call this messages and click python file all right we have two tabs one for our main module mine is called hello youtube and a separate module for messages and i can write whatever i want within here since we're using modular programming i'll place a bunch of useful functions within this module and i'll import them to the main module that we're currently working with let's define a function called hello all this will do is print hello have a nice day and i'll create a second function for good measure let's call this pie let's say bye have a wonderful time now if we would like access to this module we need to import it i will head back to my main module and at the top write this import then the name of the module and for this example we used the name of messages for our separate module and to use a function from that module type the name of the module dot and then the name of the function so messages.hello will call the hello function found within the messages module and i can also call the buy function as well messages dot bye and that will print bye have a wonderful time no it can be somewhat tedious to have to write the name the module followed by the function name what we could do to shorten things up is to give our messages module an alias also known as a nickname so at the top write import messages as and what sort of nickname should we give messages let's say msg for short so we'll replace messages with msg msg hello and msg buy and this would work the same and it involves less typing there's also an additional way of importing a module and it goes a little something like this from the name of the module import and then list all of the functions or classes you would like to import i would like to import hello comma buy and we no longer need the module name before calling one of these functions i can simply just call hello and vi directly another way in which this could be written is from messages import asterisk that means to import all and i actually would not recommend using this if you're working on a large program or something that contains many modules because you can run into a naming conflict because some of these modules may have the same named function names or variables so if you're working on a small program i really don't think it's a big deal but if you have multiple modules i would actually refrain from using import alt it's much safer to write the name of the module followed by the name of the function that you want to use now another cool thing is that python has a bunch of pre-written modules that you have access to if you would like a comprehensive list of them type help and pass in the word modules and within my console window this will populate a listing of all the modules available to us here they are let's see if math is in here yep there it is so yeah feel free to take a look through some of these modules because there are some fairly useful tools within some of these modules i suppose you can also go to python's official documentation and search for the python module index and here's a listing of all the different modules too they have access to well everyone those are modules they are files containing python code and they may contain functions classes etc if you would like a copy of all this code i will post all of this to the comments section down below but yeah those are modules in python i guess there's a module called pickle hey what's going on everybody it's bro hope you're doing well and in this video we're going to be creating a basic game of rock paper scissors in python so sit back relax and enjoy the show let's begin by importing the random module because we're going to need the computer to pick a random choice and we'll create a list of possible choices so we have three strings within here rock paper and scissors i think i spelled scissors wrong there we go okay and we will have our computer pick a random dot choice from our list of choices and let's test it by printing whatever the computer picks so the computer picked paper paper scissors and scissors okay what about the player choice let's say player equals input rock paper or scissors and let's print what the player has print player and let's print the computer too maybe i'll add a string before these so let's say computer call in space whatever the computer chooses and same thing with the player player all right let's see if this works rock paper or scissors let's say rock the computer picks paper and i pick rock so i would technically lose this round now what if the player doesn't pick rock paper or scissors what if they type in gun so we would like some way to prevent that so let's put our input for our player within a while loop while player not in choices so we're going to need to initialize player because right now it's an unresolved reference so let's say player equals none for the time being okay now let's test our choices our player choices rock paper or scissors i pick the gun and it's going to keep on asking me until i pick something from my list of choices so if i type in that still won't accept it now let's type in rock again there we go now what if somebody types in one of these choices either all caps or capitalized well that technically wouldn't be in choices because these strings are case sensitive so why don't we take our user input and make it lowercase and i'll just add on dot lower and use the lower method so therefore we can now type in any input that is either all caps or uppercase and then that will still be accepted because we're going to take our player input and then make it lower case so that it matches one of these choices okay let's work on the win conditions next so first let's check to see if we encountered a tie if player is equal to computer that means that we both chose the same thing so let's print whatever the computer picked what we picked and we will print tie now let's write an else if statement e l i f player equals rock so if we pick rock and then we will create a nested if statement if computer equals paper that means we lose so let's print everything we have here except we're going to change tie to you lose now if the computer picks let's say scissors then we win so scissors and you win okay then let's just repeat this process for scissors and paper so this will be another else if statement if we pick scissors and the computer picks rock then we lose if the computer picks paper then you win and lastly we have paper as the player choice so else if player equals paper and the computer picks scissors then we lose if the computer picks rock well then paper covers rock and we win now let's test it rock paper or scissors again i'll try and pick the gun which i can't let's take this seriously i will pick rock the computer picked rock so it's a tie i'm feeling like paper today oh it's another tie i guess and how about scissors okay so i win this round i picked uh scissors and the computer picked paper therefore i win let's try and lose this time just to verify it so i won again let's try rock again okay so i lost that round so we know that the win conditions are working now how about we add a feature where we will ask the player if they would like to play again play another round i think the best way to do that would be to write all of this code within a while loop so at the top let's write while true and we'll need to indent everything so that it's within the while loop so let's just indent everything here now at the bottom we will ask the user if they would like to play again and i will store this within a variable named play again play again equals input and the prompt will be play again yes slash no and depending on their input let's just make it all lower case if play again does not equal yes that means they would like to quit so let's use a break statement to break out of our while loop that we're in and at the end let's print by and pay attention to the indentation this input and this if statement should be within the while loop so they should have at least one indentation and our print statement here we'll just say bye and you can see that there is no indentation so that is outside of the while loop okay let's test this one last time rock paper scissors i'm going to pick the cannon okay that's not valid input how about rock okay the computer picks rock i pick rock so it's a tie do i want to play again i'm going to select actually yes all caps that should still be acceptable elbow paper this time it's a tie again man the computer is really good at this game i'd like to play again i'll pick scissors okay so i lose i would like to play again and i want to win this time okay computer pick scissors i pick rock you win do you want to play again nah and it will print bye well everybody that's a simple game of rock paper scissors i'll post all of this code to the comment section down below and well yeah that's a basic game of rock paper scissors in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to show you guys how we can build a basic quiz game in python so sit back relax and enjoy the show to begin this project i think it would be wise for us to create a skeletal structure for how this program is going to operate and then we'll fill in the gaps later as we go along so to begin let's define all of the functions that we'll need we'll need four we'll create a function that is named new game whenever we call this function it will create a new quiz game for us and for the time being let's write pass just as a placeholder we'll have a total of four functions new game a function to check our answer a function to display our score and lastly a function to play again all right now i'm just going to add some comments here just to separate each of these functions that we have just so that it's a little bit easier to read although this part is not really necessary so i just want to separate each of these functions for some readability okay those are all the functions that we'll need what we'll need now is some sort of collection to hold all of the questions and answers that we have and i think a dictionary would be perfect for this so what i did is that i created a dictionary named questions a dictionary has key value pairs each key is a question that i would like to ask and each question has an associated value we'll have the user guess between answers of a b c or d so these would be all of the correct answers all of the values within this dictionary so here are some of the questions that i want to ask feel free to come up with your own questions if you would like you can copy the questions that i have they should be posted in the comment section down below so the questions that i'm going to ask are who created python what year was python created python is attributed to which comedy group and lastly is the earth round i couldn't think of a fourth question so i just threw in a random stupid question and the correct answers to all of these questions in order would be a b c and a but feel free to come up with your own well we have our questions but we'll need some sort of collection to hold all of the different possible answers to each of these questions and i think a 2d list would work perfect for this so i have a list of lists a list of tuples could work too i suppose so here are all of the answers for the first question and the correct answer is a i believe his name is guido van rossum hey if you're listening man i'm sorry if i'm mispronouncing your name i'm really trying here the second list corresponds to the second question what year was python created it was created in 1991 at least according to wikipedia python is attributed to which comedy group the answer is c monty python like monty python and the holy grail good movie by the way and lastly is the earth round this is a highly debated topic but the answer is hey the earth is in fact round so i have a list of lists each list corresponds to a key value pair within my dictionary of questions and this is a lot to type if you want you can just copy the code that i posted in the comments down below just copy and paste and you'll have all of this or if you want you can pause the video and type it i don't care so now that you have your questions and your options we're ready to begin so the first thing that we'll do within our program is to call the new game function to begin a new game so after we have our questions and options created let's create a new game by calling the new game function now when we run this program we'll generate our dictionary of questions and our 2d list of different options for each question and then we will call the new game function to begin a new game so let's head to the new game function and fill in everything within our new game function so at the top let's declare a few things let's say we have a list named guesses and guesses will be an empty list for now i will declare a variable called correct guesses set it equal to zero because we haven't guessed anything yet and we will set a current question number and set the sequel to one to represent the first question okay now we need to display all of the questions within our dictionary of questions and we can use a for loop for that so for key in questions i'm going to print my key and let's just test this okay yeah here's all my questions i think what i'll do is actually print something to separate each question let's say one of these lines i think it would look better with them okay i'll print this line and then we'll move on to a question all right now after re-running this we have each question and i added just a line break between each of these to make it look kind of fancy now i need to display all of the different options for each question and we can do that with a nested for loop so if i were to write i in options print i let me show you what happens now with the way this for loop is written now it's going to display all of the different options available to us for the entire quiz game what i would like instead is to display only the first list for the first question and then the second list for the second question and follow that pattern so we're going to change our for loop around 4i in options and we'll set an index for options the index is going to be our question number minus one now remember what i said in previous videos where different collections including lists tuples etc the first element in a collection has an index of zero because computers always start with zero then the next element would therefore have an index of one then two three then you follow that pattern we're using this question number variable as some sort of counter and since we initially set this to one i'm just going to subtract one so that we effectively receive zero as the index and now we just need to increment our question number after each iteration so let's do that i will add that to the end here after we finish displaying all of the options let's increment question number by one by typing question num plus equals one and if i were to run this currently we'll display all of the different options for each question who created python here's all of the associated options what year is python created python is attributed to which comedy group and lastly is the earth round now it's time for some user input so i'm going to create a variable called guess and make sure you don't put it within your inner for loop it should be within the outer for loop guess equals input and i'll create a prompt enter a b c or d here's something to consider we would like the user to type in either capital a b c or d with strings they're case sensitive what if the user typed in one of these letters but lowercase if they're correct we would still like to give them their point why don't we take our guess and make it uppercase so guess equals guess and we can make this uppercase using the upper method of strings at the end of this game i'm going to compare our guesses to the correct answers so we have an empty list named guesses and i'm going to append our current guest that we're working on to our list of guesses so guesses dot append and we will append our guess this round now that we have our guess and we've appended our guess to our list of guesses let's check to see if it's the correct answer or not so we're just about to fill in this check answer function next so we are going to call this function and pass in a few items as arguments so let's use the check answer function and we'll pass in the key for the current question that we're on so the key is the correct answer so that would be our questions dot get key this would be the answer and we'll also pass in our guess and we are going to fill in the check answer function but we need to set up the parameters we're receiving effectively our answer as well as our guess so i'm going to name these as answer and guess and we are going to check to see if our answer is equal to our guess if answer is equal to guess let's print something print correct and i think we should give the user a point we'll have our check answer function return one for one point return one else if this is not the correct answer let's print wrong and we will return zero they do not get a point and since this is returning a value we should assign that so let's assign the point we may or may not receive to our variable of correct guesses which is initially set to zero so we'll type correct guesses plus equals check answer and check answer will return one if we scored a point or zero if we did not score a point and make sure you have plus equals because if you just set this to equals then we cannot score more than one point it will either be zero or one so we are effectively incrementing our correct guesses by one for each point that we score and now we're going to work on the display score function and we'll call that at the end after we finish all of our questions that we have so make sure that you do not write this within the for loop it should be outside of it because once we finish iterating through all of our questions we're going to display a final score so let's call the display score function and we'll need to pass in some arguments our correct guesses as well as our list of guesses okay let's head to the display score function so we have as parameters correct guesses as well as guesses i need to remove this pass i'm going to add one of these fancy lines in just to separate the questions from the results and i will print results and maybe another one of these lines okay so i need to print all of the answers answers and i do not want to end on a new line so i'm going to set end equal to nothing and i need to display all of the values within our dictionary all of the answers i will do that using a for loop for i in questions print questions dot get i and i do not want to end on a new line so i'm going to set end equal to nothing effectively and then i'll print a new line okay let's work on the guesses i think i'm just going to copy all this and make some changes i'll replace answers with guesses for i in guesses print i okay let's just be sure that everything's working we're not calculating a score quite yet so i'm just going to answer a then b c and d on second thought after printing each of these answers and guesses i'm going to add a space after each of these so within each of these four loops at the end i will add a space let me try that again a b c d okay not too bad now let's calculate the final score and we're still within our display score function let's set score equal to correct guesses divided by the length of our questions and let me add a set of parentheses around here then i'm going to multiply our score by 100 and if you don't want a decimal portion because we'll display a percentage we can cast this as an end okay that all looks good and we'll print the final score print your score is plus we need to cast our score to a string because we're using string concatenation plus i'll add a percent sign all right let's try it i'm intentionally going to get the last question wrong so we should have a 75 if we have four questions so that would be a b c is the earth round what's earth i'm gonna guess d answers a b c a your guess is a b c d your score is 75 okay let's test it but getting all wrong answers d d d d your score is zero percent congratulations and we'll test it one more time but get all the right answers we just want to be sure that we have 100 that's a b c a your score is 100 now the last thing that you can add is that we can play again if we want and i have a separate function for that if you would like to add this option here's how to do so let's remove that pass let's set a variable named response equal to some input do you want to play again let's ask for yes or no actually let me remove that okay and depending on the user's response it might be a lowercase so let's make it uppercase response equals response and use the upper method if response is equal to yes all caps if response is equal to yes then return true else we will return false and that is it for this function the last thing we need to do is to create a while loop that will continue to ask the player if they want to play again this will be after we call the new game function while play again and remember this will return either true or false depending on the user's response while play again new game and call the new game function to create a new game for us if we escape the while loop that means the user doesn't want to play again so let's print the message such as by e all right let's test it i'm going to get all of the correct answers this time a b c a all right your score is 100 do you want to play again i'm going to type yes all right then we can play again d d d d your score is zero percent do you want to play again no i think i mastered this game bye all right everybody so that's how you can use python to create a simple quiz game i will post all of this code to the comment section down below but well yeah that's a basic quiz game in python for you all hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain object-oriented programming in python so sit back relax and enjoy the show welcome to today's topic on python object oriented programming also known as pop and in today's video we're going to be creating objects an object is an instance of a class by using programming we can create representations of real-life objects so look around you wherever you're sitting or standing right now you are surrounded by objects next to me i have a phone a television some snacks and i'm talking into a microphone point being we can use programming to mimic real world objects by assigning a combination of attributes what an object is or has and methods what an object can do now in order to create an object we'll need to create a class a class can function as a blueprint that will describe what attributes and methods that our distinct type of object will have you can either create your class within your main module or you could create a separate file dedicated solely for your class now to create a class we would type class and then the name of the object that we would like to create so today i would like to create some car objects because i like cars so we would type car and a common naming convention with class names is that they should be capital so car is going to have a capital c and for the time being we need to type in something i'll just type in pass as a placeholder so if you have a small program it may be better to write your class within your main module but if your class is fairly large you may want to consider placing your class within a separate module so if you were to take that route we would go to file new python file and we would name this car click python file and we would declare our class within the separate module so class car and for now i'll type in pass then we just need to import this class so within our main module we would type from the name of the module import the name of the class from car import car now objects can have some combination of attributes and methods attributes describe what an object is or has so what are a few attributes that cars might have they might have a make so let's create a few variables for the time being i'm just going to use none as a placeholder cars can have a model a year and a color now objects can also have methods what kinds of methods could cars perform perhaps a drive method and a stop method so let's define those def let's say drive and we'll have one argument self self refers to the object that is using this method now what do we want to do when we call this method let's say this car is driving let's create a stop method as well def stop and we will print this car is stopped we now have all of the different attributes and methods we would like our car objects to have but there is one more thing that we need it is a special method called the init method that will construct objects for us in other programming languages this is known as the constructor so we need a special method that will create objects for us so we need to define this method def and the syntax on this is somewhat strange it is two underscores init it's short for initialize 200 scores again and then we need at least self as an argument and then we can actually assign our car objects unique variables so take all of these attributes that we have and we're going to place them within this init method now we can receive arguments when we create car objects but we need to pass them in as arguments to our init method so we need to set up some parameters let's say in order to create a car object we need a make a model a year and a color then when we receive these arguments we can actually assign them to each car's specific attributes but we need to precede each of these with self self is referring to the object that we're currently working on or creating so self.make self.model self.ear and self.color and then when we assign these we're going to say self.make equals whatever make that we receive when it's passed in as an argument self.model equals model and continue that pattern for year and color all right that is all we need for our class car we have a constructor we're assigning arguments that we receive to the attributes of our car object and we also have two methods one for drive and one for stop now we can start creating some car objects so going back to my main file here to create an object we need a unique name for it let's call this first car just car one equals the name of the class car then a set of parentheses now in order to construct a car object we need to pass in a matching set of arguments you can see here that we need to pass in a make a model a year and a color so what kind of car should we make let's say that the make is going to be chevy we need a model perhaps corvette a year 2021 is good and a color let's say blue alright now let's actually access some of these cars attributes and i should probably put this one in a print statement so print car ones make and this should print chevy then we can do the same thing for model year and color so let's change some of these around model year and color yep this object is a chevy corvette 2021 and the color is blue and we should have two methods as well so car one i would like this car to use its drive method this car is driving and let's have this car use it stop method car one dot stop this car is stopped there's one thing that i should mention real quick because i forgot to mention it earlier so within our init method you can see that we need five arguments in order to construct a car object self make model year in color but when we pass in our arguments we're not passing in anything for self we only have four arguments here that's because with python we do not need to pass itself that's done automatically for us we're referring to the object that we're dealing with as you can see with our drive and stop method we need to pass in self in order to execute our method but when we call this method we do not need to do so so just remember with python with self we do not need to pass in anything for this argument that is all now the nice thing about this is that we can reuse this class as a blueprint to create more car objects we just call that init method that constructor so this time let's create a second car called car 2 and this will be a different kind of car what kinds of arguments should we pass it let's say this is a ford mustang the year will be 2022 and the color will be red all right let's check card to use attributes and let's have car 2 use its drive and stop method this is a ford mustang the year is 2022 the color is red this car is driving and this car is stopped one other thing that we can do too is that within our methods here let's replace car with the name of the model that we're working with so this plus self dot model plus is driving now this self keyword think of it as you're replacing self with the name of the object that we're working on if car one is using its drive method replace itself with car one if this is car two that called this method then replace itself with car 2. think of it that way and let's do the same thing for stop this plus self dot model plus is stopped all right probably don't need these anymore so let's have car one use its drive and stop method this corvette is driving this corvette is stopped let's try this with car two this mustang is driving this mustang is stopped now you can have them do things independently too let's have car 1 use its drive method and car 2 uses stop method this corvette is driving and this mustang is stopped in conclusion a class can function as a blueprint to create objects we can assign attributes what describe an object is or has and methods what each object can do and then within our class we have a special method called the init method we can pass in some arguments and assign these arguments to each object's attributes and then we can reuse this class as if it was a blueprint so we can create more objects out of it so that is the basics of object oriented programming in python if you would like a copy of all this code i will post this in the comment section down below but yeah that's the basics of object oriented programming in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain the basics of class variables in python so sit back relax and enjoy the show here's a super quick video on the differences between class and instance variables for this example let's say we have two car objects named car one and car two and i'm just passing in a bunch of values to each of these car constructors now within my class car i have my init method also known as the constructor and what i'm doing is assigning all of these values to the variables found within my car constructor these variables declared inside the constructor are known as instance variables and each object can have their own unique values assigned to each of these variables now where a class variable is different is that a class variable is declared inside the class but outside of the constructor and what we can do is set some default values for some variables let's say we would like to add an additional variable let's say wheels wheels equals and we can set a default value for all instances of this class for each car object that we create so we set wheels to equal four this is an example of a class variable whenever we create a car object we can pass in a unique make model year in color but by default they will all have four wheels now if i was to print the amount of wheels that car 1 and car 2 have they will both have four wheels it's as if we're setting a default value if i change this to two wheels well then these cars have two wheels maybe their motorcycles or something now you can actually change these values each object will have their own copy of this variable but you can set it to a default value so let's say car one is a motorcycle car one dot wheels equals two so if i were to print car one's wheels along with card two car one will have two wheels but car two is still using that default amount of wheels which is four now there's another way in which you can access a class variable you don't necessarily need to create an object to do so you can just use the name of the class so what i'm going to do is turn all of these lines into comments and i will print the amount of wheels that our class has so type in the name of the class car with a capital c it should be the same name as your class name followed by the name of the class variable car dot wheels but make sure you spell it right all right so this will display four wheels now what if we decide to change the class variable through our class well that will affect all instances of our class so let's say car dot wheels equals two it's as if we change our mind and we have decided to create motorcycles instead of cars well if we were to change the wheels class variable through the use of our car class well then it's going to affect it for all instances of this class you can see that both car 1 and car 2 now have two wheels when we just changed car 1's wheels it did not affect car 2 at all so that's the main difference between a class variable and an instance variable an instance variable is declared inside of constructor and they can be given unique values with class variables they are declared within a class but outside of the constructor and you can set a default value for all instances of this class for all unique objects that are created and then you can change those values later too so if you would like a copy of all this code i will post all of this in the comment section down below but yeah that is the basics of class variables in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain inheritance in python so sit back relax and enjoy the show let's talk about irritants the term inherit means to receive derive or be left with and we can apply this concept to programming classes can inherit something usually attributes and methods from another class these classes can form parent-child relationships where a child will receive everything that the parent class has much like you inherit jeans from your parents and classes can have children and give whatever they own to their children and in today's video we'll be creating a parent class called animal and children of the animal class will inherit the common attributes and methods that all animals might have to kick off this video i think what we'll do is keep all of our classes within the same file just so that it's easier for us to read and understand let's begin by creating a class called animal so at the top type class animal and what are some attributes and methods that all animals should have let's say we have a class variable called alive and we'll set this to true if you're an animal you begin by being alive and what are some methods how about an eat and sleep method so let's define those def eat what are we gonna do when we call this method let's print something let's print this animal is eating let's also create a sleep method def sleep what are we gonna do when we call this method let's print something as well this animal is sleeping and we now have our animal class now let's create separate classes for specific types of animals let's say a class for rabbit a fish and a hawk so we can make objects of those classes so let's begin with a rabbit class class rabbit now to use inheritance with the class that you intend to be the child class after the class name add a set of parentheses and then pass in the name of the parent class in this case it's going to be animal so we will add that to the parentheses so now rabbit is the child class and animal is the parent class so the child class is going to inherit everything that the animal class has so for the time being i'm going to type pass so this rabbit class will have access to a class variable called alive and an eat and sleep method so let's define a fish and hawk class and i'm just going to copy what i have here and just change rabbit to fish and then do so again and change rabbit to hawk this is our family tree animal is the parent class and it has three children a rabbit class a fish class and a hot class and for the time being we're just going to write pass as a placeholder so i bet we can create objects from these classes so let's do so let's say we have an object called rabbit rabbit equals rabbit let's do the same thing for fish and hawk all right we now have three objects rabbit fish and hawk and let's take a look at their class variables i bet they have an alive variable let's check that so i would like to print rabbit dot oh would you look at that this rabbit class has a class variable called alive even though there's nothing within this class well that's because we used inheritance so each of these three children classes inherit everything from their parents all of these attributes and methods i bet they have eaten sleep functions as well so let's check that with fish let's have fish use its eat method and hawk will use its sleep method hawk dot sleep so the rabbit is alive the fish is eating and the hawk is sleeping now even though we have nothing written within each of these specific types of animal classes all of these animals have access to these attributes and methods because of inheritance and another benefit of inheritance is that we don't need to keep on copying and pasting this code for example let's say we were not using inheritance so we would not need an animal class we could write our code this way where we would just copy and paste everything underneath each of our classes so what if we need to make a change to one of these methods as in your boss says you know what let's change sleep to slumber okay well we would have to go to each of these classes and make the change manually it's not too bad if you have like three classes but what if you have hundreds that's going to take a lot of effort so wouldn't it be nice if we just list everything that each of these classes has in common and then have all of these classes inherit from one common class and then if you need to make any changes you can do so just within this class and this change will apply to all of the different child classes so that's another benefit of inheritance and not only does it make any changes easier but each class can have their own unique attributes and methods as well along with the attributes and methods that they inherit from their parents so for rabbit fish and hawk let's have each of these classes have their own unique method as well so for rabbit let's define a run method if you're a rabbit then you can run so let's print this rabbit is running and i'm just going to fix some of the spacing here all right if you're a fish then you can swim def swim let's print this fish is swimming and lastly we have hawk if you're a hawk then you can fly def fly let's print this hawk is flying like i said before not only do these specific types of animals have access to all of the attributes and methods that they inherit from their parents but they can have their own attributes and methods as well so let's test some of these methods so we have our rabbit fish and hawk objects let's have rabbit use its run method fish we'll use its swim method and hawk will use its fly method and here we go this rabbit is running this fish is swimming and this hawk is flying so in conclusion classes can have children the children classes will inherit everything that their parent class has all of the parents attributes and methods but not only that the children classes can implement their own unique attributes and methods as well so that is inheritance if you would like a copy of this code i will post all of this in the comment section down below but yeah that's the basics of inheritance using python yo what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain how multi-level inheritance works in python so sit back relax and enjoy the show all right welcome back everybody let's talk about multi-level inheritance this is a concept where a derived class also known as a child class inherits from another derived class here's an example let's say we have a hierarchy of classes there will be three levels to this we'll create a family tree of living organisms so at the very top we're going to have a class called organism any class that inherits from the organism parent class will receive one attribute one variable named alive and this will be set to true so if you are an organism you begin by being alive now let's say we have a child class that will inherit from the organism parent class let's say animal class animal inherits from organism so any animal that we create will have this alive attribute set the true and all animals eat so let's define a function that does that at least i believe all animals eat let's pretend that they do so this animal is eating and now why stop there let's create a class for a specific type of animal i like dogs so let's create a dog class class dog inherits from the animal class and all dogs should be able to bark so let's create a function to do that and we'll print this dog is barking okay so what we just did here is multi-level inheritance we had a derived child class inherit from another child class so it's kind of like this dog class is the child animal class is the parent and then the parent of the parent class would be like a grandparent right and then if you added another layer on top of that to this hierarchy well then the parent of the grandparent would be like a great grandparent that's how i think of it at least now let's create a dog object just to verify that everything's working so let's call our dog dog and our dog object should have access to an attribute named alive and our dog object receives that attribute from the organism class and this will print true if i were to print whatever this attribute contains and our dog should be able to eat because it receives this method from the animal parent class and lastly our dog should be able to bark and that method is defined within its own class so that's how multi-level inheritance works it's a concept where a child class will inherit from another child class i like to think of it like a family tree where a child class will have a parent and the parent of that parent would be like a grandparent basically so if you would like a copy of this code i will post all of this to the comment section down below but yeah that is how multi-level inheritance works in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to show you all how multiple inheritance works in python so sit back relax and enjoy the show all right people multiple inheritance multiple inheritance is the concept where a child class is derived from more than one parent class here's an example let's say that all of our children classes are going to be certain types of animals and we would like our animal classes to inherit from either the prepared class the predator parrot class or both depending on what type of animal it is because some animals in the animal kingdom can be both prey and predators and one example that comes to mind would be fish fish will eat smaller fish but also can get eaten by larger fish so here we have two classes prey and predator each has a dedicated method if a class inherits from the prey parent class they will have access to a flea method which will print this animal please if a class inherits from the predator parent class that class will have access to a hunt method that will print this animal is hunting and it's possible that some animals can do both they can both flee and hunt but they'll need to inherit both of these classes both prey and predator and that's where multiple inheritance comes in now let's create some classes based on certain types of animals let's say we have class rabbit and rabbit we'll inherit from the prey class because rabbits are typically prey and not predators but i don't know there could be some killer rabbits out there haven't run into any yet let's have class hawk inherit from the predator class and lastly fish and fish can be both prey and predators so they will inherit from both classes and we just separate each class with a comma so prey comma predator and it's as simple as that now let's create an object from each of these classes we have rabbit equals rabbit hawk equals hawk and fish equals fish now let's just verify all of the different methods that each of these objects inherited so our rabbit should have access to a flea method but no hunt method and let's just test that yep this animal flees and my hawk object should have access to a hunt method but no flea method this animal is hunting and lastly my fish object has access to both a flea and a hunt method and if you take a look on the right hand side of this pop-up window it shows the class that it inherited this method from so fleet comes from the parent class of prey and hunt comes from the apparent class of predator so my fish can both flee and hunt because it's typically considered both prey and predators this animal flees this animal is hunting so that's basically what multiple inheritance is it's a concept where a child class is derived from more than one parent class so that's basically multiple inheritance i'll post all of this code to the comment section down below and well yeah that's how multiple inheritance works in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to teach you guys about method overriding in python so sit back relax and enjoy the show here's a super quick video on method overriding i have two classes a class called animal and a class called rabbit rabbit inherits from the animal class therefore rabbit is the child class an animal is the parent class within the animal class there is one method a method called eat and when you call this method all this will do is print this animal is eating the rabbit class inherits from the animal class therefore rabbit has access to this eat method and if i were to create a rabbit object and this rabbit used its eat method well then this is going to print this animal is eating now method of writing is the ability of an object oriented programming language to allow a subclass also known as a child class to provide a specific implementation of a method that is already provided by one of its parents in this case we're going to override the eat method and what we can do is provide a more specific implementation for the rabbit class and now to override a method what we'll do is that within the child class we need to define a method with the same matching method signature that is the combination of a method's name plus its parameters both of these together are known as a method signature within the child class we will define and eat method with the same parameters def eat and in this case the only parameter is self just to keep this simple and what we'll do is that will provide a more specific implementation of the eat method specifically for rabbits so let's print something more closely associated with rabbits such as this rabbit is eating a carrot now if i were to run this program again we will instead use this implementation of the method instead of the one that it inherits from its parent class of animal basically speaking an object will use a method that is more closely associated with itself first before relying on a method that it may inherit from a parent class in this example we're using this version of the eat method specifically for rabbits instead of the version that we inherit from the parent class of animal that is the basics of method overriding i will post this code in the comment section down below and well yeah that's how to override a method using python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to teach you guys all about method chaining in python so sit back relax and enjoy the show all right everybody let's talk about method training method chaining is used to call multiple methods sequentially and each call performs an action on the same object and return self here's an example of how method chaining would be useful let's say we have a class named car car has four methods turn on drive break and turn off they will all just print a simple message beginning with turn on turn on what print you start the engine drive will print you drive the car brake will print you step on the brakes and turn off will print you turn off the engine let's say we have a car object car equals car and i would like my car object to use its turn on method immediately followed by the drive method with how we've been coding things previously we may write something such as the name of the object in this case car dot and then the method to use i would like my card to use the turn on method followed by car dot drive so currently this will take two lines of code but this will print you start the engine and you drive the car now with method training we can call multiple methods sequentially now the format on this is going to be a little bit different and if we were to write the same code using method chaining it might look a little something like this after the first method call we would add dot and then an additional method that we would like to call so for example after the turn on method we'll immediately call the drive method but there's one more thing that we need to add when we're using python to do method training so normally this by itself will not work when we call a method in python if there is nothing that is returned python will return none so as you can see here attribute error none type object has no attribute of drive so we need to return itself under each method that we're using method training with so let's add return self to each of these methods so let's do that for drive break and the turn off method and this should work now you start the engine you drive the car so think of it like this after we finish calling this method python is going to return self so it's going to return car so then we'll immediately use car.drive now here's another example let's say i would like to call the break method followed by the turn off method so that would be car dot break parentheses followed by dot turn off so this will print you step on the brakes you turn off the engine now here's an extreme example let's say we would like to call all four methods in order so that would be car dot turn on followed by dot drive dot break dot turn off so this will call all four methods in order starting with the leftmost method you start the engine you drive the car you step on the brakes you turn off the engine now if you have one long method chain like this it might become difficult to read after a while so what i would recommend if you're doing a lot of method chaining is that after each method call just hit enter to move each method call down to a new line so it'll look something like that and this backslash might be inserted this is a line continuation character so this is a little more readable but you know it still does the same thing basically all right everybody so that is method training it's used to call multiple methods sequentially and each call performs an action on the same object and returns self if you would like a copy of this code i will post all of this in the comments section down below but yeah that is how to do a method chaining in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain the super function in python so sit back relax and enjoy the show well then since you clicked on this video i should probably discuss the super function now the super function is used to give access to the methods of a parent class it returns a temporary object of a parent class when used here's an example of why the super function would be useful let's take this program that i've written there's three classes a class called rectangle which is the parent class to two children classes square and cube and all we're doing is creating a square object and a cube object but we need to pass in a length and a width for squares and a length width and height for cubes now with programming we don't like to repeat code we like to reuse code and if you take a look within my knit methods for both square and cube we're repeating self.length equals length and self.width equals width twice for our init methods so one thing that we can do any similarities between the square and cube class we can place within the rectangle class and then reuse this code so what i'm going to do is copy this indent method within our square class and paste it within our rectangle parent class and then in order to access this init method we can use the super function so we no longer need these two lines of code what i'm going to do is ask the rectangle class to use its init method so we're going to type super parentheses dot and then the name or the function of the parent class that we would like to use and i would like to use the init method but i need to send a length and a width because it requires that so let's send these so we're going to pass in our length and our width and now we can do the same thing for our cube init method so i will copy this line of code we no longer need these two lines of code because we will be reusing our init method within the parent class of rectangle but we'll still need to keep this line in to assign the height because that's a difference between our square and cube class and now we can just reuse this init method within the rectangle parent class now i'm thinking that we should probably test to see if length and width are assigned to these attributes and one way that i think would be fun would be to create an area method for squares and a volume method for cubes so let's define an area method within the square class def area and i would like to return self dot length times self dot width and we can create a volume method within cubes so let's do that def let's change this to volume we'll multiply it length times width times height but we need to type self dot pipe and we can call these methods to get the area of a square or the volume of a cube let's print square dot area and then cube dot volume so if our init method is actually being used we should have a length and the width assigned to these attributes and it looks like we do in conclusion the super function is used to give access to the methods of a parent class it returns a temporary object of a parent class when used in order to access the methods of the parent class also known as a super class and in this example within the init methods of both square and cube we immediately called the init method of the parent class to pass in some arguments that both of these classes have in common so if you would like a copy of this code i will post all of this in the comment section down below but yeah that is how the super function works in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain how abstract classes work in python so sit back relax and enjoy the show hey what's good everybody let's talk about abstract classes now abstract classes prevent a user from creating an object of that class think of an abstract class more as a template it's an idea it's not real it's like a ghost class basically plus an abstract class compels a user to override any abstract methods within a child class so it's also a form of checks and balances as well which we'll discuss later now here's a small program that i've written let's say we have three classes class vehicle car and motorcycle car and motorcycle are the children classes of the vehicle class now within this vehicle class we have a go method but i'm currently only defining it not actually implementing it so i'm just writing pass now within car and motorcycle we're overriding this method and creating our own implementation of the skull method that we inherit the go method for the car will print you drive the car and the go method for the motorcycle class will print you ride the motorcycle now currently i'm creating an object of each of these classes i have a generic vehicle object car object and motorcycle object now after running this program currently the go method within our vehicle class is not being implemented so this won't print anything but the go method within our car class will print you drive the car and the go method within our motorcycle class will print you ride the motorcycle with that being said let's pretend that we're coding the next need for speed game and we would like a user to create an object from a specific kind of vehicle whether it's a car from the car class or a motorcycle from the motorcycle class we would like to prevent a user from creating an object of the vehicle class because the vehicle class is too generic we do not have all of the implementations set up for a vehicle it would be like somebody unlocked the ghost car or the invisible car which doesn't actually exist and is missing a lot of features we need a user to create an object from a child class because these are fully fleshed out and one way in which we can prevent a user from creating an object of this class as well to turn this class into an abstract class which is what this video is all about go figure now the first step to creating an abstract class is that we'll need some imports so at the top of your program write this from abc abc is an acronym for abstract based class abc from abc import abc all capital comma abstract method all right now with our vehicle class the class that you intend to be the abstract class add us out of parentheses and our vehicle class will inherit from the abc class and now with any methods within your vehicle class you're going to add this decorator at the top at abstract method all right we should now be prevented from creating a vehicle object our vehicle class is now an abstract class and we cannot give it a physical form a physical manifestation and if we attempt to you can see here that we have a type error can't instantiate abstract class from vehicle with abstract methods go so an abstract class is a class which contains one or more abstract methods and an abstract method is a method that has a declaration but does not have an implementation now by definition an abstract class contains one or more abstract methods if i remove this one abstract method within our vehicle class well we could still create a vehicle object and i'm just going to turn this vehicle.go line into a comment because we don't have a go method anymore as you can see we can still create a vehicle object which we would like to prevent a user from doing so we need at least one abstract method within our vehicle class so i'm going to go ahead and add this go method back in an additional feature of abstract classes is that they compel a user to override any abstract methods within a child class a method that is abstract has a declaration but does not have an implementation so let's say that we create our vehicle class our abstract vehicle class and now we're creating the children classes of car and motorcycle and let's say i'm not paying attention and i forget to add a go method so if i just write pass within my motorcycle class i'm currently missing a go method within my motorcycle class well python is going to prevent me from running this because we have a type air can't instantiate abstract class vehicle with abstract methods of go so by inheriting from an abstract class it's a good form of checks and balances to be sure that your children classes are not missing any implementations of any methods that they inherit here's an additional way of thinking of this our vehicle class is telling its children if you're going to inherit from me then you need to override this abstract method of mine and if you don't well i'm not going to let you be instantiated so in order for us to create a cart and motorcycle class we need to override the go method that they inherit from its parent class of vehicle and provide its own implementation now let's say we create an additional method let's say we have a stop method so let's define that def stop for the time being i'll write pass and to make this an abstract method add this decorator at abstract method now car and motorcycle both need to implement that method of stop it's currently missing it as you can see here class car must implement all abstract methods and the same thing applies for a motorcycle as well so we need to override this method and provide its own implementation so let's remove that decorator and let's print something let's print this car is stopped and i'll do the same thing for motorcycle so def stop let's say this motorcycle is stopped and we'll call the stop method for each of these types of vehicles car dot stop and motorcycle dot stop all right and we can now create a car and motorcycle object because we are overriding both of these abstract methods found within the parent class of vehicle all right everybody so that's the basics of abstract classes it's a class which contains one or more abstract methods and an abstract method is a method that has a declaration but does not have an implementation and the benefits of using an abstract class is that they prevent a user from creating an object of that class plus it compels a user to override any abstract methods found within a child class so if you would like a copy of this code i will post all of this in the comments section down below but yeah that is how abstract classes work in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain how we can pass objects as arguments so sit back relax and enjoy the show ladies and gentlemen in today's video i'm going to be demonstrating how we can pass objects as arguments for this example let's say we have a class car and there is one class variable called color color equals none what we'll be doing is calling a function that accepts an object as an argument as well as a color so let's create a function named change color now make sure when you define this function it's not within the cart class then technically this would be a method of the car class what we would like is a separate function outside of the car class now we need to set up some parameters we would like to accept a car object as well as a color so for the first parameter let's say a car and make sure this is in uppercase or capital because python doesn't like that argument names should be lowercase so when we pass in a car we will give it a nickname of car and we would also like to pass in a color so let's set up a parameter called color now when we pass in a car we will assign that car's color with whatever color that we receive so car dot color equals color and now let's create some car objects so let's say car one equals car car two equals car and car three equals cart currently if i were to print their colors this is what we'll see print car one dot color and repeat the steps for two and three and we're not calling this function yet so all of these colors should be set to none they are basically cars with no color they're i don't know iron or something whatever cars are made out of aluminum plastic stuff like that okay so now let's call this function change color perhaps right here so in order to call this function we need to pass in a car object as well as a color so let's pass in car one and a color perhaps red and we'll repeat the steps for two and three so let's say car two will be white and car 3 will be blue now after calling this function we have a car object and a color and we're assigning the color of our car to whatever color that we receive now these cars in order car 1 2 and 3 are red white and blue now one thing that you should know is that the name of this parameter that accepts our object doesn't necessarily need the same name as the class name that created the object that we're passing in we could name this something else entirely perhaps vehicle you'll just want to be sure that this is at least descriptive of the kind of object that you would like to pass in and we're not limited to just passing in car objects we can pass in all sorts of objects but we need to pass in an object as well as a color so this time let's create a class called motorcycle class motorcycle and this class will also have a color set to none so what we're doing is actually reusing this function for all sorts of different kinds of vehicles now let's create a vehicle i'll just name this bike one for short bike one equals motorcycle now let's call the change color function and we can pass in an object as well as color this time we will pass in our bike object as well as a color i think black counts as a color and let's print bike once color and this should work we have red white blue and black in conclusion we can pass objects as arguments to a function much like what we've been doing with variables however the type of objects that we pass in may be limited based on the required attributes and methods that that given class or object might have and we'll get more into this on the next video on duct typing so if you would like a copy of all this code i will post all of this in the comment section down below but yeah that is how to pass objects as arguments using python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to explain duck typing in python so sit back relax and enjoy the show i hope you all like ducks because that's the topic of this video duct typing is the concept where the class of an object is less important than the methods and or attributes that that class might have the class type is not checked if the minimum methods and or attributes are present it's based off of a popular phrase if it walks like a duck and it quacks like a duck then it must be a duck here's an example i have two classes class duck and class chicken both duck and chicken have walk and talk methods but they print something different with the duck class the walk method will print this duck is walking and the duck talk method will print this duck is quacking the chicken class has the same named methods walk and talk but they print something slightly different a slightly different variation the print method will print this chicken is walking and the talk method will print this chicken is clucking now let's say we have a third class a class called person now there is one method within our person class let's say we're attempting to catch a duck we'll pass in self and we need to pass in a duck object as an argument so let's type duck now within this method we'll have our duck use its walk method as well as its talk method duck.walk and duck.talk and then maybe we'll print something such as you caught the critter now let's create an object from each of these classes let's create a duck object duck equals duck a chicken object chicken equals chicken and lastly person person equals person now if we would like our person to use the catch method we need to pass in a duck as an argument so with our person let's type person dot catch and we need to send a duck object because that's a required parameter here so we're passing in our duck object that we created and as soon as we catch the duck it's going to use its walk and talk method and then we'll print you caught the critter so as you would expect this will print this duck is walking the stuck is quacking you caught the critter now with duct typing we can pass in a different type of object as long as it has the same methods and or attributes as our duck we could pass in a chicken because a chicken can also walk and talk so this time let's pass in our chicken as an argument and this will still work even though our parameter is set up to take a duck object this chicken is walking this chicken is clucking you caught the critter in layman's terms think of it like this python is examining this chicken object it's using its walk method it's using its talk method which are required and python is saying well that's close enough remember if it walks like a duck and it quacks like a duck then it must be a duck so duct typing is the concept where the class of an object is less important than the methods and or attributes that it might have the class type is not checked if the minimum methods and or attributes are present now let's say with our chicken object our chicken can no longer walk well we cannot pass in our chicken object anymore we have an attribute error chicken object has no attribute walk so python took a look at this chicken and noticed that it does not have a walk method well it's not walking like a duck but it's talking like a duck so it doesn't count as a duck because it doesn't have its walk method in conclusion the class type of an object is not as important as the methods and or attributes that that class might have when using duct typing the class type will not be checked if the minimum methods and or attributes are present since chickens can both walk and talk like ducks then they can be a substitute for ducks when we pass in our duck object to this method so if you would like a copy of this code i will post all of this in the comment section down below but yeah that is the basics of duct typing in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to discuss the walrus operator in python so sit back relax and enjoy the show all right people i hope you like walruses because that's the topic of this video we'll be discussing the walrus operator also known as an assignment expression it's a colon followed by an equal sign and it kind of looks like a walrus on its side now this is a new feature for python 3.8 what it does is that it assigns values to variables as part of a larger expression here's an example of why the walrus operator would be useful let's say we have a variable named happy happy equals true if you're not happy or you're feeling so so you can set this to false if you want so let's print the value contained within happy so this will print true to the console window now wouldn't it be cool if we could combine both of these statements together so we would want to say something such as happy equals true and then print it to the console window using one line of code well normally we can't do this using the standard assignment operator now one thing that we can do is use the walrus operator this assigns a value to a variable as part of a larger expression so this would technically be allowed if this assignment operator was instead an assignment expression the walrus operator happy walrus true and when they're all within a print statement we can assign a value to a variable and use it as a part of a larger expression so as you can see this new variable of happy was assigned and used in one expression now here's a more practical example of why the walrus operator would be useful let's say we have the smell program what this will do is consistently ask you what food you like and put it into a list called foods foods equals list while true food equals input what food do you like if food equals quit break then append our list of foods with this new food item that we have okay let's run this then so this while loop will continue as long as i don't type in quit and it will consistently ask me what food do i like and place that food item into a list named foods so let's begin what food do i like well i do like pizza i like sushi and i like ice cream and that should be enough for me i'm going to type in quit to exit this program now let's write the same program but instead use a walrus operator so that we can write this program using less lines of code now if i were to use the walrus operator this is how i would write the same program we would still need our list foods equals list now for my while loop it's going to look something like this while food walrus operator input what food do you like all right this is the assignment portion now we can use this assignment portion within a larger expression so let's also check to see if our input does not equal quit alright so then after each iteration of this while loop we will take our list foods dot append food and that is it so we have written the same program in about half the lines of code that we did previously so let's test it what food do you like pizza sushi ice cream and quit well everybody that is the basics of the walrus operator also known as an assignment expression it's a new feature for python 3.8 and beyond so if this doesn't work for you i would check to see what version of python you're using first it assigns values to variables as part of a larger expression if you would like a copy of this code i will post all of this in the comment section down below but yeah that is how the walrus operator works in python hello what's going on everybody it's bro hope you're doing well and in this video i'm going to show you guys how we can assign a function to a variable in python so sit back relax and enjoy the show hey all in today's video i will show you all how we can assign a function to a variable this video will be a prerequisite for a few videos i have coming up regarding functions now let's say we have a function named hello and all we'll do is print the word hello and as you know to call this function you would type the name of the function followed by a set of parentheses and this will print the word hello the set of parenthesis that comes after a function's name is the portion that will call the function if you were to remove that set of parenthesis afterwards we would not in fact call that function now with python python will pretty much treat everything as objects including functions so there's something i want to show you guys if i was to print the name of my function hello what will be displayed is the memory address of this function this is the memory address of where this function is located within my computer's memory and it's in hexadecimal think of it like a street address such as one two three fake street this is the address of where this function is within my computer's memory and each time that i run this program this number can change as you can see here now one thing that we could do we could assign this address to a variable let's say hi equals hello and be sure that you're not adding that set of parentheses afterwards because then you would be calling the hello function and returning the result to high so high equals hello no parentheses and if i was to print hi well the address of hello and hi will be at the same memory address both of these numbers are the same now what do you imagine would happen if i was to call the high function after we assigned the memory address of hello to hi well then what we'll end up doing is calling the hello function even though we're listing that we would like to call the high function even though it doesn't exist so it's as if this hello function has two names you can either use hello or you can use hi and let me demonstrate that so you can call either hello hi or both for this example that's because we're assigning the memory address of hello to this variable of high so we could treat high as a function it's kind of like an alias where this function has two names now here's another demonstration let's say that we would like to assign our built-in print function to a variable so let's say maybe say say equals print and when i say print i'm referring to the print function and be sure you're not adding that set of parentheses afterwards now if i need to print something to the console window i can either use print like what we've previously been doing or i could use say because say has the same memory address let's say perhaps whoa i can't believe this works surprise face all right so we can call the print function by saying the word say say all of this text and this will print all of this text well say all of this text to the console window under normal circumstances i'm not sure why or when you would need to assign the print function to a variable but you can and well that's kind of cool so i thought i'd show you guys that so everybody that's how to assign a function to a variable like i said we'll be building upon this topic so you want to be sure that you understand this all right then well if you would like a copy of this code i will post all of this to the comments section down below but yeah that's how to assign a function to a variable in python hey uh what's going on everybody it's bro hope you're doing well and in today's video i'm going to explain higher order functions in python so sit back relax and enjoy the show all right ladies and gentlemen let's talk about higher order functions these are functions that do one of two things one they either accept a function as an argument or two they return a function as output and in python this is totally allowed because functions are also treated as objects i'll give you guys an example of both of these but let's begin with number one here's an example of number one let's say that i have two functions named loud and quiet both of these functions will accept a string as an argument loud will return that string all uppercase as if we're shouting something quiet we'll return that text i'll lowercase as if we're whispering something now i'm going to create a third function called hello and this will be the higher order function it accepts a function as an argument i'm not sure if we're going to be passing in loud or quiet whatever it is i'm going to give it a name of funk short for function each of these functions will return some text either all uppercase or lowercase i'm going to assign that to text text equals the name of our function we're not sure what it's going to be and i will pass in some text in order to call one of these functions i will pass in just the word hello that's capitalized and at the end i will print whatever text that we have in order to call this function of hello i need to pass in a function as an argument do i want to pass in loud or quiet do i want the loud variety of hello where all of the text will be uppercase or the quiet variety of flow where all the text will be lowercase i would like to pass in loud because i want to make my text all uppercase so i'm typing the name of the higher order function and passing in a function as an argument and the result is that the word hello will be printed to the console window all uppercase now here's a rundown of what just happened we're calling the hello function and we're passing in loud as an argument we're naming loud as funk while we're within this hello function text equals loud and we're sending a string of text that says hello we're returning that text all uppercase assigning it to a variable called text and printing that text to the console window now if i would like to use the quiet variety of hello then i'm going to pass in quiet as an argument so quiet will make all of this text lowercase alright people so that's example one of a higher order function a higher order function is a function that accepts a function as an argument this hello function is an example of a higher order function because we're accepting either loud or quiet as arguments all right people let's move on to the second part of this definition for higher order functions a higher order function is a function that returns a function i'm going to give a different example this time let's say we have a pair of nested functions the outer function will be named divisor and we will accept a number as an argument that we will call x a divisor is a number that is used to divide another number when using division and inside this function we have an inner function named dividend dividend is the number that's going to be divided and we will call the argument that is passed in y all we'll do is return y divided by x we're dividing the dividend by the divisor y divided by x now within the outer function but not within the inner function we're going to return our dividend function so a higher order function is a function that returns a function divisor is a higher order function because we're returning dividend now if i would like to access this nested dividend function i first need to call the outside divisor function and pass in a number as an argument to serve as the divisor the divisor function is going to return my dividend function which we can then assign to a variable so the variable i'm going to name divide divide equals and i need to call divisor and set a divisor let's say that i would like to divide all numbers by two so i will set x to be two and now for the dividend i will print call the divide variable and pass in a number as the dividend the number that's going to be divided and let's say i would like to divide 10 by two and this will work as you can see we have five in the console window so let me explain what just happened here so our program begins here divisor and we're passing in two x will be two and it will stay that way until we finish this program or until we reassign x now x equals two we're skipping this function because we did not call it yet we're returning dividend and assigning it to a variable and we can call a variable if it has the memory address of a function which is what we're doing in this line now we're calling dividend and passing in 10 so y equals 10 and x still equals to we're returning 10 divided by 2 and printing it to the console window well everyone in conclusion a higher order function is a function that either one accepts a function as an argument or two they return a function the format is a little bit strange and we're not quite used to it yet but in future videos we'll have more practice with high order functions if you would like a copy of all this code i will post all of this to the comment section down below but yeah that is how higher order functions work in python yo what's going on everybody it's bro hope you're doing well in today's video i'm going to explain lambda functions in python so sit back relax and enjoy the show all right ladies and gentlemen let's talk about lambda functions these are functions that are written in one line and use this lambda keyword they accept any number of arguments but they only have one expression think of it as a shortcut they're useful if you need a function for only one use or a short period of time and then you're just planning on throwing away that function afterwards here's the syntax for a lambda function you type lambda you add the parameters followed by a colon and then your expression let's say we have this function named double double accepts one argument that we will name x we're returning x times two effectively doubling it so if i need to call this function i would type double and then pass in a number as an argument so the result if i pass in 5 would be 10. now let's write the same function but instead write it as a lambda function so let me turn these lines into comments now the first step is to type lambda then our parameters we only have one parameter and that is x colon and then our expression we would like to return x times two now this lambda function is going to return a function object and we can assign that much like what we do with variables let's say double equals lambda x colon x times two and in order to call this lambda function we're going to type double then a set of parentheses to call this function and then pass in our arguments so let's say that x equals 5 and then we're going to double it and the result is 10. so that's the syntax for a lambda function you type lambda your parameters colon and then your expression this time let's say that we have two parameters we have two numbers that we want to multiply by each other so let's say that this function will be called multiply multiply equals lambda x comma y because we have two parameters colon followed by our expression we would like to multiply x times y and that is it now in order to call multiply we need to pass in two arguments if i were to pass in just one well we'll have a type error so let's pass in five and maybe six and the result is thirty now let's try three parameters let's say we would like to add three numbers together let's say add lambda x comma y comma z so we have all of our parameters we have our colon here and then we need our expression x plus y plus z and let's add five six and seven together the result is 18. now let's try something a little more complex let's pass in some strings this time i'll create a function named full name full name equals lambda first name comma last name the expression is going to be first name plus perhaps a space plus last name now i need to pass in a first name and a last name full name and you can use your own name for this example if you want let's say bro comma code yep this will print your first name and your last name to the console window now let's take it a step further let's say we would like to check somebody's age once using a lambda function we would like to check to see if they're 18 or older because they're signing up for something perhaps let's say a credit card so let's create a function object age check equals lambda we have one parameter somebody's edge colon and then our expression let's type true if age is greater than or equal to 18 else false to call this age track function we need to pass in an age let's say the user is 12 and they're trying to sign up for a credit card while this will return false let's say they're 18 now and this will return true so that's a lambda function it's a function that is written in one line using this lambda keyword they accept any number of arguments but they only have one expression think of it like a shortcut and they're useful if you need to use a function only once and then you're just planning on throwing it away afterwards so if you would like a copy of all this code i will post all of this to the comment section down below but yeah those are lambda functions in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to show you all how we can sort iterables in python so sit back relax and enjoy the show well well well welcome back everybody in this video i'm going to show you all how we can sort data using python we'll begin with the sort method which is used with lists and the sort function which is used with iterables and that would include lists let's start with something very basic and then we'll crank up the difficulty one step at a time i have a list named students and i have a bunch of student names within this list we have squidward sandy patrick spongebob mr krabs let's say that all of these students are taking a college course perhaps on marine biology what i would like to do is to sort this list in alphabetical order and to do that we have a method that is built in with lists so type the name of your list students dot sort and it's easy as that and to display this list i think i'll use a for loop for i in students print i and there you go that's how to sort a list starting with the top we have mr krabs then patrick sandy spongebob and squidward the sort method of lists can accept keyword arguments there are two optional keyword arguments that we can pass in we can pass in key and or reverse we'll cover key a little bit later if we set reverse to true then our list will be sorted by reverse alphabetical order beginning with squidward spongebob sandy patrick then mr krabs now the sort method does not work with other iterables it's a built-in method for lists if our list of students was instead let's say a tuple well then the sort method is not going to work you can see here that we have an attribute error tuple object has no attribute of sort that's where the sort function would come in because that's useful for other iterables you can also use this for a list 2 i suppose the sort function will return a sorted list so let's use the sort function this time and we'll assign the result to a list called sorted students equals sorted and then we need to pass in an iterable and we have the option of passing in a key and or reverse the iterable that we'll pass in as an argument is our tuple named students so this line will be sorted students equals sorted students sorted students is a list the sorted function will return a list but it accepts an iterable as an argument and to display this we should change 4i and students to 4i in sorted students and now this function will accept our iterable our tuple and create a sorted list and all of these are in alphabetical order and to reverse this we can pass in the keyword argument of reverse equals true and now our list is sorted in reverse alphabetical order all right we're gonna take it up a level welcome to level two sometimes data isn't always as simple here we have a list of tuples each tuple has a corresponding student record we have a name a letter grade for their college course and the student's age now how can we sort this list of tuples by either the student's name their grade or their age well that's where the key keyword argument's going to come in with sorting if you take a look at this list of tuples it somewhat resembles a spreadsheet there's rows and then there's columns the first column corresponds to student names the second column are grades and the third column are all the ages of the students so by default sorting by the first column is actually really easy that's the default so if we need to sort alphabetically that would be the same process as before we would type the name of the list students dot sort but if we were to print this iterable for i in students instead of just the individual student names we're going to get each tuple that we have so now all of these tuples are arranged in alphabetical order starting with the first column that we have which are all the student names now how can we sort these iterables by their second column for this case it would be student grades or even the third column which would be the student ages well that's where the key keyword argument's going to come in this is a keyword argument and we set key equal to a function that's going to return the index of that specific column that we have so let's say key equals grid grade is going to be a function object grade equals and we can easily use a lambda expression for this lambda let's say grades colon grades and we will set an index of one now the first index is zero that's the first column because computers always start with zero column two would have an index of one and then column three would have an index of two so grade equals lambda grids colon grids index one you can also rename these if you want so students dot sort we're setting the key equal to grade and grade is a function object via a lambda function and now all of these students will be sorted by their grades starting with sandy then spongebob mr krabs patrick then squidward if this needs to be in reverse order we can pass in that other keyword argument of reverse equals true and for practice if you wanted to sort all of this data by each student's age then we would change grade to let's say age age equals lambda we'll change grades to maybe ages colon ages and the index would then be two because the first column here is zero then one then two and change key to our function object of edge now each student is sorted numerically beginning with the smallest edge well the youngest person starting with spongebob sandy patrick squidward then mr krabs and like i said before if you want your data arranged in reverse order you can set that keyword argument of reverse to true within the sort method and all of our student data is sorted beginning with the eldest student which is mr krabs then squidward patrick sandy and then spongebob and for the last part of this video let's say that we're working with some other iterable let's say we have a tuple of tuples instead well we can no longer use this sort method because that only belongs to lists you can also use the sort function with lists and it will generate a new sorted list without changing the placement of the original so let's say we have a tuple of tuples and this will create a new sorted list let's call this list sorted students equals then we'll use the sorted function we need to pass in an iterable and we can pass in both a key and or the reverse keyword argument so the iterable would be students and let's set the key equal to edge and i will not reverse it we can keep it as it is but let's change for i in students to sorted students and that's how to use the sorted function to sort an iterable including a list well all right everyone that's how to sort iterables in python if you would like a copy of all this code i will post all of this to the comments section down below but yeah that's a basic way to sort iterables in python hey what's going on everybody it's your bro hope you're doing well in today's video i'm going to show you all how the map function works in python so sit back relax and enjoy the show what up everybody let's discuss the map function the map function will apply a function to each item in an interval that would include lists tuples things like that and the map function accepts two arguments are iterable as well as the function we would like to apply to each item within our iterable for example let's say that we have an online store to represent this i have a list of tuples named store each tuple within this list corresponds to an item for sale within our store there's shirts pants jackets and socks and each item has a price in us dollars let's say now what i would like to do is to convert all of the prices within my store to euros and currently the conversion rate as of the filming of this video is one us dollar to 0.82 euros so let's begin we can easily convert dollars to euros with a lambda function so let's say two euros equals lambda the parameter will be data colon and the next part's a little bit tricky within a set of parenthesis to represent a tuple we'll take data at index 0 that corresponds to the first column comma data at index 1. this represents the index of our prices we're going to take data at index 1 times 0.82 and that's it the first column will be left untouched but the data in column 1 will be multiplied by 0.82 now our map function is going to create a map object but we can easily cast that to a different type of iterable so let's say that store underscore euros equals map parenthesis and then we can pass in our function as well as our iterable our function is our two euros function comma and our iterable is our store and that is it now if you want to convert this map object to an iterable you can easily surround this with a cast i would like to convert this map object to a list and we will now have a new store named store euros which will have all of the different prices of our store in euros and to display this i'll use a for loop for i in store euros print i and let's try it yep that seems about right all of the prices in our store are now in euros let's pretend that these prices are already in euros and we would like to convert these to american dollars so we will use the same conversion rate but divide by 0.82 so let's create a separate lambda function two dollars equals i think i'll just copy this but we are going to divide the first index of data by 0.82 and let's say store dollars to represent our store in dollars because we're pretending now that it's currently in euros and we will display 4i in store dollars so if all of these prices are in euros we are now converting them to american dollars but you may want to do some rounding as opposed to the nearest descent well everyone that is the map function it applies a function to each item in an iterable those include lists tuples the like you pass in your iterable and your function as an argument to the map function so if you would like a copy of all this code i will post all of this to the comment section down below but yeah that is how the map function works in python what's going on everybody it's you bro hope you're doing well and in today's video i'm going to show you all how the filter function works in python so sit back relax and enjoy the show all right all right let's discuss the filter function the filter function creates a collection of elements from an iterable for which a function returns true now what the heck does that mean let me explain let's say that we have a list of tuples named friends each tuple has the name of a friend as well as their age i just made up some ages for all of these friends what i would like to do is to create a separate list for all the friends that are 18 or older so let's say that we're all going out drinking and i would like to create a list of my drinking buddies because they're of drinking age i'm in the united states and the drinking age is currently 21 but i think worldwide is 18 so let's go with 18 for this example since i have a worldwide audience all right now with this filter function we have to pass in our iterable as well as a function to get anybody's edge that is over 18. so let's begin by writing a lambda function for this expression here our filter function so let's say age equals lambda data will be the parameter colon data at index one so the first index the first column in this chart here would be zero for other names the next index of one would be all the ages data at index one is greater than or equal to eighteen and that is it that is our lambda function and now we're going to filter our iterable by this function of age so let's write filter pass in our function which is edge comma and our iterable friends now this filter function will return a filter object you can easily cast this i would like to cast my friends list back into a list and i will assign this to a new list let's say drinking buddies equals list filter age and friends and i should be able to print all of the friends that are 18 or older for i in drinking bodies print i and we have rachel monica chandler and ross well everyone that is the filter function it creates a collection of elements from an iterable for which a function returns true i like to think of it as the search results we're searching for any results that meet this criteria where age is greater than or equal to 18 and then you can create a separate collection or other list if you want from the results but yeah that is how the filter function works in python yo what's going on everybody it's bro hope you're doing well and in today's video i'm going to show you how the reduce function works in python so sit back relax and enjoy the show well i suppose we're on the reduce function today the reduce function applies a function of our choosing to an iterable and reduces that iterable to a single cumulative value the way this works is that the reduce function performs our function on the first two elements of our iterable and repeats the process until only one value remains i kind of like to think of it like we're recycling elements within an iterable until a single value remains our finished product so how is this useful let's say that we're playing a game scramble and we have a bunch of different letters within an iterable a list is a type of iterable so i have a list named letters and we have all of the letters we need to spell the word what i would like to do is to reduce all of these individual elements into a single cumulative value until only one value remains so we can do that using the reduce function you can also do this with the for loop too there's multiple ways of doing this so using the reduce function we're going to import func tools and now let's say we have our cumulative value stored within a variable named word word equals func tools dot reduce now the reduce function has two arguments the function we would like to apply to the first two elements and then our iterable the interval is easy that is just letters so let's put that in letters and for the function we can easily write a lambda function for this lambda and now this function needs two parameters let's say x and y now what kind of function do we want to perform on the first two elements of our iterable let's combine them together so let's say x plus y and now let's print our single cumulative value of word so this should print the word hello i'm fairly confident that the word hello is worth like 20 points in scrabble now let me explain what happened step by step our reduce function applies our function to the first two elements within our iterable it performs this expression that we set x plus y but really we can write anything here so we perform this expression on the first two elements then we repeat the process again using the result from the first time we use this expression and the next element so we're combining x plus y again and then we're just going to repeat this process until only one value remains it's kind of like we're recycling all of these letters and creating a finished product out of all of these that's how i think of it at least here's a different example let's say that i would like to find the factorial of 5 so i have the numbers 5 through 1 within a list named factorial so if i was to find the factorial of 5 via the reduce function i would probably write something like this so let me change word to let's say result result equals functools reduce now our lambda function will be x times y because with factorials we multiply the next two numbers together then we take that result and then multiply the next one in this list so the iterable will be factorial and let's print what our result is so the factorial of 5 should be 120. now let's walk through this we're taking the first two elements of this iterable five and four multiplying together in this case in the last example we concatenated the strings together of x and y in this example we're multiplying them together so we take the first two elements 5 times 4 we take the result and apply it to the next iteration of x times y again so 20 times 3 is 60. we repeat this process again 60 times 2 is 120 and 120 times 1 is 120 so that's kind of how the reduce function works it applies a function of our choosing to the first two elements of an iterable and repeats that process until only a single cumulative value remains so that is the reduce function if you would like a copy of all this code i will post all of this to the comment section down below but yeah that is how the reduce function works in python hey what's going on everybody it's your bro hope you're doing well and in this video i'm going to show you all how list comprehensions work in python so sit back relax and enjoy the show all right everybody so list comprehensions a list comprehension is a way to create a new list with less syntax you can also use a list comprehension to mimic certain lambda functions such as in the previous videos where we use the map and the filter functions and not only that but a list comprehension is easier to read than a lambda function but there is a formula that we're going to follow when we create our list within our list we're going to write an expression for item in iterable now let me give you an example of where a list comprehension would be useful let's take this program that will create a list of all the numbers 1 through 10 squared so if i were to print this we'll get the numbers 1 through 10 whatever their square is right so we have 1 through 10 and the square of 10 is 100 so we wrote this program in three lines of code we're creating an empty list we're creating a for loop and then we're writing an expression for what we want each loop iteration to do now let's write the same program but used a list comprehension and we can write the same program with less syntax so i would write something like this and we're going to follow this formula so our list is going to be named squares equals then within a set of straight brackets we're going to write our expression which is this portion i times i for item so that would be 4i in our iterable that would be range 1 through 11 because remember 11's exclusive and then let's print our squares print squares and there you go we made the exact same program using a list comprehension so basically speaking you just follow this formula you set your list equal to your expression and our expression for this example is i times i for item for i in your interval in range one through eleven so this took three lines of code well if you exclude us printing our list and this program took one line of code now we can also use a list comprehension to mimic certain lambda functions i wrote a program where we will be filtering a list of student grades let's pretend that all of these students took some sort of exam so we have one student that received a 100 90 80 70 60 50 40 30 and then one student got a zero because they didn't show up so what i would like to do is to filter all of these student grades into a list that only contains students that passed and the criteria for a passing grade will be a 60 or above so i would like to filter all passing students and if i was to write this program using the filter function i would probably write something like this so i need a function and then my list that i'm working with lambda x colon x is greater than or equal to 60 will filter all of the results and then convert it to a list named past students so the result will look something like this i have five student grades in here with 100 90 80 70 and 60. now let's write the same program using a list comprehension now there's just one portion to this formula for list comprehension that we're going to add at the end we're going to add if conditional we can check some sort of condition after each iteration so let's write the same program using a list comprehension following this new updated formula that we have so we need our list which will be named past students equals first comes our expression and it's just i for this example for item i in our iterable of students and then if we can check our conditional if i is greater than or equal to 60 and this will have the same effect as our previous program but instead it uses a list comprehension now if your program has multiple output if you need an else statement within your conditional you're actually going to move this portion of the if conditional within our formula to right after the expression so let's write an if else statement here so let's say that instead of just excluding any student that didn't pass we'll replace their grade with the word failed and we can do that using an if else statement so let's do this again i'm going to copy what we have here paste it and we'll move our conditional from the end to just after the expression portion i if i is greater than or equal to 60 and you can see here that we need to add an else statement else will return the word failed so we're replacing each instance of a failing grade with the word failed instead so if your condition returns whatever i is you can just add that to the end if you need an if else statement you're going to add it right after the expression so everybody in conclusion a list comprehension is a way to create a new list with less syntax you can even mimic certain lambda functions which we did with the filter function and it has the added benefit of being easier to read than a lambda function so you just follow one of these formulas depending on what you're trying to do so you need at least list equals your expression for item and your interval if you have a condition that you want to check you just add that to the end of your list comprehension if you have an if else statement then you'll add that to right after the expression so you just follow one of these formulas depending on how you want to write your program so that is a list comprehension if you would like a copy of this code i will post all of this to the comments section down below and well yeah that's how list comprehensions work in python yo what's going on everybody it's bro hope you're doing well and in this video i'm going to explain dictionary comprehensions in python so sit back relax and enjoy the show okay people dictionary comprehensions they're very similar to list comprehensions except they're with dictionaries that's it video over okay but seriously a dictionary comprehension is a way to create dictionaries using an expression and they can replace for loops and certain lambda functions and all we have to do is follow this formula dictionary equals key colon our expression for key value in iterable so let's go over a few examples our first example we're going to take this dictionary named cities in f f is short for fahrenheit i have different city names as keys and relative temperatures as values in fahrenheit so new york is 32 degrees fahrenheit boston is 75. los angeles is 100 and chicago is 50. and what we'll be doing is creating a separate dictionary where all of these temperatures will be in celsius using a dictionary comprehension so let's follow this formula let's create a new name for this dictionary let's say cities in c short for celsius equals and we will follow this pattern first our key golden then our expression we'll go back to this in just a moment for key comma value in our iterable of cities in f and since we're working with a dictionary we're going to use the items method now we just need to fill in this expression there is a formula to convert fahrenheit to celsius and it should be on the screen right about now so let's follow this formula so we'll take our value minus 32 and just for good measure i'm going to put these within parentheses and we will multiply all of this by 5 divided by 9 and that is it so we have our key our expression to convert fahrenheit to celsius for key value in our iterable of cities in f our previous dictionary and let's test this by printing our new dictionary cities in c actually i think i'm going to round these numbers just so it's more readable so let's round all this there we go so new york and celsius is zero boston is 24. los angeles is 38 and chicago is 10. so we created a new dictionary using a dictionary comprehension now with these dictionary comprehensions you can add an if conditional to the end of this so let's say that we have a separate dictionary of weather like a description of the weather in each city new york is snowing boston is sunny los angeles is sunny and chicago is cloudy let's say that we would like to create a separate dictionary with a dictionary comprehension that only has cities where the weather is sunny so i would write something like this let's say sunny weather will be the name of our dictionary equals and we'll follow this formula and then we just tack on our conditional to the end so it's kind of the same as before really so key colon and we don't really have an expression here so let's just say value then for key comma value in our iterable of weather dot items then our conditional if value sunny because we are only looking for sunny weather and let's print this print our dictionary of sunny weather and let me just make this more readable for you guys and our new dictionary comprehension will create a dictionary of key values where the value is sunny using an if conditional at the end of our dictionary comprehension here's a third example for you well if you have an if else condition you can add that to where the expression is within your dictionary comprehension so i'm going to reuse the previous dictionary for the first example where we have cities and their temperatures as values so we're going to replace each temperature with a description of the weather is it warm or is it cold so let's do that using a dictionary comprehension that contains an if else statement so let's say we have a new dictionary named desk short for description cities it's a brief description of each city's temperature so we follow this formula key then our if else conditional for key value and iterable actually i probably can copy all this just to save some time okay so our iterable will be cities dot items and our conditional is going to be we will return warm if our value is greater than or equal to let's say 40. else cold and we will print our new dictionary of desk cities description of cities so new york is cold because it's 32 that's below 40. boston is warm los angeles is warm and chicago is warm now if your condition gets somewhat complex you can even call a separate function to keep your code more organized so key then we can call a function and pass in a value for key value in iterable so i'm going to again reuse our city names and our temperatures and this time we are going to call a function instead i think i'll reuse this code from the previous example where we have a separate dictionary named desk cities and i'm going to replace this if else statement with a function so let's say we have a function that is named check temp and we will pass in our value and we just need to define this function so let's define that here so let's define check temp and our parameter is our value that we're currently working on within our dictionary value then we'll write if value is greater than or equal to let's say anything above how about 70 will return the word hot then else if let's say 69 greater than or equal to value and then value is greater than or equal to how about 40 then we will return the word warm and lastly else return cold and let me just fix some of the spacing now depending on the temperature that is stored within each value of our dictionary we will call a function that will return one of a few different outputs so it's kind of like we're using the map function the map lambda function so let's print our description of cities and we should get a short description of the temperature in each city after we call the check temperature function and then pass in each value from our dictionary so new york is cold because it's 32 degrees fahrenheit boston is hot because it's above 70. los angeles is hot because it's 100 and then chicago is warm because that is 50 which is between 69 and 40 within our function so that is a dictionary comprehension it's a shortcut where you can create dictionaries using an expression and they can replace for loops and certain lambda functions so if you would like a copy of all this code i will post all of this to the comment section down below and well yeah that's how dictionary comprehensions work in python hey what's going on everybody it's bro hope you're doing well and in today's video i'm going to show you how the zip function works in python so sit back relax and enjoy the show all right ladies and gentlemen welcome back we're talking about the zip function today the zip function will aggregate elements from two or more iterables iterables are those things like lists tuples sets etc and the zip function will create a zip object with paired elements from each iterable stored in a tuple for each element within our zip object here's an example let's say that we have two different types of iterables i have a list of usernames and a few usernames within here are dude bro and mr and i have a tuple of passwords and i have some very secure passwords such as password abc123 and guest what i would like to do is to zip elements from each iterable together so that they're in pairs and each pair is going to be stored as a tuple within a zip object and here's how we can do that let's say that we will create a zip object called users and we will use the zip function the zip function will take a varying amount of iterables we're going to pass in our usernames and passwords and zip them together so let's pass in usernames as well as passwords and now our zip object of users is actually iterable zip objects are iterable so we can use them within a for loop so let's type for i in users and print i and what we get is that we have a zip object of tuples and each tuple is storing each pair of elements from our two iterables now users is a zip object and if you don't believe me let me prove it i'm going to print the type of users and this will print that users is indeed a zip object but you can easily convert this to a different type of iterable by using a cast let's say that we would like to convert our zip object into a list so we'll surround the zip function with a cast to a list and now the data type of users is now a list what we have is a list of tuples and each tuple is storing a pair of elements from our two iterables of usernames and passwords now currently since we're passing in only two different iterables we can easily make this a dictionary so that these are key value pairs so let's cast our zip object as a dictionary and to display all of the elements within our dictionary all the key value pairs we're going to change our for loop to this for key value in users dot and we will use the items method print key comma value actually i think i'm going to separate each of these with a colon just to make it more readable and now when we zip these two intervals together we end up with a dictionary of usernames and passwords and the name of this dictionary is users now you're not limited to just two iterables you can add a third iterable or more so this time let's create a maybe a list a list of last login dates and i'll just call this login date equals and why not make a list and let's make up some dates let's say 1 1 dash 20 21 12-20-21 and 1-3-20 21 okay so let's create a zip object of users and we're going to zip user names passwords and login date and let's iterate over this for i in users print i now we have a tuple for each element and instead of a pair we now have a trio i guess of all of the different elements from each iterable so in conclusion the zip function will aggregate elements from two or more iterables and create a zip object with paired or grouped together elements stored in a tuple for each element within our zip object so that is the zip function if you would like a copy of this code i will post this to the comment section down below and well yeah that's how the zip function works in python hey what's going on everybody it's you bro hope you're doing well and i'm going to explain the purpose of if name equals main in python so sit back relax and enjoy the show during your programming journey you may have encountered this strange statement of if name equals main now what the heck does that mean so with python files also referred to as modules by including this statement it gives our modules some flexibility one a module that has the statement can be run as a standalone program or two this module can be imported and used by other modules if there's some sort of useful functions or other resources within this module to be imported by including the statement of if name equals main we're checking to see if a user is running this module as either a standalone program or they're importing it from another module behind the scenes the python interpreter will set special variables one of which is double underscore name it's a variable and python will assign the name variable a value of main if it's the initial module being run and we can actually test that by printing double underscore name so since this is the initial module being run module one for my example name is going to be assigned a value a string of main now check this out i have two modules what if i were to import module 2 and check the name variable of module 2. let's try it import module two in order to access a variable from another module i need to type the name of the module module two dot and i would like to check the special name variable of module 2 and print it so when you import a module this name variable is going to be assigned the name of the module in this case module 2. this time what if we change the roles around i'm going to copy all of this text and paste it within module two we're going to import from module one we will print that special name variable of this module module 2 and then print the name variable of module 1 which is being imported now when i run this program i'm going to instead run from module 2. now this time that special name variable of module 2 is main and the special name variable of module 1 is module 1 the name of the module so by including a statement such as if name equals main we're checking to see if this module is being run directly or indirectly so let's test it within this statement of if name equals main let's print running this module directly else that must mean that we're running this module indirectly so let's print running other module indirectly okay so i'm going to go to module 1 and run from here running this module directly now let's do the same thing with module two but we need to import module one and let's run for module two running other module indirectly for the time being i'm just going to write pass within our if name equals main as a placeholder and get rid of our if statement so let's say within module 1 there's a useful function or resource we would like to access from module 2. so let's say we have a function named hello and all this will do is print the word hello let's just pretend that it's a useful function not really but let's pretend so in order to use this function from module two i need to import module one then type module one dot and then the name of the function so i'm going to run from module 2 and this will print hello but what if i run this program from module 1. so right now module 1 cannot be run directly as a standalone program so i cannot print the word hello so what i could do is within if name equals main i can call that hello function directly so let's run from module one hello one other thing that you might see too within the if statement if name equals main there might be a call for a main function and you can write the main body of your program within a main function so everybody in conclusion the reason that people may include this statement if name equals main is that it allows our modules to have some flexibility they can be run as a standalone program or they can be imported and used by other modules and this is because the python interpreter sets that special variable of name with a value of main if it's the initial module being run if you would like a copy of my code and my notes i will post all of this to the comment section down below but yeah that's the purpose of if name equals main in python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to show you all a few useful functions related to times and dates using the time module in python so sit back relax and enjoy the show alright everybody so the time module let's begin by importing time and the first thing that i'm going to explain to you while is how we can find our computer's epic also pronounced as epoch so this is a date and time in which your computer thinks time began think of it that way at least so we use our epic as a reference point so to find your computer's epic it's going to vary based on your computer and your operating system so to find your computer's epic type time dot c time and as an argument we will pass in zero now what this method will do is that this method will convert a time expressed in seconds and convert it to a readable string so if i was to pass in 0 and print it well then this will display the date and time which is my epic our reference point so for me my epic is wednesday december 31st 6 p.m 1969 so i've just added a note that the c time method will convert a time expressed in seconds since epic and convert it to a readable string a readable date and time so for practice let's pass in perhaps 1 million seconds and see what date and time that we receive so our c time method will return a date and time one million seconds past this epic here so that would be for me monday january 12th about 7 a.m 1970. our next method is the time method of the time module let's print time dot time method and what this method will do is return the current seconds that have passed since our epic using our computer's clock so the number that i end up with is just over 1.6 billion and this is in seconds so for me 1.6 billion seconds has passed since that date which is my epic i believe it was december 31st 1969 and every time that i rerun this program you can see that the amount of seconds that has passed is actually increasing so that is the time method it will return the current seconds since you're epic using your computer's clock and you know what just for fun let's change the date and time under clock and see what happens so let's change the year to how about the year 2000 change and close so let's see what number we get with the time method now so we get just under 1 billion 948 million seconds have passed and now if you need to retrieve the current date and time well there's one of a few ways in which you could retrieve that but one way is that we can combine both of these methods of the see time method and the time method of the time module so let's print time dot c time and we're going to pass in an amount of seconds into the c time method as an argument so within the c time method we're going to call the time method so the time method will return an amount of seconds since our epic and the c time method will convert that amount of seconds to a readable date and time so the current date and time is saturday january 23rd about 3 p.m 20 21 now there is more than one way to get the current date and time another way is to use the local time method and the local time method will create a time object based on the current time so what i'm going to do is create a variable called time object and i just need to explain a few things about time objects so to best explain this i'm going to print our time object now a time object is also referred to as a struct time object it is made up of different keyword arguments there's a year a month day hour minutes seconds day of the week day of the year and this keyword argument here has something to do with daylight savings time so there's quite a few uses with time objects and one way is that we can format them however we want because right now this time object is not in a readable format so to convert this time object into a readable string we'll need the help of a separate function and that is the strf time function str is short for string f4 format and time well for time i guess so this function needs two arguments a format and a time object so our strf time function will accept a format and a time object as an argument so our format is really just a string of different directives and to best explain these i'm going to head to python's official documentation on the subject so here i am on python's website regarding the time module and underneath this section on the strf time function there are different directives that we can embed within our format string that we pass in as an argument depending on the directive that we add we can display a certain format of our date and time so for example if i was to pass in let's say percent lowercase a then we will display the time object's weekday name and you're not limited to just one directive you can add any combination of directives so if i was to add percent m well we would display the month of our date time object as a number 1 through 12. so there's a bunch of directives here and i'm going to be using some of these so within a string for the format argument i'm going to pass in percent capital b for the name of the month percent d for the day percent y for the year percent h for the hour and to format this i'm going to add a colon to separate hours and minutes percent m for minutes colon percent s for seconds and then we are going to assign all of this to a variable let's say local time and local time will be a string so let's print our local time and the current time is january 23rd 2021 about 3 p.m oh and i almost forgot you can also get the utc time that is the coordinated universal time if you know how that works so if you need that you would just use the gm time method for the utc time coordinated universal time okay next up we have the strp time function and this function will parse a string representation of a time and or date and return a time object so we need to pass in a string representing the date and or time as well as a format string so let's create a time string and this variable is going to be a string representation of a date let's say 20th of april 2020 and what we can do is take this string representation of a time and or date and parse it to a time object so we're going to pass in our time string variable as well as a format string so let's say i would like to parse the day so that would be percent d for day then percent b for name of the month and then comma percent y for year this function will create a time object so let's assign that to a variable time object equals time dot strp time we're passing in our string representation of a time or date as well as a format string and we can print our time object using a print statement however this is going to be in a form that is somewhat difficult to read but you can see at least we have a time object with all of these keywords filled in with anything that we passed in via these format directives that we have now the next function is the asc time function and this function accepts a time object or a tuple representation of a relative time so this time let's create a time tuple and we're going to follow this order we can pass in up to nine values the first value is a year so let's pass in perhaps 2020 a month let's say four a day how about 20 four hours let's say four minutes 20 and seconds maybe zero let me just fix some of the spacing here okay you can also pass in a numbered day of the week um i'm just going to say zero i don't think it's really that important a day of the year zero and negative one or zero for daylight savings time so we created a time tuple and we can pass in a time object or a tuple representation of a time following this formula so let's pass in our time tuple and this will create a time string a string representation of the time that we create and let's print our time string and we should have april 20th about four in the morning the year 2020. so that is asc time it will convert a tuple representation of a time and date or a time object and convert it to a readable string now another option is to use m k time and mk time will take a tuple representation of a time or a time object and convert it to seconds since epic so april 20th of the year 2020 is about 1.5 billion seconds since our epic date and for me that was december 31st the year 1969 so that is a few useful functions of the time module if you would like a copy of this code i will post all this to the comment section down below and well yeah that's the time module in python yo what's going on everybody it's bro hope you're doing well and in this video i'm going to explain multi-threading in python so sit back relax and enjoy the show think of a thread as a flow of execution like a river and each thread can carry out its own separate order of instructions if we use this process of multi-threading we can have our program run different parts of its program at different times they all run concurrently but not truly in parallel that is a concept for later referred to as multi-processing so with reds they each take a turn running to achieve concurrency this is due to a notorious feature known as the gil the global interpreter lock only one thread can be running at one time but they can all take turns when one thread is idle so this allows one thread to hold control of the python interpreter at any one time so they run concurrently but not truly in parallel which is what we do with multi-processing now programs and tasks can be divided into two different categories they can be cpu bound that is a program or a task that spends most of its time waiting for internal events such as a task that is cpu intensive it is better to use multi-processing for tasks that are cpu bound now tasks that are io bound means that the program will spend most of its time waiting for external events such as waiting for user input or if you're doing activities like web scraping you do a lot of sitting around so with i o bound tasks it's better to use multi-threading because we can have multiple threads running concurrently but not truly in parallel like what we do with multi-processing after importing the threading module we can count the number of threads that are currently running in the background whenever we run a program we have one thread that is running that is in charge of executing our program and we can print the active count of threads running in our program using the active count function of the threading module so this will print one we have one thread that is running and we can print a list of all the threads that are running by using the enumerate function so the one thread that is in charge of running our program is referred to as the main thread by using this concept of multi-threading we can have more than one thread running concurrently not truly in parallel all the threads will take turns while one of them is idle so we can have more than one thread running more than just the main thread which is in charge of running the main body of our program so while our main thread is in charge of running the main body of our program we can have another thread that's in charge of a separate part of it maybe like a countdown timer or something so one good example take that quiz game that we made some number of videos ago while we were waiting for user input which is a i o bound task we could have had a countdown timer going like you only have so many seconds to answer this question we could have had one thread in charge of waiting for user input and another thread in charge of the countdown timer so that's an example of multi-threading we had two threads running concurrently and what we'll be doing in this video is creating a program that involves multi-threading we can have different threads in charge of different parts of our program and they can all run concurrently they'll all take turns while one of them is idle so let's say that we're running late for school or work in the morning and we have three different tasks that we need to complete before we can leave for school or work so think of three different things you do in the morning such as maybe eat breakfast some people drink coffee or maybe a beverage of your choice so drink coffee and some people like me they like to do their homework last minute so i'll say study before i leave for work or school in the morning so what we'll do in each of these functions each of these functions should take some amount of time to complete so we can have our main thread sleep for a given number of seconds using the sleep function time dot sleep and let's say that in order for me to eat breakfast this task will take me three seconds let's just pretend that instead of minutes this will be in seconds so drink coffee will take me four seconds and study will take me five seconds then when we finish sleeping let's print a confirmation message let's say you eat breakfast as in you finish eating breakfast with drink coffee you drink coffee and with study you finish studying now each of these tasks are i o bound they're going to be spending a lot of time just waiting around for external events they're waiting for the sleep function to expire before they can finish their task so we're going to have all of these three functions run on our main thread and we'll see how long it takes for us to complete our morning ritual these three tasks so let's call these three functions within our main thread so let's call the eat breakfast function first followed by drink coffee and then study in that order so this program is going to take approximately let's see 12 seconds to complete so there's going to be a pause for a second you eat breakfast then followed by you drank coffee and then study you finished studying so this program took about 12 seconds overall so if this were realistic what we would have done is we would sit down and eat breakfast for three minutes well three seconds in this case and then once we finish eating breakfast only then are we allowed to drink our coffee and once we finish our coffee only then can we study so we completed these tasks sequentially and not concurrently for us to move down to the next function we need to complete the previous functions because we're doing this in order but realistically us human beings we would probably eat breakfast drink coffee and study altogether because we can multitask and we can complete these three functions in less time and that's kind of the same process as multi-threading we can have these three separate functions running concurrently as if we're multitasking we're eating breakfast drinking coffee and studying all at once now currently we have one thread that is in charge of these three separate functions what we could do is that we can create three additional threads each thread will be in charge of each task and then we'll have our main thread running in the background that will complete the rest of the program so this is how to create an additional thread let's say that x equals threading dot thread we need to pass in a target target equals and then the name of the function so let's say thread x will be in charge of eating breakfast and then you can pass in arguments too if your function has parameters by typing args and then you pass in a tuple so let's say you have one argument to pass in you'll type your argument followed by a comma but we don't have any arguments in this example but you'll need to be sure to enter them in if you do have any okay then to begin this thread you type the name of the thread in this case x dot start so we now have an additional thread and this thread is in charge of eating breakfast now let's create another thread to drink coffee and we'll call this y and the target will be drink coffee and lastly we have a thread in charge of studying and this will be z and the target is our study function okay now let's see how long it takes for us to complete our program oh and be sure to comment out these function calls within the main thread because we don't want the main thread in charge of those anymore okay now we can run the program so we have four threads running this time you eat breakfast you drink coffee you finish studying so this program took approximately five seconds to finish and the reason that this program took five seconds instead of 12 is because before our main thread was in charge of running these tasks sequentially in order but now since we have a thread dedicated to each task we can run them all concurrently instead of sequentially so that this program now took about five seconds to complete and you may have noticed too that the activecount function as well as the enumerate function were called before threads 1 2 and 3 finished their respective tasks that's because the main thread is not going to wait around for these three threads to complete it has its own set of instructions to do so it is no longer in charge of these three functions the program is going to handle those three functions to our three threads and our main thread is going to continue its own set of instructions its job is to print the active count as well as call the enumerate function which it did and it finished its tasks before threads one two and three now one trick that you can do too is that you can use the time modules performance counter function and this function will return how long it takes our calling thread as in our main thread to finish its set of instructions so our main thread is not in charge of executing these three functions our main thread is in charge of creating three additional threads and then calling the activecount function and the enumerate function as well as the performance counter function so our main thread will take approximately 0.075 seconds to complete and our three threads are still running in the background our main threads job its order of instructions is to create three additional threads and then immediately print whatever is returned via the activecount function enumerate and then your performance counter so our main thread says that it finished its tasks in about .07 seconds but threads one through three were still trying to catch up that's why the main thread finished before are three additional threads and once all active threads have completed their tasks then your program will finish and exit there's also this concept called thread synchronization we can have a calling thread in this case our main thread wait around for another thread to finish before it can move on with its own instruction set so let's say we would like our main thread to wait around for thread 1 also known as x so we're going to use the join function of thread x and now our main thread has to wait around for thread x also known as thread 1 to finish before it can move on with its instruction set so let's do the same with y and z so now our main thread before it can move on with the rest of the program has to wait for all of these threads to synchronize and join and then and only then can it move on with the rest of its own instruction set so this time our program is going to look a little something like this you eat breakfast you drink coffee you finish studying so by the time we reach our active count these threads are already joined and synchronized they're no longer active when we enumerate over our active threads we only have our main thread and our main thread completed in about 5.1 seconds this time because it did a lot of waiting around it was waiting for threads x y and z to join and finish in conclusion a thread is a flow of execution like a separate order of instructions that a program can follow and when we run a program we always have at least one thread running initially and that is referred to as the main thread however if you have multiple threads using the concept of multi-threading we can have multiple threads running concurrently but not truly in parallel which is what we'll cover during the video on multi-processing this is due to a feature known as the gil the global interpreter lock which allows only one thread to hold control of the python interpreter at any one time and tasks can be either cpu bound or io bound a cpu bound task is a program or task that spends most of its time waiting for internal events such as a task that is cpu intensive and o bound tasks spend most of their time waiting for external events such as waiting around for user input or web scraping with i o bound tasks it's better to use multi-threading with cpu bound tasks it's better to use multi-processing well everybody that is a quick overview of multi-threading i will post all of this code to the comment section down below and well yeah that's how to achieve multi-threading using python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to explain demon threads in python so sit back relax and enjoy the show okay so demon threads also pronounced as daemon threads a demon thread is a thread that runs in the background and they are normally not important for your program in order to run your program will not wait for demon threads to complete before exiting whereas non-demon threads they cannot normally be killed they will stay alive until their task is complete so a few common uses of demon threads would be background tasks garbage collection waiting for input or other long-running processes so here's an example of why demon threads would be useful let's say that we'll have two threads our main thread will be in charge of waiting around for some user input we'll ask do you wish to exit and in the background we'll have a timer going that will display how long somebody is logged in so let's create a function named timer and what we'll do is just display how long somebody's logged in so let's say we have a count variable while true we'll use the sleep function of the time module to sleep for approximately one second then we'll increment our count variable by one and we'll print a message so let's say logged in for count seconds and let's create a thread that will be in charge of this timer and run it in the background so let's say x equals threading dot thread the target will be our function of timer and we need to start this thread x dot start so our thread x will be in charge of our timer and run it concurrently while we're waiting for some user input our main thread will be in charge of waiting for this user input do you wish to exit now here's the issue of us using a non-demon thread for a background task such as a countdown timer so our main thread is in charge of waiting around for some user input and thread x our additional thread is in charge of running this countdown timer so if i wish to exit this program i'm just going to type okay and hit enter well my background timer is still going but my main thread is complete so i would like to exit this program but my program will not exit as long as there are non-demon threads that are still alive we cannot normally close this program unless we do like a brute force you know close and exit of the program so we can turn this thread of x into a demon thread so that when we wish to exit the program when there are no more non-demon threads alive and to change a thread to a demon thread it's actually fairly easy when you create your thread you can set this flag of demon equal to true and that's it so when all non-demon threads have finished their tasks your program will complete and exit but if there are demon tasks running in the background they will be killed automatically so let's try this program again so do you wish to exit my program is going to continue running my demon thread is in charge of the timer and it's going to continue running until all non-daemon threads have completed their tasks so once i type ok my program will finish running and my countdown timer will stop because all demons are killed when your program is finished running there's also two additional methods that you might be interested in you can use the set daemon method of a thread and you can set it to false or true if you would like to change a thread to a non-demon or a demon however if your thread is currently running well you cannot actually change it from a non-demon thread to a demon thread while it's currently running so you would have to do that before you actually use the start function and you can also check to see if a thread is a demon or not by using the is demon method this will return true or false so everybody in conclusion a demon thread is a thread that runs in the background and they're not important for your program in order to continue running your program will not wait for demon threads to complete before exiting the program whereas non-demon threads cannot normally be killed they will stay alive until their task is complete and demon threads are commonly used for background tasks garbage collection waiting around for input or other long running processes so if you would like a copy of this code i will post all of this to the comment section down below but yeah those are demon threads in python yo what's going on everybody it's bro hope you're doing well and in this video i'm going to explain multi-processing in python so sit back relax and enjoy the show what's up let's talk about multi-processing multi-processing is the act of running tasks in parallel on a different cpu cores it's different from multi-threading although it sounds similar because with multi-threading we're limited to running one thread at a time because of the gil that lock which is used for threading we can run threads concurrently but not in parallel however with multi-processing we can create processes and we can run each process in parallel on a different cpu course so with multi-processing it's better for tasks that are cpu bound where you need heavy cpu usage whereas multi-threading that is better for i o bound tasks where you do a lot of waiting around so before we begin i recommend these two imports multi-processing and time let's begin quick note if you're running the windows operating system you'll probably need to add this line if name is equal to main so when we run a program we have a main process that is running and if we create a child process from that process it's going to copy the module that we're currently working with and that child process will create its own children processes and it's going to be a problem so we're going to add this line if name is equal to main so when we create a child process it will copy our module but it's not going to execute it so let's create a main function and a majority of our code is going to be within our main function if you're running a different operating system you probably don't have to do this but if you're running windows you probably will now with multi-processing multi-processing is better for tasks or functions that are cpu bound where they require heavy cpu usage let's say that we have a function named counter and we'll pass in a number to count up to but the number we're going to pass in is a ridiculously large number like a billion so let's create a function that will count from zero so count equals zero and while count is less than our number that we pass in we will increment our counter by one so that is the function that we'll call with our processes that we create now within our main function we'll create a process and to do that you'll need the multi-processing module so import process and cpu account and we'll save this for a little bit later to create a process let's say we have process a a equals process this step is very similar to creating a thread we have a target our target will be our function of counter and if we have arguments we will pass those in so remember with our arguments we have to pass in a tuple since we only have one argument to pass in to differentiate this from an expression we have to add a comma at the end so our number let's say is 1 billion so that's a million 10 million 100 million 1 billion let me just verify that okay so that's 1 billion we're going to count from zero to a billion and in order to start this process a my process use the start function and then i will use some process synchronization by using the join function my main process is going to wait around for my child process of a to finish before continuing and let's print our performance counter so we'll print finished in let's say time dot performance counter seconds okay so let's see how long it'll take to count from zero to a billion using one process i fast forwarded this video but it took my program 56.7 seconds to count from zero to a billion but we can speed this up by using multi-processing let's create a second process named b and i'm going to divide the amount of work in half so each process will count to 500 million half of a billion so let's change a to b and i'm gonna group these start functions together just so it's easier to read and then b dot join just to synchronize everything okay and then let's change 1 billion to 500 million for each it's the same amount of work but divided among workers so that is 500 million let's see how well it runs this time so it took my program about 40.3 seconds to finish counting from zero to a billion but i divided that task among different processes each of my two processes counted from zero to 500 million this time so this time let's create four processes so we have a b c and d and we'll need to start them and i'm going to join them now this might not actually speed it up for you and i'll explain why later it depends on the amount of cpu cores that you have okay so oh let's change this to so 250 million for each okay see you in a couple seconds okay welcome back so on my computer when i ran four processes and each was counting up to 250 million i could finish my program in 27.3 seconds now for me if i created more processes than this it would probably take longer and here's why so you can print the cpu count of your computer using this function of cpu count so if i were to print whatever this function returns i can get the count of the number of additional processes that i can run for the time being i'm just going to comment out this start function because i just want to print whatever this value is so my cpu count on my computer is four so i can run four additional processes but let's attempt to run eight processes so i'm going to copy all these and let's say that we have e f g and h and we will start all of those two so give me a second just to start them so a b c d e f g h and then i'm going to join all of them e f g and h okay so let's run this now oh and change the arguments to i keep forgetting to do that so let's say 125 for each so 125 million times eight is one billion okay see you in a bit all right welcome back this time when i had eight processes working it actually took me longer than when i had four processes working when i had four processes working it took me about 27 seconds this time it took 30 seconds when i had eight processes working that's because i had more processes than my cpu count and that's partially because whenever you create a process there's significant overhead with beginning and destroying a process and if i can only run four processes on my computer at one time well then i'm creating additional processes to no extra benefit it's actually hindering the performance of the computer because i'm creating all of these additional processes when it really doesn't help me in conclusion multi-processing is the concept of running tasks in parallel on different cpu cores it's similar but different from multi-threading because with multi-threading we can run tasks concurrently but they're all taking turns because of the gil with multi-processing we can run all of these different tasks together in parallel multi-processing is better for cpu bound tasks where a task has heavy cpu usage and multi-threading is better for i o bound tasks tasks that involve a lot of waiting around so that's multi-processing if you would like a copy of all this code i will post all of this to the comment section down below but yeah that is how multi-processing works in python hey what's going on everybody two bro here hope you're doing well and in this video we're going to be creating our very first graphical user interface in python so sit back relax and enjoy the show welcome one and all today we'll be creating our very first graphical user interface in python also known as a gui for short we're going to be using the tk inter gui which is a module that is included with python our first step in order to use tk enter is to import this module so that we can begin using it our first line of code will be from tk enter import asterisk this will import everything related to the tk inter module and with this import we can now use all of the gui features that this module has to offer now there is one important distinction that we need to make we need to discuss the differences between windows and widgets here's a few quick definitions that i definitely did not copy from the internet widgets are gui elements such as buttons text boxes labels images you name it and windows they serve as a container to hold or contain these widgets for this topic we'll be creating and customizing our own window and in future topics we'll be exploring different widgets that are available to us so let's begin by creating a simple window and we should give our window a unique name such as window that's pretty creative and in order to instantiate this window we're going to follow this window name with equals tk make sure you get the capitalization right this is a uppercase t and a set of parentheses to serve as the constructor what this will do and i'm just going to add a comment is instantiate an instance of a window for us and when we compile and run this nothing appears to happen that's because we only instantiated our window and we're not actually displaying it in order to display our window we're going to follow this with the name of the window dot main loop and this will display our window and this is our first graphical user interface and we'll be adding widgets to this window so i'm going to add a comment that this will place window on computer screen and it will also listen for events but we'll get to that in future videos now what we'll be doing is customizing the appearance of this window let's begin by changing the size and we can do that with the geometry function so we're going to first begin by typing the name of our window which is window follow this by using the geometry function and we pass in a width and a height but make sure this is within quotes and set this to whatever width and height that you want so if i want 420 by 420 that would be 420 x 420 and the size of our window is now the size that we set with the geometry function now take a look at the top left of this window we have this feather icon as well as a title of tk that's kind of lame so let's change that let's first change the window title and there is a function to do that so we type in the name of our window window dot title function and we can pass in a new title that we want to set and i will set the title to be maybe bro code first gui program that'll work and we now changed the title of this window and it says bro code first gui program the next thing that we can do although not necessary is that we can change the icon of our window bar at the top i would like to replace this feather icon with an image of my choosing here's my desktop don't mind all of the clutter and i would like to use this image of the logo for my channel and set this as the icon for my window so what i'm going to do is copy and then go to my project folder and then paste it click ok and i now have this image within my project folder but it's in a format that we cannot use currently we need to convert this to what's called a photo image that is a format that tk enter can use so we'll need to convert our image to a photo image so do that anywhere within the window between window equals tk and window.main loop right here is good i suppose we're going to create a photo image from this image and this is a png file but yours might be something different so let's give our photo image a unique name like maybe icon and in order to create a photo image we'll follow this with equals photo image and within the constructor of our photo image there is an option for file we can either list the file name or the file path if it's somewhere else on your computer since this image is within my same project folder i only have to list the file name and this is called logo.png and this is probably going to be named something else for you though so we now have this photo image called icon that we can use and i need to set the icon of my window to this icon and luckily there is a function to take care of that for us type in the name of the window which is window dot and we're going to use the icon photo function there are two arguments the first we're going to set to true and the second is the photo image that we want to use and this photo image is called icon so we're going to pass this photo image as an argument to this function of icon photo and now when we compile and run this the image that we wanted to use is now set for the top left icon of this window bar however it loses a lot of the quality since the dimensions are so small but you can still tell that it's my logo though so that's how to replace the icon of your window bar in the top left corner now let's change the background color of this window and one way in which we can do that is to use the config function you can use the config function anytime that you want to make any changes to this window so let's change the background color here and there is an option called background and we can set this equal to either a color name or a hexadecimal value let's begin with just some color names let's say that i want the background color to be black i'll just type in the word black here and this will change the background color of my window to black alternatively you can set a hex value as the color so if you were to look up or google hex color picker you can select whatever color you want let's say that i want a sky blue color like this well this is the hex value i'm going to copy this value and then paste it within the option for my background make sure you have this hashtag as well because that represents that this is a hex value so now the background color is that sky blue color that i picked well everybody that's the basics of creating a window in python and in future videos we're going to be exploring different widgets that we can add to this window that have some functionality so if you would like a copy of all this code i'll post all of this in the comments down below but yeah that's how to create your very first gui in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create labels in python so sit back relax and enjoy the show what is a label well i'm glad you asked that question it's an area widget that holds text and or an image within a window so to begin we'll need to create a window to act as a container to hold this label we can create a window with window equals tk followed by window.mainloop and this will give us a window in which we can add a label to now let's give our label a unique name such as label and in order to instantiate a label we'll follow this label name with equals label with a capital l and a set of parentheses the parentheses are acting as the constructor for this widget our label and we can pass in arguments into these parentheses the first argument that we're going to pass in is a master the container for this label we're going to pass in the name of our window because our window is acting as the container with widgets in python we can de-eliminate the arguments that we're passing in with a comma and there are options available to us options are keyword arguments that we can pass in to the constructor for this widget one option available to us is text and we can set the text of this label equal to a string that we set so let's say that we want this label to say hello world well we're going to pass in this option text and it's a keyword argument so if we were to do this we're going to set the text of the label but this label currently doesn't appear within our window what gives bro i thought you knew how to code hold up wait a minute there's one more thing that we need to do so we're going to actually add this label to the window now we set the master of the label to be our window but now we actually have to add it as step two one way which we can do that is to use a pack function of our label so follow label equals label and pass in all of your arguments and then follow this with the name of the label dot pack so with the pack option by default this will place our widget in the top center of our window another way in which we can add a label to a container or window is to use the place function and we can set some coordinates of where we want this label or other widget to appear within the window if we want this to appear in the top left corner we can set x to equal zero and y t equals zero and these are options available to us too that we can pass in so this place function will place our label at some position or some set of coordinates within the window and with x equals 0 and y equals 0 that will place our widget in the top left corner of the window and if i were to change these to let's say x equals 100 and y equals 100 well this is going to be placed down by 100 pixels and to the right by 100 pixels so you can use pack or place there's a few others like grid but they're a little more complex so we'll get to that in a future video for the time being i'm going to use the pack function of the label and turn this place function into a comment dot pack all right now how can we customize this label we can pass in different options when we instantiate this label let's change the font and that's another option we can change the font with font equals and then we can pass in a font let's begin with a font family i will say maybe ariel a size perhaps 40 and then a style if you so choose like bold there's also italic and underline uh but this will work just fine then so this will change the font of the text of our label and it says hello world still now let's change the foreground color so that is another option the foreground is the font color and the option is fg for foreground it's short for foreground foreground equals we can state a color name such as green and our text should now be green you can select something more specific by passing in a hex value so a custom color that i like is hashtag zero zero ff00 this is bright green you can always look up what different hex values are and we can also change the background color too that is bg short for background color and we can pass in a color name or a hex value i'm just going to set this to black just to demonstrate that we can pass in both either hex values or color names and what we have is green text on a black background and this is the limits of our label within the window because when we expand this window the label is still going to stay the same size if we were to change the text within the label our label is only going to take up the room that it needs and you can see that our label is now smaller now we have all of these arguments within our constructor and it's getting a little bit difficult to actually read so i'm going to separate each of these arguments line by line just so that this is more organized but it'll work just the same as it did before now how do we add a border around our label one we can set the border style with the relief option and one border that i like is raised but right now the border width is one so it's a little difficult for us to actually see the border let's increase the border width with the option bd and i'll set this equal to maybe 10. so this border is now more visible another relief which is the border style is sunken and this will give our label a sunken appearance but i think i'll change this back to raised we can also add some padding around the text between the text and the border we can pad x and pad y pad x will add some padding some space between the x-axis of our text between the border so let's set this to maybe 20 and we now have 20 pixels worth of space between the text and the border let's also pad y this will add some space above and below our text between the text and the border now how do we add an image to a label we first need to create what's called a photo image and we will create this within the lines of window equals tk and window.main loop and let's give this photo image a unique name like photo and in order to create a photo image we're going to follow this with photo equals photo image and within the constructor of our photo image there's an option called file and we can list a file path or a file name right now on my desktop there is a image that i want to use and i need to convert this to a photo image here's my desktop and this is an image that i want to use to add to my label i need to get the file path and i can get that by going to properties then underneath location i can copy this location address and paste it within the quotes for file and then i need to add the image name and this is person.png and with these backslashes these need to be double backslashes because that is the escape character for a backslash but what would be a better option is to add this image to my project folder that contains the python file that i'm working with so in place of listing the entire file path i'm going to copy the image that i want to use go to my project folder and then paste it and i no longer need this entire file path i can just list the image name that i have and now what we need to do is add this photo to the label and there's an option to do so that is the image option and we'll place this within the constructor for the label we're going to set image equal to the photo image that we have and our photo image is called photo this will add our photo image to our label or other widget depending on what we're working with so we have our image but it replaced all of the text that we had for this label how do we add both text and an image to a window well we can follow this with the compound option we can set a direction of where we want this image to be placed relative to the text that we have so i'm going to set compound equal to bottom so that the image appears on the bottom or underneath our text so we can both have text and an image or if i want this to be in a different location i could set this to maybe top left or right if i were to set this to top we have our image on top of our text and one thing to know about labels and many other widgets in python is that the size of the widget will actually increase to accommodate the size of all the components that's contained within if i were to give the text a longer string of characters such as bro do you even code then the width of our label is actually going to expand to accommodate the size of the longer string of text that we have so that's the basics of labels everyone if you would like a copy of all this code i will post all of this in the comments down below but yeah that's the basics of labels in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create buttons in python so sit back relax and enjoy the show buttons you click them and then they do stuff that's pretty much it so this is how to create a button in python we'll need a window window equals tk followed by window.main loop let's call our button just button and in order to create this we'll follow this with equals button and within the constructor for this button we're going to list what we want to add this button to what is the master the master is the window and in order to display this button we're going to follow this with button dot pack and we should have a small rectangular button within our window but it doesn't display any text nor does it do anything so let's add some text and there is an option to do that within the constructor we're going to list the option for text and set this to whatever text you want to display let's say click me and then when we run this our button now says the text that we set and it says click me however it currently doesn't do anything though we need to set a command that is another option command equals and we list a function name this is what's known as a callback so let's create a function called click and then outside of the window let's define what our click function does def click and let's print a message you clicked the button now with the command we're going to list the function name without the parentheses so make sure you're writing it as this and not that this is what's known as a callback so when we click on this button it's going to perform our callback and perform whatever is within our function click just like that let's customize the appearance of this button i'm going to change the font that is another option font equals and let's pick a professional font such as comic sans it's very professional and i'll set a size of 30. and now you can actually read what's on this button it's large enough let's set the foreground color that is the font color fg you can place a color name or a hex value here i'll pick green that is 0 0 ff00 and our text should now be green which it is let's also change the background color that is bg i will pick the color name of black and now we have green text on a black background notice that when i click on this button or hold my mouse button down the color scheme has changed that's because there is a different active foreground and active background and we can change those too so that this won't flash every time you click on the button so let's change the active foreground and active background those are other options active foreground and i'll set this to the same color as my foreground which is green so the text color is going to stay the same and i'll also change the active background and i will also set this to black to match my background and then this should no longer flash when we click on our button if you need to disable somebody from clicking on this button there is an option to do so and that option is the state option and normally this is active but you can set this to disabled and we can no longer click on this button and you can see that the color scheme has changed too it's all grayed out and whatnot so i'm going to replace this back with active because we still have a few more things to do now how do we add an image to a button there is an image option and we set this equal to a photo image but first we need to create a photo image i have this photo of a like button a thumbs up that i want to use i need to create a photo image from this image file so within the window let's call this photo image just photo photo equals photo image then i'm going to list the file path or the file name since this image is within my same project folder i only have to list the file name and this is called like.png but if you use your own image it's probably going to be named something else then i need to set the image equal to my photo image which i named photo but the photo replaces the text on this button but it still works the same so we would like to display some text as well as our image we need to use the compound option and we list a direction we can list top bottom left right we want this image to be on the perhaps bottom so let's list the bottom and now when we run this we have our text as well as our image and if we changed compound to a different direction like top then the image is going to be displayed on the top relative to the text what if we wanted to count the amount of times that we clicked this button we could create a variable called count and we'll set this equal to zero but in order for us to access this count variable within the function of click we're going to list count as global so that this is a global variable every time we click this button let's increment our variable count by one by saying count plus equals one and then we will print whatever the value of count is so within a print statement we'll just say count now when we click on this button we have access to our count variable that's outside of this function and every time we click on this button it's going to increase our count variable by one well everybody that's the basics of creating buttons in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of buttons in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create a simple entry box in python so sit back relax and enjoy the show if you find this video helpful please remember to like comment and subscribe your support will help keep this channel running alright my fellow bros in this video we're going to be discussing the entry widget this is a text box that accepts a single line of user input as always we'll need a window window equals tk followed by window.main loop and let's give our entry box a unique name let's call this entry for short and then to create this entry widget we're going to follow this with equals entry and within the constructor we have to state what we're adding this to we're going to add this to our window and we should finish this by packing it or placing it entry dot pack and we should have an entry box within our window however the text is somewhat small so let's change that we can set this as an option within the constructor of our entry box so let's set the font font equals and pick whatever font you want i'm going to pick maybe ariel and then a size it'd be 50. and this should be a little bit larger and we can type in some text like this cool right now we should add a submit button because right now this currently doesn't do anything if we type some text in so let's create a button i'm going to create this button maybe after the entry box and let's say that this is a submit button so let's call this submit button equals button what are we adding this to writing the square window and we'll set some text text equals submit we'll also need a command for this button command equals and we'll create a function called submit and we want to pack the submit button to add it to the window submit button.pack all right now let's put our entry box on the left hand side and our submit button on the right hand side when you pack these widgets you can set these on a certain side side equals left and our submit button we want this on the right not necessary but i think it looks better and we also need to define our submit function outside of the window let's define what this does def submit what's this going to do we need to get the current value that's within our entry box one way in which we can do that is use the entry boxes get function this will return a string and we can do something with that string such as store this within a variable so let's create a variable called maybe username let's pretend we're having a user submit their username to login to something i suppose so we'll get the current value of the entry box store that within a variable and we'll call this username and then we will maybe print this for fun print hello plus user name and let's try this so here's our entry box here and our submit button i'm just going to make up something click submit and it displays our message hello ergo gerger gerger i didn't say that this video was going to be professional let's add a few other buttons let's say we want a delete button as well as a backspace button so let's copy what we have for our submit button and create a delete button and then a backspace button the delete button is a little bit easier to code so let's rename our submit button as delete button make sure to change the name to when you pack this and the text we will say delete and we'll create a function called delete and let's define what delete does so after our submit function let's define our delete function and we need to delete all of the text within our entry box one way in which we can do that is to type in the name of our entry box dot delete function and this takes two positional arguments which portion of our entry box do we want to delete so we want the very first character that is index 0 followed by the last character and we can say end so this will delete all of the characters within our entry box and let's try it so i'm just going to type in my name bro i'm going to delete this and all of the text is now gone just like that let's create a backspace button we'll copy what we have for our delete button and change the word delete to backspace make sure you change that when you pack this as well and for the text we'll set this to backspace and we'll create a function called backspace and let's define what backspace does so after our delete function let's define back space and this is going to do something very similar to our delete function except we're going to change the first positional argument we need to place the second to last character within this positional argument one way in which we can do that is to first get the entire length of all of the characters within our entry box so let's begin by typing entry dot get and we need to determine the length of this and we can surround this by placing this within the length function so this will return the current length of all of the characters within our entry box and then we're going to add -1 so that this first positional argument is the second to last character and the second positional argument is the end the last character and then when we run this let's type in our name i'm just going to type in draw code this time i'm going to click backspace and then it's only going to delete the last character and then if you were to click delete it deletes everything broy and then if you click submit it's going to submit your name all right let's customize the appearance of this entry box so within the constructor for this entry box let's change maybe the color maybe the background color and foreground color let's begin with the foreground color you can pass in a color name or a hex value i want this to be green so the hex value for that is zero zero f zero ff00 and the foreground color of the text when we type it in is now green and we can also change the background color that is bg we could pass in a color name or a hex value i'm just going to say black to keep it simple and we now have a black background and the text color is now green here's a few useful features that you might be interested in let's insert some default text for our entry box so we can use the insert function entry dot insert we place a positional argument as well as some text so for the positional argument let's say zero so that's the very beginning index zero and let's set the text to maybe spongebob and then the default text within our entry box is now spongebob another option available to us is that we can set the state of this entry box we can set this to active or disabled let's say that after somebody submits our name we want to disable this entry box so we can either pass in this option within our constructor or we can use the config function to make any changes to the state of our entry box so let's say after we submit our username we want to disable this entry box so let's type in the name of our entry box dot config and for the option for state let's set this to disabled and then once we type in a name and then click submit our entry box is now disabled there's also an option called show where you can show a certain character in place of the normal text on the screen so this would be useful for a password let's say that we're typing in a password but we don't want to display the password on the screen we can use the show option to show a certain character in place of our text so you might see bullets or an asterisk so let's pretend that we're now typing in a password so we're going to set the option for show and place a character that we want to replace each character with let's say we want to only display asterisks when we type in some characters and i'm going to type in the word password but it's only displaying asterisks now but if i were to click submit it displays our text and i would say plain text instead of our hidden text because we're only showing whatever character that we set so that's an option available to you as well well everybody that's how to create an entry box in python you can submit information such as a username for example or even a password if you set the show option available to you if you want a copy of all this code i'll post all of this in the comments down below but yeah that's some of the uses of the entry widget in python hey how's it going everybody two bro here hope you're doing well and in this video i'm going to teach you guys how we can create and customize our own check buttons in python so sit back relax and enjoy the show all right my fellow bros in this video we're going to be creating and customizing our own check buttons in python i sometimes refer to these as check boxes so in case i do that's what i'm referring to as always we'll need a window window equals tk followed by window.main loop and let's call this button just check button and in order to create this check button we type in the name of the check button equals check button and within the constructor what are we adding this check button to we're adding this to our window and also within the constructor we can set the different options for how we want to customize this check button let's begin with the text text equals i agree to something and last but not least we need to add this check button to the window one way in which we can do that is to use the pack function of this widget so follow this with check button dot pack when we run this we have our check button within our window and we can toggle this on or off right now i'm agreeing to something i'm not sure what i'm agreeing to but hopefully it's not anything bad now currently this doesn't do anything so we'll need to associate a variable with this check button so we'll add that as an option variable equals and let's create a variable called x and we'll need to define this within the window so after we create our instance of our window let's say x equals now with check buttons they store a 1 or a 0 by default within our variable our variable that we call x so with x we're going to set this equal to a int var if this were to return a string we would say string bar but normally by default this returns a one or a zero and we can actually change that using the on value and off value options so the on value is what's going to be stored within our variable if it's toggled on so by default this is one and the off value is the opposite this is what is stored within our variable if this is toggled off alright now let's have some fun with this so let's associate a command with this check button command equals and let's create a function called maybe display and then let's define this before the window def display and we're going to check the value of x to see if it's one or zero so within our display function we're going to check to see if x and to get the value of x we're going to use the get function so if x dot get is equal to one that means that somebody clicked on the check box or toggled it on so if they check the check box or check the check button then they agree so print you agree if it's zero and we can do this with an else statement else print you don't agree frowny face and let's test this theory so we have our check button when we click on this it's actually going to call our display function i agree to something and it says within our console window you agree and if i were to toggle this off it says you don't agree let's change the font of our check button so we'll add that as an option font equals and we can pass in a font that we want i'll say maybe ariel and then a size of 20 and now this should be readable i agree to something let's also color this because well i like coloring let's begin with the foreground color so that is fg for short fg equals and then we can pass in a color name or a hex value i like hex values so i'm going to stick with those i want a green foreground color so that is zero zero f zero zero but feel free to adjust these values however you want so our text should now be green that is a very bright green and it hurts my eyes so i'm also going to change the background color which is bg and i'm going to set this to black so we'll have green text on a black background okay now when you click on this it flashes that's kind of annoying that's the active foreground and active background if we click on this or hold this down the color scheme switches to our active foreground slash background and we can change those too so i'm going to set those options active foreground i'm going to set this the same as my foreground color and the active background will be the same as our normal background so that's active background equals black and this should no longer flash when we click on it not too bad not too bad let's add some padding pad x i'll set this to 25 and pad y i'll set this to 10. we have a little more padding around our check button one feature that's available to us is that we can add an image next to our check button i downloaded an image of the python logo that i want to add so we'll use the image option to add a photo image to this check button but first we need to create a photo image from our image file so within the window let's call this python photo but you'll probably use something different for your project python photo equals photo image and within the constructor for our photo image we can set the file path or the file name since this image is within my project folder i only have to list the file name and this photo of mine is python.png and now we set the image equal to our photo image that we have image equals python photo but when we run this it's going to overlap the text we still have our image though and this still works as intended so in order to display the image as well as the text we're going to need to use the compound option and let's add that at the end compound is where we're adding this photo relative to the text i want this photo on the left hand side of the text so i'm going to set this to left and now when we run this surprise surprise our image is on the left hand side one thing that you should know is that with the on value and the off value data type if you were to change this to a non-integer value let's say we're going to replace the on value with a boolean value of true and the off value is false with this variable make sure to change the data type as well to reflect what you're storing within it so with our int var variable we want to change this to a boolean var value so replace int with boolean and this will work much the same now with this display function we'll need to account for that so within the if statement here we'll say if x dot get we don't need to say is equal to one this will return true or false and this will work just the same as it did before and if you replace this with a string let's say the on value is yes all caps and the off value is no this is now a string bar and we'll change our display function to say if x dot get is equal to yes and this should work you agree you don't agree you agree you don't agree and i'll change that back to one so one and zero is the default for this but you can edit these based on what you need all right so that's the basics of check buttons in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of check buttons in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to be teaching you guys how we can create radio buttons in python so sit back relax and enjoy the show okay everybody let's create some radio buttons now these are similar to check boxes but you can only select one from any single grouping so let's pretend that i'm buying you lunch and you can only select one item from a menu you can select either a slice of pizza a hamburger or a hot dog so let's begin by creating a list i will call this list food food equals pizza hamburger hot dog and let's create a window window equals tk followed by window dot main loop so to create a radio button we'll need a name so i'll call this radio button radio button equals radio button and we're going to be adding this to our window and we're going to put this within a for loop so we're going to iterate through all of the items within our list so let's create a for loop so we'll say for index in range length of food so this is going to iterate once through all of the elements within our list so when we run this it's going to create three radio buttons for us because we're instantiating one radio button for each item in the list now what i'm going to do is set the text equal to our list of food at a certain index so when we first run this for loop it's going to be zero for the index then one and then two and then so on and so forth for each item within our list and then we just need to pack this so radio button dot pack and then let's take a look at this alright so here are all of the radio buttons that we have currently they're all selected though so we'll need to link these within a single grouping the next thing we'll add is a variable and we'll set this equal to x and we'll need to declare this after we create an instance of our window so x equals int var so this will hold an integer object so these are all within the same grouping however if we try to run this again and select one of these options they all become selected so we're going to need to give each of these individual radio buttons their own value because right now they're all sharing the same value so we can add value equals whatever the index is currently so the first item within our list of food is going to have an index value of zero then one then two so let's try that again and you can see by default it's zero so pizza is already selected then we can select either hamburger or hot dog but we can only select one so that's kind of what we want then so do you guys usually know how i call the config function after each change that i make for an object well that's because i like to add comments just for teaching purposes for what each change does however it might be easier for you instead of calling the config function a bunch of times just to list all of the changes within the parentheses when you create an instance of the object that you're working with however just for teaching purposes i'm going to put this all within separate lines that allows me to add some comments so i think i'm going to start doing that from now on uh so what this does is that this adds text to radio buttons and this groups radio buttons together if they share the same variable so if you wanted a completely different grouping of radio buttons you can give them a different variable like y and what this line does is that this assigns each radio button a different value all right so let's make some cosmetic changes to our radio buttons so right now they are centered let's anchor these to the west so we'll place this within the pack function so anchor equals w alternatively you can just say capital w without the quotes this would also work too so now they're all lined up let's add some padding so i'm going to add pad x and i'll set this to 25 and this adds padding on x axis let's also change the font so we'll save font equals maybe i'll pick impact for a font style and set the font size to 50 and now we can actually read these because the font is large enough now let's add some images so let's create some photo images you'll want to be sure to create these after you create your instance of your window so let's create a pizza image first pizza image equals photo image file equals the file path or the file name and my file is pizza.png and it kind of looks like this it's just the pizza emoji so pizza.png and then i'll do the same thing for hamburger and hotdog so this will be hamburger image file equals hamburger.png and then hotdog image and this is what the other emojis look like and then let's create a list of the photo images that we have i'll call this food images equals than the names of these images pizza image hamburger image and hot dog image so then we can set the image for each radio button image equals the name of the list food images followed by the index that we're currently on within our for loop so this adds image to radio button and let's test this cool here's our images now if you want some images as well as text you'll have to use compound so let's add that next so i'm just going to add a comma followed by compound equals let's say left so this will add the image to the left of the text adds image and text i'll just say left side so this will display both an image and text so with these radio buttons you can eliminate these circle indicators and there's actually a way to do that so what we'll add if you want to get rid of those is indicator on equals zero so this will i should say eliminate circle indicators so it's going to change these to these push buttons however they are going to be of uneven size you can set the width if you want to so we'll do that so we'll say width equals what about 75 i'm not sure if that's a good size or not okay that's way too small let's try 375 so yeah you can have some push buttons if you want to if you don't like the circle indicators so this sets width of radio buttons now let's actually set a function to uh be called when we click one of these buttons so let's call this function maybe order like we're ordering one of these items so def we'll call this order like we're ordering something and what we'll do is just a few if statements because i'm feeling lazy so we'll just say if x that's the value that's going to be stored because each of these radio buttons is grouped together by the variable x if x dot get is equal to zero that's our first index for pizza what we'll display is print you oops you ordered pizza then we'll just add else if x dot get is equal to one we will print you ordered a hamburger and then else if two you ordered a hot dog else print huh so there's probably a more efficient way to write this however i was just feeling lazy and this is probably the best way to keep this simple and easy to understand so let's try this now oh however we need to set the command for our radio buttons so command equals then the function name which is order and make sure you do not add the parentheses so don't do this do that and this will set command of radio button to function all right let's test this so if we click on pizza it says you ordered pizza you ordered a hamburger and you ordered a hot dog okay everybody so that's the basics of radio buttons if you would like a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of radio buttons in python hey what's going on everybody it's you bro here hope you're doing well and in this video i'm going to teach you guys how we can create a sliding scale in python so sit back relax and enjoy the show let's create a scale so we'll need a window window equals tk followed by window.mainloop we'll create a scale called scale scale equals scale we need to add the scale to our window so we'll put that here we can list a from position and a 2 position both of these values will be our range of values that we can use for our scale so from sure to add an underscore after from it won't work without this underscore from equals let's say 0 and 2 equals 100 so we're going to create a scale for temperature and this will be in celsius so 0 will be freezing and 100 will be the boiling point uh you know for water so then to display the scale we'll need to add scale.pack and let's run this so the front position is zero so that's at the top here and then if you go down it increases so you can actually flip this so we'll save from 102 will be zero so now you can scroll up and the number will increase let's also get the current value so we'll need a button so button equals button we'll add this to the window we'll add some text text equals submit and then a command command equals submit but we'll have to make this function so let's do that outside the window def submit and we will simply print the current temperature so let's display message the temperature is plus scale dot get plus degrees celsius we can just say degree c so let's try this uh but we also have to pack the button so button.pack so if we were to try and submit this right now scale.get is going to return an integer so we need to convert this to a string so str scale.get and you have to do that with python if you're displaying a integer value along with another string uh you need to convert it to a string so now this should work so it is 82 degrees celsius so let's do some cosmetic changes for our temperature gauge because right now it's kind of ugly so the first thing we'll change is let's say the length so length equals 600 so that should be fairly large you can also set the orientation so that is orient spelt like that so this can either be vertical which it currently is or horizontal but i'll keep this as vertical so i'll let a comment that this is orientation of scale let's also change the font so font equals pick whatever font you want and a size so maybe 20. now you can add some tick intervals maybe i'll set this to 10. so these will be numeric indicators on the scale and show value this hides the current value so if you set this to zero this will hide current value so it no longer displays what the current value is next to the slider to actually retrieve it you'd have to get the value so right now it's 40 but it helps that you have the tick intervals on the left-hand side i should probably add that this adds uh numeric indicators for value good enough let's continue on now let's use the set function we can set the current value of the knob on our scale and by default it is zero so we can use the scale dot set function and we can place a number in here a value so let's say we want this to be 100 so this is now at the 100 position instead of zero if we wanted this in the middle we could set this to 50 and now it's in the middle however if you change the range of your skill of from minus 2 and set this to 50 now 50 is all the way down here so it no longer appears in the middle so this isn't really necessary but if you want this to be a little more sophisticated there's actually a formula that you could use we can use scale straight braces and then place the word from within here this will give us our max basically uh so this is from without an underscore so this not this this scale from minus scale two and then we're going to divide this by two and then i'm just going to put this within a extra set of parentheses plus scale two just in case our two value is greater than zero we just want to account for that and then i'm just going to put these within another set of parentheses so this should always appear in the middle then even if we were to change this range yeah it seems like it works uh like i said it's not really necessary but if you want this to be a little more sophisticated that would work now let's make some cosmetic changes to this scale and make it look pretty so first let's change the trough color this is this gray portion right here so let's set the trough color equals whatever color you want you could say like blue or you can place a hex value here and i actually picked one out already so i'm going to use 6 9 e a f f and that is this icy blue color kind of like this is sliding on ice and i'm also going to change the font color and i'm going to pick this fiery red color to symbolize heat and then you can change the background color too so that is bg and i'll just set this to like black it's looking kind of cool now right and for no good reason i'm going to add some pictures so feel free to pause the video if you'd like to download some images i'm going to use an image of a flame for the hot side of our scale and a snowflake for the cold side so let's begin by adding the hot image uh to the scale before we actually add the scale to the window so we'll do this after we instantiate the window because that's the only place that we can do that so we're going to create a image i'll just call this hot image for the fire icon so hot image equals photo image file equals this is hot.png so hot.png we're going to add the image to a label i'll call this hot label hot label label image equals hot image and then we need to pack this so hot label dot pack and this should appear at the top let's test it yep there it is let's do the same thing for the cold side so i'll add this here before the button and i'm going to replace hot with cold same thing with the file name cold.png this will be cold label cold image and cold label dot pack and that should be it let's take a look not too shabby it's looking pretty sweet it has our submit button at the bottom too uh so right now the temperature is 100 degrees celsius the temperature is 0 degrees celsius the temperature is 60 degrees celsius well that's how to create a scale in python if you would like a copy of all this code i'll post all of this in the comments down below but yeah that's how to create a scale in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create a list box in python so sit back relax and enjoy the show all right you wonderful people let's create a list box a list box is a listing of selectable text items within its own container so as always we'll need a window window equals tk followed by window dot main loop let's create a list box simply called list box big surprise there right so list box equals list box what are we adding this list box to we're going to place that here within the parentheses of the constructor we're adding this to our window and then we're going to follow this with listbox.pack you can also do listbox.place as well and place some coordinates but we've always done pack let's just stick with that for now all right so this is what our list box looks like it's a small rectangular box and we're going to add some text items that are selectable and eventually we'll be able to submit a choice so i have an idea let's create an online menu like we're ordering food from a restaurant let's say it's bros italian restaurant so let's add some food items to our menu and somebody can submit an order so we'll need to use the insert function of the list box to add some items so list box dot insert we place an index and a text item so let's say for index one we'll have pizza and this is what we end up with we have the item pizza it's selectable and well that's really it we'll need to create a submit button and populate the rest of this list box so let's add a few other items for our menu so let's say we'll have five items and we need an index for each so one two three four and five so we have pizza for the first item for the second item let's have pasta and third let's say garlic bread because garlic bread is awesome and restaurants usually have appetizers so why not soup and salad and that should be enough for this example and this is what we have we have our menu and we can select an item from this menu so let's customize the appearance of this menu well because we can so let's do that let's change the background color so we do that with the option bg for background and you can set this equal to a color of your choice or a hex value so i have a hex color value already picked out it is f7fde and this has the appearance of i would say paper like it's kind of faded i think that would fit some sort of menu for a restaurant but pick whatever background color you want so let's change the font next so we can do that with the option font and i will pick the font it's somewhat fancy i think it would fit like a restaurant menu and then a size of 35. yeah we're getting somewhere we can also change the width and the height so width equals let's say 12. that's not too bad for a width let's also change the height so we can do that with a function of our list box so let's get the current size of the list box and let's actually do that after we insert all of the items within our list box so to change the size of our list box what we do is type in list box dot config you usually use config if you need to change any uh options and we want to change the length of or the height of this list box so we're going to say height equals list box dot size function so then this will adjust the size of our list box dynamically even if we were to remove an item then the size of our list box is going to shrink just like that but let's keep salad in there for now because we need salad all right so how do we actually submit one of these options we'll need to create a submit button so let's do that after we create our list box so near the bottom we'll call this submit button submit button equals button we're adding this to our window let's set the text to submit and we'll need a command so we'll create a function called submit and then we need to pack this submit button submit button.pack now at the top of this program let's create a submit function so at the top def submit so to retrieve or get the current selected item of a list box there is a certain function that you can use so we'll begin by saying list box dot get what are we getting we want to get anything that is currently selected and there is a function for that so what we're going to do within the parentheses of the get function is type in listbox dot current selection it's shortened to cur selection all right and then we can either store this within a variable or we can just print this but i think we'll just print this to keep it simple now when we select an item and click on the submit button it's going to submit our order actually better yet let's actually uh print you have ordered whatever item that we select so garlic bread you have ordered garlic bread cool what we're going to work on now is a way to submit or insert an item to our list box after this program is compiled and already running so we'll create an entry box within our window where we can submit a custom item to this menu so let's create an entry box and let's do that before the submit button that would be a good spot for this so let's call this entry box where somebody can type in something to add to the menu so entry box equals entry and we're adding this to our window and then entry box dot pack then we're going to create a button called add and i'm just going to copy everything from the submit button and we'll change submit to add we're going to add an item to the menu so we'll change the text to add and command add add button dot pack then we're going to create a function called add and we'll do that at the top def add parentheses colon so to add an item to the list box first we need to get what is currently in the entry box so we can do that by typing in list box dot insert then within the parentheses we need to get an index number as well as a text item so for the number what we can type here is the listbox dot size so this will give us the current position of the index that we're currently on for the list box and then we need to get the text in the entry box so we type in the name of the entry box entry box dot get and this will insert a new item within our menu our list box so let's try it again so we can type in an item let's say soda we want to add soda to the menu and then we click add all right there's our soda but we have to scroll down to see it so let's change the size of our list box so there's actually a line of code that we did that already listbox.config height equals listbox size so let's add that within the add function at the very end so then the height of our list box will adjust so currently there's no soda within our menu let's type in soda or some other item click add and then that item will appear and the size of the list box will change to accommodate any new items let's say now that we serve sushi we're now an italian and japanese restaurant now we have sushi on the menu you know what why stop there let's create a delete button to delete an item from this menu so we'll create a delete button i'll just copy everything for add and change this to delete so delete button text equals delete command equals delete as well and delete button dot pack and then at the very top we'll create a delete function so we'll do that here d e f delete and to delete an item from a list box there's actually a function to do that so list box dot delete and then within the parenthesis of the delete function we can pass in list box dot current selection or just cur selection for short and then we want to readjust the height of this list box after we delete an item so we'll just add listbox.config height equals listbox.size because the size of all the items within the list box is going to shrink after we delete an item so let's try this so here's our menu let's say we no longer want salad because salad is healthy well we can delete it same thing with soup and you know what let's also delete the pasta and the pizza so we're only left with sweet sweet garlic bread well ladies and gentlemen we're going to get into some more advanced stuff with list boxes what if you want to select more than one item from this list box we're going to need to change a few things so when we create our list box there is a select mode select mode and we are going to set this equal to multiple so now we can actually select multiple items from this list box like i want to select one of everything but what happens when we submit this well we're going to run into some problems so we're going to need to change this program around so let's begin with the submit option so what we're going to do within the submit option is first get rid of this line let's say we no longer need this anymore uh and then before we print out the items that we ordered let's create a list called food and we'll just leave this empty for now we'll fill this later so we'll create a for loop for index in list box dot current selection what we're going to do after each iteration food dot insert our index number as well as listbox dot get the item name at this index what this for loop is doing is that it's going to iterate once for each item that we select so since we have three items that are currently selected this is going to iterate three times get the index number as well as the item at that index number and now we just need to display the contents of what we have within our list of food so we can do that with another for loop so let's add that after you have ordered then for index in our list food all we'll do is print index so this will print out everything that we ordered so let's say that we want one of everything and submit this you have ordered pizza pasta garlic bread soup and salad now what happens if we try to delete multiple items so let's say we want to delete soup and salad and we click delete well we're going to run into an error because our function is not set up to accommodate for multiple items so we'll need to change a few things around so let's get rid of this line for now list box dot delete list box dot current selection and we're going to place a for loop here so for index in list box dot current selection then after each iteration what we're going to do is use list box dot delete and we're deleting the item at whatever index we're currently on so you would think this would work at first glance let's say we want to delete pizza and pasta we're going to click delete so pizza was deleted but not pasta that's because the indexes are changing after we delete an item so when we use this for loop we should actually reverse this so with listbox.currentselection we are going to enclose this with reversed so then we're going to start at the last index and work our way to zero in that order so now if we want to delete pizza and pasta i don't know why we would because they're amazing and we click delete it deletes pizza and pasta but we still have garlic bread soup and salad then we can add an item let's say we want to add sushi against the menu we can do that and then we can order one of everything because we're really hungry you have ordered garlic bread soup salad and sushi so that's the basics of creating a list box in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of list boxes in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create message boxes in python so sit back relax and enjoy the show okay people let's create some message boxes but first we'll need an import so from tk enter import message box and what this will do is import the message box library so it's not necessary to add this comment uh so we'll need a window window equals tk followed by window dot main loop let's create a button so button equals button we're going to add this to the window we're going to set the command to execute a click function that will have a message box appear when we click on the button and let's set the text so text equals click me and then we will need to pack this button so button.pack now we'll need to create a click function so let's do that at the top def click and what do we want to do so there's a few different uh message dialog boxes that you can use so let's begin with a basic show info message box so message box dot and there's a few options let's begin with show info show info this just displays a simple message so if we were to run this we have a button we click on the button and it's going to create a message box for us and it just shows some info but we don't really have any info to show yet so we can set a title and we can set a message so let's set the title title equals this is an info message box although part of the title got cut off let's also set the message message equals you are a person click me you are a person thanks i didn't know that so there's a few other message boxes that we can use too so for now i'm just going to turn this into a comment and i'll just copy this just to save some time and the next one that we have is show warning so this will have a different icon so the title let's say warning and the message you have a virus so now we get this annoying warning message but you can just click ok to get rid of it so one thing that you might see with tech support scams they'll have a message box like this that shows a warning but they'll put this within a while loop that's set to true so this will just continue on and on kind of like this so if we were to try and close out of this it's just going to reappear while true is true basically so that's just something funny that i wanted to show you so let's move on i'm going to turn this into a comment then the next one we have is show error so show error title set it to whatever you want error message something went wrong there's a few more sophisticated ones too we can ask for some user input so this next one is message box dot ask and there's a few to choose from let's go with ask okay cancel first we'll set the title title equals ask okay cancel and a message message do you want to do the thing so we can actually put this within an if statement so this returns either true or false depending on what you click so let's put this within an if statement if this is true print you did a thing if it returns false we can use an else statement else what else do we want to do we'll say else print you cancelled a thing and let's test this but i am forgetting a colon there do you want to do the thing okay you did a thing let's try it again do you want to do the thing cancel you cancelled a thing cool there's a few others so i'll turn all of these into comments and the next one we can go over is ask retry cancel and this is fairly similar to what we had before i'm going to copy this let's change this to ask retry cancel ask retry cancel do you want to retry the thing you retried a thing or you cancelled a thing so it's very similar to what we had before do you want to retry the thing retry you retried a thing and cancel you cancelled a thing okay the next one we have is ask yes no so we can get some user input if it's a yes or a no so this returns a boolean value a true or false value so message box dot ask yes no and we'll set the title title equals ask yes or no and a message do you like cake so let's put this within an if statement because this returns a true or false answer print i like cake too else they answered no then if this is false print why do you not like cake and i'm missing a colon there we go so if they click yes this returns true and we execute this line of code i like cake too if they answer no it's going to execute this else statement do you like cake no why do you not like cake now what we have next is ask question and this doesn't return a boolean value of true or false it actually returns a string of yes or no so this is message box dot ask question and we'll set the title to ask question and a message message equals do you like pi so let's just print the result what this returns so print everything within here so like i said this doesn't return it true or false but yes or no so what we could do is assign the response to a variable such as answer so answer equals whatever the answer is whatever they click whatever button they click on so if our answer is equal to yes will print a message print i like pie 2. then else the answer is no will print why do you not like pie so do you like pie yes i like pie too do you like pie no why do you not like pie so this next one is probably the most difficult it's ask yes no cancel so it's message box dot ask yes no cancel it's this last one so let's set the title title equals whatever you want yes no cancel and a message message equals do you like to code so let's just print the results what this returns so print everything just so we can take a look so the possible answers are true false or none so we can just run some if statements for this so if answer is equal to true what we can do is print you like to code oh but we need to assign this to an answer so answer equals all of this else if answer is equal to false let's print then why are you watching a video on coding and then else the response is none so we can just use an else statement so else you have dodged the question okay let's try this do you like to code yes you like to code uh but this should really be a smiley face right do you like to code no then why are you watching a video on coding do you like to code cancel you have dodged the question no one other option available to you is that you can change the icon that you're using so let's say that we want to change this icon so right now it is currently this question mark so we can set this to one of a few preset icons so icon equals and let's set this to warning so instead of that question mark we get this yellow exclamation point and you can also use info it's just an eye and error so do it fits best for you all right well that's the basics on message boxes in python if you'd like a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of message boxes in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys about the color chooser module in python so sit back relax and enjoy the show okay everybody so before we begin it we'll need a second import so let's add this at the top so from tk enter import color chooser and the reason that we need a second import and it's not included with this first import is because this is a sub module it's not necessary to add this comment i just like to add comments for teaching purposes so make sure you have these two imports before we begin now we'll need a window and a button that we can add to the window and when we click on the button we're going to select a color and change the background color of the window so let's create a window window equals tk followed by window.main loop and then let's set the geometry so we're going to change the background color of the window after we select a color so let's select a fairly large size for a window maybe 420 by 420 so this is the width and the height and then let's create a button so button equals button let's set some text text equals click me and we're going to set a command for this button that is called so we're going to create a function maybe called click and then we just need to pack this button so we can add this to the window so button.pack now we're going to need to create a function and we'll call it click so when we click on the button this function is going to be called so def click and what do we want to do after clicking this button what we're going to do is take color chooser and we're going to use the ask color function so currently this is what this does we can select a color after clicking this button and pick whatever color you want then you hit ok however we need to store this color within let's say a variable so we'll create a variable called color color equals color chooser dot ask color and then we can do something with this color but for now let's just print this color just to take a look to see what it contains so print color so let's say that i want this green color click ok this is what this prints this is our color so this is the rgb values that we have in this first element so this is the amount of red then green and then blue and the second element is the hexadecimal representation of these values so what we want is this hexadecimal value so what we can do is create a second variable to store this so let's just call this color hex color hex equals color and we're going to get the first element well technically it's the second element but it's the element at position one so this one this is zero index zero so we're going to basically extract this hexadecimal value and let's just print this just to be sure that it's working fine so print color hex and let's try this again but select a different color uh maybe i want this purple color then click ok so this is cb42ff and here we have cb42ff now let's change the background color so since we have this hex value that's actually fairly simple so we're going to take window dot config bg for background color equals color hex and this will change background color and let's set this to a sky blue color maybe like this click ok and it changes the color however it's not really necessary to continue printing these values you can take these out if you want and this would work like just the same then now this part isn't necessary but if you want you can condense these three lines of code that we have for our click function into less lines of code so what you could do instead of assigning the value of color at index 1 to a separate variable we can take color at index 1 get rid of this line and assign bg equals color at index one so now this is done with just two lines of code and why stop there we can write this with just one line of code so now we're going to take color chooser dot ask color get rid of this line bg equals color chooser dot ask color at index one and now this is done with just one line of code however it's a i would say a little more difficult to teach so that's why i kind of like to separate this line by line so if you want you can condense all of this into just one line of code so here's some ideas of where the color chooser sub module could be helpful so of course you can change the background color too but let's say that you're creating a game and you can customize your character or avatar well it would be kind of nice if you could have some way for the user to actually change maybe the character's hair color eye color something like this would actually work fairly well so yeah that's the basics of color chooser if you'd like a copy of all this code i'll post this in the comments down below but that's the basics of color chooser in python hey what's going on everybody it's bro here hope you're doing well and in this video i'm going to teach you guys how we can create a text area in python so sit back relax and enjoy the show all right my fellow bros let's discuss the text widget this functions like a text area you can enter multiple lines of text i'm not sure why it's called a text widget instead of a text area widget text area would make more sense but idk though so let's begin by creating a window window equals tk followed by window.main loop so to create a text widget also known as a text area let's call this text text equals text and we're going to add this text to our window and then we need to pack this text text dot pack so we should have a text area and you can enter in stuff like this all right but what good is a text area if you can't actually submit some text so let's create a button to do that for us so button equals button we're going to add this button to the window and button dot pack so we need a command for this button and a function as well so let's create a function called submit it's going to be a submit button and let's change the text to because we can text equals submit cool now let's create a function called submit and we'll do this at the top d e f submit and what is this going to do well it's going to get the text from the text area and let's assign this to a variable and we can call this maybe input or whatever you want so to get the text from the text area let's say text that's the name of this text area dot get but we need a starting index as well as an ending index so we're going to place 1.0 here for the beginning index this is the first line we want to get everything so for the second index we can just put end then we can do anything we want with this input so let's just print this to the console window so print input and this should work hey you drink plenty of water love you and click submit and then you can do whatever you want with this input well that's how a text area functions but now let's customize the appearance of this text area and i have a few ideas that you might be interested in so let's change the background color of this text area so bg equals and i will pick light yellow and you will see why in just a second so now this text area kind of resembles maybe a piece of paper a notebook a post-it note however this font is really small so let's change the font styling and the font size so font equals and i will pick the font ink free this somewhat resembles handwriting so i kind of like this and it kind of fits our notebook theme and then a size maybe 25. one thing you should know the text area size corresponds directly with the font size so 25 is a fairly large font so if we were to compile this and run this the size of our text area is now massive because it corresponds directly with the font size so we might want to limit the width and the height so the height is the amount of characters that this is tall so let's say 8 and the width is the amount of characters that this is long and let's say 20. and now this should be much smaller and it kind of resembles a post-it note which is kind of cool let's also change the amount of padding that we have we can do that with pad x and pad y so pad x let's say 20 and pad y also 20. so the text shouldn't actually touch any of the borders this is some sample text cool let's finish this by changing the font color so that is fg for foreground foreground equals and i'll pick purple because purple is a pretty color and let's run this one last time roses are red violets are blue booty booty booty booty rockin everywhere well that's the basics of the text widget in python if you would like a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of the text widget in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can use a file dialog in python to open and read the contents of a file so sit back relax and enjoy the show okay people so this is how you can use file dialog to open and read the contents of a file but first we'll need a second import along with this import at the top so what we're going to be importing is from tk enter import file dialog and then we'll need a window like what we usually do so window equals tk followed by window dot main loop now we'll need a button that we're going to add to the window and when we click on this button it's going to launch our file dialog so we can select a file so we'll call this button button equals button let's set some text maybe to just open like we're opening a file and we'll associate a function to our command for this button so let's create a function called open file that's fine and then we need to pack this button so we can add it to the screen so button.pack now we need to create a function called open file and we'll do this before we create our window let's type def open file and when we call this function we're going to take file dialog and use the ask open file name function so this is going to return a string and that string is the file path of where your file is located so what we could do is store this within a variable so let's store this within a variable called file path and to test this let's just print this just to take a look at the contents of this variable so let's just print the file path now i have a file on my desktop that i want to use called test file so let's click the open button and this might not necessarily bring you to your desktop it might bring you someplace else within your file directory so this just happens to be bring me to my desktop so i'm going to click the test file that i have and click open so this prints the file path so it's going to return a string and it's the file path basically so now we want to open and read the contents of this file so we don't really need this print line anymore so what we'll do is create a file variable and we're going to use open we're going to list the file path and then we're going to use r for read so the default is normally rt for read text otherwise you can read binary uh but we can just set this to r r is the same as rt basically uh so then we're going to open this file and then we're going to read it so let's just print this to the console window so print the name of the file which is file where this is located file dot read function and then it's a good idea to close your files after you're done with them so file dot close and let's test this so i'm going to click open find the file that i want click it and then open and that text file says my name is bro i like pizza now let's say you want to make this a little more advanced so what i'm going to do is that i'm going to set the initial directory of where we begin looking for a file when we launch our file dialog so with that test file i'm going to move this to my project folder so i'm just going to paste it so now this is within my project folder now i'm going to set the initial directory within the function of ask open file name so we're going to set the initial d i r for initial directory and then we can list a file path so one thing you could do i want to get this path here this file path so if you're using pycharm what you could do is right click this copy path and then get the absolute path and then i'm just going to paste this and then uh with these backslashes you'll have to do double backslashes because this is the escape character for a backslash alright so this should open my project folder which it does and here's that test file another thing we could do is that we can change the title of our file dialog right now the default is just open so we can change that to something else so i'm going to add a comma maybe put this on a different line uh so this is still within the function of ask open file name so i'm going to set the title to something else i'll say open file okay so if we were to run this again instead of just saying open it says open file okay and we can also limit the file types that we accept and look for so we can use file types so let's say that we want to initially look for a txt file so what we'll do is type in like a name for the file that we're looking for so this is what's going to appear to the user uh text files followed by an extension so we want asterisk dot txt and then we can also have an option for all files so i'm going to add a comma for a second option and then let's say all files and then an extension so comma asterisk dot asterisk this will look for all files uh but i think i am missing a parenthesis there that should be good so then when we open our file dialog it's going to initially be looking for plain text files and with this drop down menu it says text files and all files so that's what we have listed within our file types of what we want to search for so you can see that if i switch to all files our python file actually appears because we don't have any limits on the files that we're trying to open or search for so if i change this back to text files only folders and plain text files are visible so then we can open our test file again but yeah that's the basics of file dialog in the next video we're going to be saving a file so if you'd like a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of opening a file using python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can use python's file dialog to save a file someplace on your computer so sit back relax and enjoy the show okay everybody so this is how we can save a file we're going to be reusing a file dialog again kind of like what we did with the video on opening and reading a file so from tk enter import file dialog we're going to be creating a window and adding a button as well as a text area to this window so let's create our window window equals tk followed by window.main loop let's create a button so button equals button let's set the text of the button so text equals save it's going to be a save button and then a command so we'll need to link a function to this command so let's create a save file function and then we need to pack this button so button dot pack now let's create a text area this is just called text so text equals text we're going to add this to the window and we need to pack this text so text dot pack and now let's create a save file function so at the top of our program d e f save file and then we're going to take file dialog and use the ask save as file function and we're going to store the contents within file file equals file dialog dot ask save as file let's run this just to test it out so we have our window a save button and this is our text area we can type in multiple lines of text yay and let's try and save this just to see what we have so far so this will bring me to my desktop it might bring you someplace else for your computer so i'm just going to save this as test file now with this drop down menu save as type there's nothing set up so we'll need to do that manually uh if we were to save this and here's that test file on my desktop so let's take a look at the properties we did not list a file extension so the type of file just says file so we'll get to that later on in this video and if we were to open this with a program like notepad well it's currently empty that's because we need to write some text to this file so let's do that next let's store all of the text from our text area to a variable let's call this variable file text file text equals and then we need to get all of the text from our text area so text dot get and we're going to list the starting index as well as the ending index for this function so we're going to begin at 1.0 that is the beginning of this text area and the ending we can just put end and then we need to convert all of this into a string so let's surround this with str and then we can store all of the text from our text area within this variable file text and now we just need to write our text to this file so file dot write and we're going to pass in file text and then it's a good idea to close your files when you're done using them so file dot close and let's try this again hello my name is bro let's save this i'll call this hello and click save and we still can't save s-type so we'll work on that next let's go to my desktop here's the test file that we created i'm going to open this with notepad and it has all of the text that we added to that text area now let's list some available file extensions that we can have the user save this file as so let's begin by setting the default extension so default extension and let's set this to a text file that is dot txt and then we can list all of the available file types so file types and we're going to place these within a set of straight brackets and i'll just separate these line by line so let's begin with a plain text file so this will take two strings the first is the message that will appear within that save as type drop down menu so let's place text file and the second string the file extension and that is dot txt then let's add another let's say html so i'm going to copy this and paste it and let's say html next dot html and then lastly you can do just all files so all files and that is dot asterisk and let's try this again so hello my name is bro i like pizza and ice cream and this time i think i'll save this as an html file and this is we'll call this pizza and ice cream i guess and click save now let's go back to my desktop here's that file pizza and ice cream and it is an file let's just verify that yep.html for the type of file so we can open this with notepad and it has all of the text i could even open this with sublime text as well kind of like that all right let's change the initial directory for saving a file let's change it to my project folder for uh this python file that we have so that is and i'm just going to organize this a little bit initial d i r equals and then we can list a file path so i'm just going to copy this so copy path paste it then i want to make sure that these are double backslashes and i need to add a comma at the end okay let's try this again so testing one two three and this should go to my project folder which it does testing123 and let's save this as a plain text file click save and here's that plain text file testing123 another option available to you is that you don't necessarily need to use a text area to get some text to write to a file you could use the console window to accept some text so to demonstrate this i'm going to turn this line into a comment and we're instead going to use the console window this time so we'll say file text equals input and then let's just have a prompt here enter some text i guess and then let's run this again so we still need to click this save button and select a file location i'll just save over our file testing123 i'll click save yeah i'll replace it alright so we need to enter some text i guess so i will write a message such as the cake is a lie and hit enter so then our file testing123 now says the cake is a lie so you don't necessarily need to use the get function for a text area you can use the console window as well here's one last thing to consider before you go so what if we begin the process of finding a file location to save a file to and then we exit out of this window well we're going to encounter an exception so one way that we can prevent this is to add this line if file is none return so then if we were to try this again begin saving a file and then exit out of this there is no exception that we encounter so that's just one little extra i thought i would throw in but yeah that's the basics of saving files in python if you would like a copy of all this code i'll post all of this in the comments down below but yeah that's how to save a file using python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create a menu bar in python so sit back relax and enjoy the show all right people let's create a menu bar not too different from the menu bar that you see at the top of many programs there's usually a tab for file edit view help stuff like that except we're going to create one that doesn't have as many options or features it's going to be the generic brand menu bar like the walmart variety so let's begin by creating a window so window equals tk followed by window.mainloop then we're going to create a menu bar and add menus to the menu bar and each menu is going to function like a dropdown menu where you hover over one of these tabs and there's a drop down so we need a menu bar let's just call this menu bar menu bar equals menu and we're adding this to our window so then we're going to take window dot config and we can set the menu of this window to equal the menu bar that we just created with each of these tabs for your menu bar you need to create a separate menu and add each menu to your menu bar and the menu bar is added to the window there's different levels to the stuff so let's create a file menu because well this one has a file menu why not our program so file menu equals menu kind of like what we did with our menu bar except instead of adding this to our window we're going to add this to our menu bar so menu bar like that there's one other step two we need to use this function menu bar dot add underscore cascade this will have a drop down menu sort of effect so let's create a label just called file to mimic the file tab that you see at the top of many programs so label file and we're going to set the menu to equal the file menu that we created so file menu and let's take a look just to see what we have so here's our menu bar and here's our menu there's a drop down effect for this but we need to add actual options to this file menu so let's do that so let's begin by creating let's see we got maybe open save and exit that should be good so file menu dot add underscore command so this is a clickable option and let's create a label called open and we can open a file and maybe two more so we got open save and exit open save exit and let's take a look at this so here's the drop down menu we can open save exit now you might notice that there is this annoying line this is called a tear off you can actually get rid of this if you want so when we create this file menu we're going to set tear off to equal zero and that should get rid of that and it's gone so sometimes you might see a line to separate sections well you can do that with a separator so let's separate the exit command that we have from open and save and to add that separator we just type in the name of our menu file menu dot add separator so this will separate your different commands from each other within a menu you can see that there is a line between save and exit because we placed a separator here now if you want each of these file commands to actually do something you need to associate a command with each of these commands it's a command within a command so command equals for our open file command we'll create a function called open file and we'll need to declare that function and then let's create a command called save file and then another called exit actually one shortcut if you want to exit something you can just say quit all right let's create an open file and a save file function so def open file let's just print something just to keep this simple i already have another video on opening files so print file has been opened and let's do the same thing for save file file has been saved and then our last command exit we'll just quit so let's try this so let's go to file here's the drop down menu we can open a file file has been opened we can save a file and then exit and exit will close out of our window let's create a second menu called edit to mimic the one that we have at the top of our ide so let's create a edit menu so it's the same process that we did with our file menu so let's call this edit menu equals menu we're adding this to our menu bar and i do not want a tear off so tear off equals zero then for the next line we need to add cascade so i'm going to copy this menu bar dot add cascade the label name will be edit and the file i mean the menu will be edit menu and we're setting this menu that we're adding to edit menu and let's try this so we have file and edit but we need to add commands to this edit menu so it's the same process that we did with our file menu i'm just going to copy this change file to edit and let's make a command called cut copy and paste so the label will be cut we'll create a command called cut we'll copy this and we'll create a another command called copy and then paste all right then we just need to create some functions for this so cut copy paste let's do that at the top so cut you cut some text so cut copy and then paste you copied some text and paste you pasted some text all right let's try this so here's our edit menu here's the drop down we can cut we can copy and we can paste not actually but it's going to call a function that can do something like that if you want to set that up maybe that's a video for a different day let's customize these menus well because we can so let's begin by changing the font so we can just type in within each of these menus font equals pick a font that you want and then a size so i'm going to add this font for both of these menus that we have and then when we hover over and click on these menus you can see that the font has changed did you guys know that you can actually add images next to each of these commands well you can and this is how we can do that first you'll need some images here's a few that i'm using so add these to your project folder i plan on using a floppy disk for save and open folder for open and for some reason a stop sign for exit because i couldn't really think of anything at the moment i guess an arrow would have worked too i guess so let's create some photo images out of these images so i already did this i'm just going to copy and paste the text that i had so create a unique name for each image i have open image save image and exit image they're all photo images and here is the file path or the file name for each of these pictures that i'm using so to add an image to each of these commands when you add the command we can just say image and then the photo image that you want to use so with my open command i'm going to use this open image photo image that i have and this is the open folder so i'm going to do the same thing for save and exit so we have save image and exit image but when we run and compile this let's take a look yeah so all the text is gone that's going to be a problem so we'll need to compound views so with compound we can add an image on a certain side of the text and keep the text so compound let's say we want the image on the left so compound left and i'm just going to add this to each of these commands and now we should have an image as well as some text well that's the basics of creating a menu bar in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's how you can create a simple menu bar in python what's going on everybody it's bro here hope you're doing well and in this video i'm going to teach you guys how frames work in python so sit back relax and enjoy the show what's going on people we're going to be discussing frames today a frame is really just a rectangular container to group and hold widgets together so we're going to practice using frames today but first we'll need a window we're going to create a frame and add a frame to the window so window equals tk followed by window.main loop well we're going to need some widgets to add to our frame so let's create a bunch of buttons because why not so i'm going to show you guys a shortcut too so let's say button equals button and then for now we're going to add this to our window but we're going to replace this eventually with frame when we create this and i'm just going to set the text to equal let's say w we're going to have four different buttons wasd like the buttons on the keyboard if you're playing a game and you want to move forward left back or right so we're adding this to the window for now let's set the text to w and what else can we do uh let's change the font so font equals i'll pick the font consoles because that tends to be even uh with buttons the size of the button adjusts to uh the size of the uh letter that you're using or the size of the text uh so let's set this to 25 and then a width so maybe width equals three all right and then button.pack and i just want to take a look at this so here's our button w so i'd like to show you guys a shortcut if you don't plan on using this button by name you don't really need to give it a name you can just say button and then have all your uh options here and then instead of having button.pack just add dot pack to the end so this will do the same thing however you can't adjust this button by its name though because it doesn't have a name anymore so let's create a few other buttons one for a s and d so we have w a s d and by default they're all top and center so with pack we can actually put these on a certain side so let's say we want uh w on the top and then the other three will be all left so side equals left and then after i show this to you you'll see the benefits of using a frame all right so right now they're all at least it appears that they're all within a container so what if i were to expand this well w is just drifting off it's sailing away by w so what if we could put these within a frame or container to actually contain all of these widgets well we can so let's create a frame frame equals frame and instead of adding these buttons to the window we're going to add these buttons to our frame and now we need to add the frame to the window and this is what this looks like however we need to actually add this by using pack or place so frame dot pack so now what this looks like is that all of these buttons all of these widgets are now contained within a frame a container let's change the background color of this frame just so that we can see the width and the height of this frame so when you create your frame there is an option for background color it's just bg and let's set this to a color we haven't done pink yet pink is a very masculine color so now the background of our frame is pink and that might be a better visual cue to the balance of the frame let's also give this frame a border so let's set a width of 5 using bd and then the type of border that we want and we can specify that with relief so relief equals let's say raised so this will have a 3d pop effect kind of like that let's try sunken there's a few other ones as well but i don't feel like it's necessary to go over all the border types let's stick with sunken for now that'll work alright so with this frame we are currently packing this we can set this on a certain side within our window so currently it's at the top let's set this to maybe the bottom so side equals bottom now this frame is sticking to the bottom of the window and it still contains all of the buttons all of the widgets that we added another function available to you is the place function we can place this frame at certain coordinates within our window so let's set x to equal zero and y to equal zero so then when we place this frame within our window and set some coordinates this entire frame is going to stick at these coordinates even if we were to resize this window and we can change these too let's say x is now 100 and y is also 100 so the frame along with all of the components all of the widgets that it contains are sticking within the container and they move along with this so that's the basics of frames it's really just a rectangular container to group and hold widgets together so if you want a copy of all this code i'll post all of this in the comments down below and well yeah that's how frames work in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys a few different ways in which we can create new windows using python so sit back relax and enjoy the show let's get started everybody so we're going to create a window and we'll add a button to this window when we click on this button it'll create a new separate window for us so window equals tk followed by window.main loop we'll need to add a button so let's do that button we're adding this to the window let's add some text to the button let's say create new window and we'll set a command command equals and we'll need to define a function let's create a function called create underscore window and let's pack this as well so we will define this function create window and let's do so at the top def create window and what do we want this to do well we're going to create a new window and let's call this next window new underscore window equals and there's two popular ways of creating a window one is we can use tk and the other is that we can use something called top level and let me explain the difference between the two here's a definition for a top level window this is a new window on top of other windows and it's usually linked to a bottom window our main window is serving as the bottom window and our new window is serving as the top window the top level window so let's try this and just experiment here is our main window the bottom window and if we were to click on this button it's going to create a new window for us a new top level window if we were to close out of the bottom level window any top level windows associated with this would also close kind of like what you just saw now however it's not the same case the other way around if we have a bottom window and a top level window and we close out of the top level window our bottom level window is just fine it didn't close out of that so think of these like jenga pieces if you were to pull one of the pieces one of the windows out from underneath the bottom any pieces or windows on the top of it will close out as well or collapse kind of like in the game jenga so that's one way to think of top level windows they're stacked on top of any bottom level windows if you remove a bottom piece it removes any from the top on the flip side we have tk this is a new independent window and we've actually been doing this since day one of our gui programming tk is a new independent window and our main window and the new window that we create are not linked whatsoever they're completely independent so if we were to create a new window this is our new window and close out of our old window well this new window still persists so this could be useful for let's say a login form or a login screen after you log in you'll be brought to your main program which could be within the new window one other thing that you can do too you can also destroy the old window after creating a new window so we need to type in the name of the window that we want to destroy actually let's call the main window just old underscore window just to clarify things so let's rename that here here and here as well so we want to destroy our old window as if we're closing out of it so we type in the name of the window old underscore window and we use the destroy function and that sounds pretty sweet so we're going to destroy our old window after creating our new window so let me add a comment that this will close out of old window and let's test it so we have our old window our main window we'll create a new window it creates our new window and then closes out of the old window so that's one of a few ways in which you can create a new window for your program so if you want to copy of all this code i'll post all of this in the comments down below but yeah that's how to create a new window using python hey what's going on everybody too bro here hope you're doing well and in this video i'm going to teach you guys how we can create separate tabs for our gui applications in python so sit back relax and enjoy the show okay let's begin so in order to create tabs for our python gui application we're going to need access to a widget called notebook and that's found in a different module so this time we're going to need two imports so at the top from tk enter import just everything but the notebook widget is found within a separate module so we'll need a second import from tk enter import ttk so this ttk import gives us access to several different widgets that are normally not available to us so once you have these two imports you're ready to begin so we'll need a window window equals tk followed by window.main loop and we need to create a notebook widget so right after you create your window we're going to create a notebook we'll call this notebook equals ttk dot notebook and we want to add this notebook to our window so let me add a comment here what this widget does so this is a widget that manages a collection of windows and displays and that's really all there is to it so in order to create different tabs we're going to create some frames so for the first tab i'll call this tab 1 equals frame and we want to add this to the notebook and with our notebook we're adding this notebook to the window all right so this will be a new frame for tab one and let's create a second tab and we'll call this tab two and you can create more tabs if you want but that might be overkill so this is a new frame for tab two after you finish these two lines of code we're going to follow this up with notebook.ad so notebook.ad what widget are we adding we're adding our tab 1 frame and we can set some text for this tab so text equals and i'll type in tab one and we'll repeat the process for tab two so notebook dot add tab two and we'll change the text to tab two and then we need to pack this notebook notebook dot pack and let's take a look to see what we have all right we have tab one and tab two but we'll probably want to actually add something to each of these tabs so that the content is visible so let's create some labels so after we pack our notebook let's create some labels i don't really feel like giving these names because we don't really plan on using them for anything else so we'll just say label tab one that's going to be the parent widget and let's set some text text equals hello this is tab number one then i think i'll give this a width and a height too just so it's more visible so for the width i'll make this 50 and the height 25 so this will be roughly a square shape and then we need to pack this so i'm just going to add pack and let's create a second label for tab two so label tab two maybe i'll say goodbye this is tab number two okay we should have some actual content for these labels now for these tabs so here's the label this is tab one and this is tab two and you can switch between these and they display each of these separate labels however with the way that this window is arranged if we were to expand the size of this window well our frames and our tabs kind of stay in the top and in the center so i'm going to add a few lines within the pack function of our notebook the first thing i'm going to do is use the expand option and set this to true so what this does and i'm just going to add a comment that expand this will expand to fill any space not otherwise used so what happens now is that this will actually expand and it's staying in the center of the window but there's one more thing we're going to add fill equals both normally this is x or y or you can do both so i'll add a comment as to what this option does so fill will fill space on x and y axis so if you combine both of these together what you get is that these tabs will stay in the top left corner and if you were to expand the size of this window the tabs aren't going to move they're going to stick to the top left but the size of the window will expand all right so that's the basics of creating tabs in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of creating tabs in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys all about the grid geometry manager in python so sit back relax and enjoy the show all right everybody let's talk about the grid geometry manager well because we have to this is a useful way to organize widgets within a container imagine our windows being arranged into a series of rows and columns similar to an excel spreadsheet i tend to use that example a lot the top left most cell is row zero column zero computers always begin with zero so that's why our grid doesn't begin with row one column one and we can list which row and column we would like our widgets to be placed within and by default we only have one row and one column to work with at the start but we can explicitly state which row and column this widget should be placed within relative to the container that it's in and python will create new relative rows and columns for us if we state where these widgets should be placed so let's create a small submission form and then organize all of our widgets using our new grid system that we have so let's begin by creating a window window equals tk followed by window.mainloop now that we have our window we'll need to create some widgets to add to this window so let's say that we want an entry box and a label for a first name last name and email address as well as a submit button so let's create a label and an entry box for a first name just to demonstrate this so let's call this label first name label equals label we're adding this to the window and let's set the text to first name for now i'm just going to use that pack to demonstrate the differences between pack and grid and let's create an entry box let's call this first name entry equals entry we are adding this to the window and for now we're just going to pack this and let's take a look so here's our label on the top it says first name and then it has our entry box right underneath so what if we want to have this label on the left hand side and our entry box on the right hand side of the label we're better off using the grid geometry manager so we're going to replace pack with grid and we have to set which row and column that we want each of these widgets to be placed within normally if you use the pack geometry manager as you create new widgets they're just going to be placed directly underneath in one long column so let's say that for our name label we want to place this where the row is zero and the column is zero that's the top left corner so within the grid geometry manager when we call it we're going to set row to equal zero as well as column to equal zero and then for the first name entry we want this to be on the right hand side of our label so we'll place this within the same row row equals zero but in a different column column equals one so column one is directly to the right of column zero and then when we compile and run this we now have our entry box to the right of our label that we have so let's repeat the process for a last name an email address and then a submit button so i'm just going to copy what we have here and change first name to last name so last name label and we'll change the text to last name last name entry and we'll keep that the same now we want this last name label to be underneath the first name label because right now they're going to overlap because we have them in the same row and columns so you can see that we can no longer see the first name label or the first name entry so let's place this directly underneath we're going to put these underneath by one row so we'll keep the columns the same but we're going to put this underneath by one row so row one and row one for the last name entry and what you get is that these two labels and entry boxes are arranged neatly into rows and columns and let's do the same thing for an email so i'm going to copy what we have and we're going to change last name to email so email label and email entry and then change for the text last name to just email and we're going to place these where row equals 2 and we'll keep the column the same and for email entry row 2 column one so doesn't that look a lot better now let's create a submit button so let's call this submit button equals button and then we're adding this to the window and we should set some text text equals submit i guess dot grid and we want to place this underneath currently kind of just shoves it underneath for now let's say that we want this between these two columns so we'll want to set the row and the column to begin with row is going to equal three and column we'll set this equal to zero for now there isn't going to be any apparent change it's still going to be in the same place but one thing that we can do is use an option called column span we can have a widget take up more than one column and it's going to place this widget in between both of these columns in between the combined width of both of them so we'll add column span equals two so this widget is going to take up the next two available columns including the one that it's currently in and you can see that our submit button is now between these two columns that we have one thing that you should know is that the column width is dependent on the width of the largest widget that is contained within that particular column let's say that we increase the width of our first name label well our column is going to expand to actually fit that widget that we have so for our first name label let's set the width to maybe 20 and this is going to increase the width of column 0 and to even better demonstrate this let's color each label a certain color just for a visual for our first name label let's say this is red and then for our last name label let's set this to green and then for email maybe blue now all of these are color coordinated and you can see that the background color of our first name label is taking up the entire column space now what if we changed the size of our email label to something even larger like 30 so width equals 30. and now the column 0 has expanded to accommodate the size of our largest widget which is our email which has a width of 30 and before we finish this video let's add a title to the submission form right on top of the first name label and the entry label so let's call this title label equals label writing this to the window let's set some text let's say enter your info and let's pick font font equals what am i feeling like today maybe just arial and then a size maybe 25 we're going to use the grid geometry manager and we want this at the top so we want row zero at least i want this to take up two columns so we'll say column equals zero and then set a column span column span equals two now a few things are going to overlap here so we're going to move everything down by one row besides our title label so we want this first name label to be directly underneath our title label so let's move everything down by one row and our title is going to be directly on top of our first name label as well as the first name entry box that we have all right so that's the very basics of the grid geometry manager if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of the grid geometry manager in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create a progress bar in python so sit back relax and enjoy the show okay let's create a progress bar but we'll need a few imports to begin the progress bar widget is found within that ttk module so we'll need a separate import from that from tk enter dot ttk import everything and we'll import everything from time as well let's create a window window equals tk followed by window.mainloop we're going to add a progress bar and a button to this window when we click on the button it's going to fill our progress bar let's begin by creating a button to begin with let's call this button equals button we're adding this to the window let's set some text text equals maybe download and then a command maybe i'll call this start finish by adding this button to the window and we'll just use pack to do that let's define what our start function does def start we'll fill this in later i'm just going to print nothing just as a placeholder and we should just have a button now let's add a progress bar before this button and we'll call this progress bar just bar for short bar equals progress bar we're adding this to the window we can set an orientation this can be horizontal or vertical later on in this video i'll show you the differences between the two but for now let's set this to horizontal and then i'm going to pack this bar bar dot pack and add some padding pad y equals 10 and let's see what we have okay this is our progress bar at the top and this is the button when we click on this button it's going to fill our progress bar but i think i'm going to increase the length of this progress bar let's set this to maybe 300 i believe 100 is the default okay that's not too bad of a size now let's define what our start function does we can actually increase the value of our progress bar by typing in the name of this progress bar here value plus equals some amount let's say 10. so what's going to happen right now is that every time we click on this button it's going to fill our progress bar by 10 out of the total which is 100 let's pretend that we're waiting for a certain amount of tasks to complete so let's define a few variables let's say we have a variable called tasks and let's set this to 10 just to keep it simple and x will represent the current task that we're on and we'll say 0 to begin with let's create a while loop while x is less than the amount of tasks that we have we will increment the value of our bar by 10. 10 10 for each test that we have which is 10 for a total of 100 and we'll want to increment the task that we're on as well which is represented by x so let's increment x by 1 after each iteration of this while loop now when we run this and click download this spills instantly let's add a delay just to simulate each task waiting to be completed so let's add that here let's add a delay by using time dot sleep and let's set this to one second we're going to wait one second and then complete a task what ends up happening now is that nothing appears to be updating well what gives bro you lie to me well that's because the window is waiting to have this progress bar complete before it's actually going to display it being filled so we would want to refresh this window after each iteration of the while loop so at the end of this while loop let's add one thing window dot update underscore idle tasks after each iteration of this while loop it's going to update the window that we have so then when we download something it's going to update our progress bar after each iteration of this while loop until it's completed right about now let's take this a step further by adding a label that displays the current percent of the progress bar that is complete let's add this label after the progress bar but before the button sandwiched right between these two widgets so let's add that here we'll call this label percent label equals label we'll add this to the window and we'll need a text variable text variable equals let's call this percent so the reason that we use a text variable is so that we can update this label with some text after each iteration of our while loop and we'll need to pack this okay within the window near the top let's define percent percent equals string var this allows us to update percent with some new text and set the percent label with the new text that we have within the while loop but before we update idle tasks let's set what percent is percent dot set and let's say x divided by tasks and then we'll multiply this by 100 i'm just going to put this within its own set of parentheses times 100 and then we'll convert all of this to a string so we can display this along with some text there are a lot of parentheses here so it might be difficult to keep track of all this all right and then we're just going to tack on percent and that's it let's try it so we got 10 20 30 40 50. i'll shut up now one change that i'm gonna make is that i'm going to cast all of this as an integer before we convert it to a string because i do not like that decimal at the end of our percentage so yeah it says 10 percent 20 so on and so forth let's add a label that displays the current task that we're on so let's copy what we have for our percent label and let's rename this as maybe task label task label text variable will equal maybe text and let's define what text is so text is also a string var and within our while loop let's update the value of our text text dot set will display x plus maybe a forward slash plus our tasks and since we're displaying integers along with some strings we need to convert these to strings and we can use the str function to do that for us so surround x and tasks with str to convert these to strings and then we'll add just plus tasks completed so the value of x will update after each iteration of this while loop let's try it and after clicking download this will display the percentage as well as the amount of tasks that have been completed all the way until it reaches the end let's change this into a more practical example we'll pretend that we're downloading a video game so let's replace or rename tasks as maybe gb4 gigabytes and this game will be 100 gigabytes we'll rename x as well so let's refactor rename and change x to maybe download to represent the amount of gigabytes that are downloaded and let's create a variable called speed and let's set this to one alright so while our download is less than the amount of gigabytes for this game we'll sleep for maybe a portion of a second .05 should be good we'll increase the value of our bar by this amount speed divided by gigabytes and then multiply this by 100 for the download we're going to increment this by whatever our speed is and right now it's one so that's the same we can keep percent the same for our text let's change tasks to gigabytes and that's all the changes that we have to make and now when we download something we're kind of pretending that we're downloading a large file or a game you can see that once it reaches 100 it says 100 100 out of 100 gigabytes completed now we can change this to a different value let's say maybe 50 and the speed will be maybe two so this will adjust to accommodate whatever the new file size is as well as the speed and before i forget you can change the orientation to a vertical bar if you so choose so we have this vertical download bar now which could be good for something all right so that's the basics of progress bars in python if you want to copy of all this code i'll post all of this in the comments down below but yeah that's the basics of progress bars in python what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can use the canvas widget to draw some simple shapes so sit back relax and enjoy the show welcome back everyone well in this video we're going to be creating a canvas a canvas is a widget that is used to draw simple graphs plots and images within a window we're going to be creating some simple shapes in this video not anything too sophisticated i might get more into the canvas widget in a separate video and at the end of this lesson we're going to practice by creating a pokeball so to begin we'll need a window window equals tk followed by window.main loop to create a canvas we can just simply call this canvas canvas equals canvas and we're adding this canvas to our window and then we need to follow this with canvas.pack or place but i'm just going to use pack because it's simple this is what our canvas looks like it's a rectangular area which we can draw graphics on we can also set the width and the height of this canvas so when we create this canvas we're going to set the options for a height and a width so let's begin with the height height equals let's say 500 and the width will be the same 500 and now we have a square canvas that we can draw graphics on let's begin by creating some simple shapes maybe a line i think a line is a shape maybe a one-dimensional one i don't know i don't geometry so let's create a simple line so we type the name of the canvas dot create and there's a bunch of different shapes that we can create let's create a line now i'm just going to turn this into a comment for a moment we need to set some coordinates for this line this top left corner of our canvas is 0 0 and the bottom right corner of this canvas is 500 by 500 depends on what you set the dimensions of the canvas to so when we create a line we need a starting point and an ending point so if we want this to start in the top left corner we're going to pass in 0 0 that is the starting position and we can place the coordinates for the ending position if we want this line to end in the bottom right corner that would be where x is 500 and y is 500 and this is what this looks like we just have a simple line going across the screen but that's not all we can also change the color of this line and the thickness let's begin by changing the color so we can do that with fill fill equals let's pick color blue and now we have a blue line going across the screen but we can also change the width of this as well so we can do that using the width option and let's set this to five now we get an extra thick line across the screen now let's make a red line so i'm just going to copy this canvas.createline and let's change some coordinates for this uh let's say we want this to start in the bottom left corner and go up to the top right so the starting x position would be zero y would actually be 500 x for the ending position would be 500 and y would be zero let's set this to red and we'll keep the width the same okay so here's our red line and notice that this red line is overlapping the blue line so when you create shapes on a canvas if there's any that overlap the one that you most recently created will appear on the top one option available to you is that you can actually give these graphics a unique name with our blue line we could call this blue line blue line equals all of this and then we can call our red line something different like red line this would be useful if you want to call or use a graphic by its name if you want to like move a graphic on the screen or have something appear you can use this by its name but we don't really need it for this lesson so i'll just revert this back to what we had previously i'm just letting you know that you can do that alright what do we have up next let's create a rectangle so canvas dot create rectangle we can set some starting coordinates and ending coordinates the starting coordinates are for the top left of the rectangle and the ending coordinates are for the bottom right so for the starting coordinates let's say we're going to place this where x is 50 y is 50. for the ending coordinates we want this where x is 250 and y is 250 i'm just making up numbers put it whatever you want really and this is what this looks like but i think i'm going to comment out these lines for now and here is our rectangle well i guess it's also a square we can actually give this a fill color as well so we do that with the fill option fill equals purple i guess and now we have a purple rectangle next on our list is create polygon we can create many sorts of shapes using create polygon but it really depends on how many coordinates that we enter let's create a simple triangle so we need at least three coordinates for this to work so canvas dot create polygon and i have some coordinates picked out already so let's place the first set of coordinates where x is 250 y is zero for the second set where x is 500 and y is 500 in the last set the third set we'll place this where x is zero and y is 500 and what this looks like is that we have this black triangle that's taking up most of the canvas we can also change the fill color as well so we do that with the option fill and we can set this to whatever color you want let's say yellow and we now have a yellow triangle on our screen and it kind of resembles the triforce from the legend of zelda series one of my personal favorites let's also add a border this is actually done with outline outline equals and then pick a color for the outline let's say black and we have a black outline around this graphic and you can also change the thickness of this too with width and let's set the width to five and now we have an extra thick line around our triangle with these shapes you can pass in a list of points too so i'm going to get rid of all these and we're going to pass in a list so let's create a list called points points equals all the points that we just entered in previously and then instead of passing in all these coordinates individually i'm just going to pass in our list of points and this will work exactly the same okay let's create an arc now so canvas dot create arc and arc is really just a curved line between at two points however when we list some coordinates we're not listing the coordinates of the starting position and ending position for this arc it's more or less for the amount of space that we want to allocate to actually draw this arc so let's say that we want this arc to take up the entire canvas we can pass in the dimensions for this canvas so the top left corner is zero zero and the height and the width are five hundred so this is our arc it resembles a pie slice it's not starting in the top left corner and ending down here that's the amount of space that we're giving this crate arc function to actually draw an arc it's really an entire circle but only a portion of it is visible let's also set a fill color for this so fill equals what color did we not pick yet let's say green and now we have a green pie slice there's different styles you can do too so we can change that with style equals the default is pi slice that's what we had previously let's change this to chord this will draw a line between these two points and this kind of resembles like a bow like a ball with arrows and there's also just arc where it's simply just a curved line let's change this back to pie slice well because i like pie we can change the starting position of where this arc begins with the option start so start equals 0 by default so there's going to be no apparent change let's adjust this by 90 degrees so this is in degrees so this shifted what is this direction counterclockwise by 90 degrees so 180 would theoretically flip this and now this is on the other side of what we had previously and then 270. all right we can also set an extent so the default is normally 90 degrees but let's change this to 180 and now we have a what is that hemisphere half a circle all right people let's practice by creating a pokeball there's still one more function that we have to cover it's called create oval but we'll do that as we're making this so let's begin by creating the top red hemisphere of this pokeball so that's canvas dot create arc and we're going to set the extent of this to 0 0 500 500 so that this is going to take up the entire canvas and then let's also set a fill color to red so fill equals red we need to change the extent of how far this extends so we'll do that with the extent function so extent equals 180 so that this is a half circle and let's also change the thickness of this outline as well using the width option so width equals 10 would be good and we have a red hemisphere for the top of our pokeball let's work on the bottom half so that is a white hemisphere so canvas dot create arc these are all the same we'll change the fill to white the extent will be the same but we need a different starting position so start equals 180. so this is going to begin at the 180 degree mark so when you combine these both together we get two different colored hemispheres that form a perfect circle now let's create an oval within the center of this pokeball so we're going to do that with canvas dot create oval we're going to set the amount of space that we want to give the circle to be drawn so we'll place this where x is 190 where y is 190 where x 2 or the second x position is 310 and y2 is 310 let's set the fill color next so we do that with fill fill equals white and lastly let's just give this a thicker border so that is width equals 10 to match the width for the two arcs that we have and there you have it we have a simple pokeball all right well that's the basics of the canvas widget if you'd like a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of the canvas widget in python what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create key events in python so sit back relax and enjoy the show welcome back everyone in this video we're going to be discussing at key events we can bind a key event and a function to a widget or a window so that when we press a certain key or do something we can trigger a function to be called that will perform some sort of task for us so we can actually do this by using the bind function so widgets and windows have access to a bind function so when our window or our widget is selected and then you press a certain key or do something then it's going to call a certain function to perform a task for us so there's two arguments within the bind function this takes an event as well as a function name let's say that when we press the enter key we want to call this function to do something so for this event what we type for that is a set of quotes angle brackets and the name of the button so for example if you want to press w to move forward like you're playing a game this would be w a s d there's also up down and then let's say we want to press enter to do something that is actually a return and then we will call this function so let's create a function called do something and let's define this at the top def do something now pay attention to this part we need to set up one parameter for this do something function this needs an event so be sure to include that and it's easy to forget so what do we want to do after we press enter let's just print a message you did a thing and this should work now so let's try it so while this window has focus ability we can actually uh have this respond to events so right now i'm pressing all sorts of keys you can probably hear me right now going crazy on my keyboard but now i'm going to hit enter and it says you did a thing and you can bind all sorts of keys to this window let's say that i want to press q to quit so we'll just replace this with lowercase q so i'm typing all sorts of keys but now i'm going to press q and it says you did a thing kind of like we're quitting the game you can actually have this respond to all keys well almost all of them so to do that you just type in key with the capital k so i can pretty much press on any key then it's going to trigger or call our function kind of like that so one thing that we could do we can display the key event that was pressed so i'm just going to add that here maybe i'll change this message u pressed plus and to display what key was pressed that is event dot key sim i believe that's for key symbol so this will actually display what button you pressed so w-a-s-d here's a unique idea for practice let's say that we want to add a label to our window and we're going to change the text on the label to reflect whatever key that we press so let's create a label label equals label we're adding this to our window and let's change the font as well to something massive like helvetica and a size of 100 that should be good then we need to pack this label so label dot pack then within this function let's turn this into a comment and we're going to use label dot config and we're going to update our text and the text is going to be whatever key that we press so we can do that with event dot key sim so now this label is going to display whatever key that we press so for example w a s d backspace escape up up down down left right left right b a start all right so that's the basics of key events if you could do me a favor and in the comments down below just press f to pay respects so if you want a copy of this code i'll post this in the comments down below but yeah that's the basics of key events in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys all about mouse events in python so sit back relax and enjoy the show hey everyone we're going to be discussing mouse events in python so before we begin we'll need a window so window equals tk followed by window.main loop and in the last video we learned that we can bind a widget or a window so that when a certain event occurs we can call a function so we're going to do the same thing for this video but we have various mouse events that we can cover so we're going to use the window.bind function and this takes two arguments an event as well as a function name so let's define a function let's call it the do something function so do something and we'll need to define this so at the top def do something and remember that we need to set up one parameter for this function the parameter is an event and then we'll just print something print you did a thing okay so there are various mouse events for a left button click within quotes and then within angle brackets a left button click is button dash one so then if we were to click within this window it's going to call our function you did a thing but if i were to right click it doesn't do anything so there are other mouse events too so button two is that scroll wheel not if you scroll up or down but if you press in on it so right now i'm clicking left i'm clicking right now i'm going to press in on the mouse wheel and it says you did a thing button three is a right mouse click so i'm clicking left nothing but i'm gonna click right and that seems to work all right so button one i'm just going to add a note left mouse click button two is the scroll wheel that's if you press in on it and then button three is a right mouse click so did you guys know we can actually get the x and y coordinates of where this event occurred so to do that we type in the name of the event dot x however since we're displaying this along with some text we'll need to convert this to a string so string event dot x then i'll add the y coordinates as well event.y i think i'll just add a comma between these to separate them and we'll change our text so we'll say mouse coordinates all right let's try this again so this is going to give us the coordinates of where we click and right now i'm just left clicking so the top left corner is zero zero well at least close to it not there exactly alright so here's a few other events that we can cover i'm going to copy this we have button release if we were to release a button it's going to trigger our event so right now i'm holding in on the left mouse button but i'm going to let go then it triggers our event if i were to right click and hold it it doesn't do anything but as soon as i let go then our event is triggered we also have enter not to be confused with the enter button just going to get rid of that so that is enter if we were to enter our binded window or widget so if i were to enter it's going to give the coordinates of where i entered this there is also leave so i'm going to say that enter the window and leave is leave the window so if i enter nothing happens but as soon as i leave it gives the coordinates and the last one is motion as long as the cursor is in motion so this one might be good for a game so that is motion where the mouse moved it's consistently giving me the coordinates if i'm moving the mouse but if i were stationary or stop moving it stops all right so that's the basics of mouse events in python if you want to copy of all this code i'll post all of this in the comments down below but yeah that's the basics of mouse events in python hey what's going on everybody it's bro here hope you're doing well and in this video i'm going to teach you guys how we can drag and drop widgets in python so sit back relax and enjoy the show all right people let's just dive into this so we'll need a window and then we're going to be adding widgets to the window so window equals tk followed by window.main loop now you can drag and drop all sorts of widgets but let's just stick with the label because creating a label is simple so let's define a label label equals label we're going to be adding this label to the window and let's set a background color so we can actually see this label pick i don't know your favorite color i'm going to pick red and then i'm going to set a width and a height because normally if you have a label without any text it's really small so let's set a width of maybe 10 and then a height of 5. that should be good and we want to place this label someplace within the window so label dot place and we can pass in some x coordinates as well as y coordinates so x equals zero and y equals zero so that this is going to appear in the top left corner of our window so this is what we have this is our label and we want to be able to drag and drop this label someplace within the window what we're going to need to do is actually bind this label twice but let's begin with just the first binding so in order to bind a widget you type in the name of the widget followed by calling the bind function so this bind function can take two arguments it can take an event as well as a function name so for the function name let's call this drag underscore start but you don't really need to name it the same that i do and for the event that occurs this is going to be a left button click with the mouse so that event is within quotes and within angle brackets button dash one so if we were to click someplace within the label using the left mouse button it's going to call our drag start function but we need to define this so at the top of our program let's define this function def drag start and this takes one parameter the parameter we have is our event so what we're going to do is actually get the coordinates of where we click within this label and we're going to assign these to a new variable or attribute of our label so label dot let's create an attribute called start x equals our event dot x so this is where we click within the label and not necessarily the window and let's repeat the process for y so label dot start y equals event dot y so we're going to have some coordinates of where we click within this label and we can actually use that for our next function so we're going to bind this label a second time so i'm going to copy this line and paste it the second binding let's say is drag underscore motion for the function name and this event is going to occur if we were to hold down the left mouse button and then drag so that is b one dash motion and then we need to define this function so at the top d e f drag underscore motion and this takes our event as a parameter so this part is going to be a little funky we're going to get or create new x and y coordinates so let's begin with x x equals the name of our label or widget label dot w info underscore x this is a function so add some parentheses this will get the top left x coordinate of our label relative to the window that we're in minus label x well labeled.startx plus event dot x all right so we're going to do the same thing for y well we're going to replace x with y for the second line all right so this is the top left corner the x coordinate of our widget relative to the window this is the place where we click within the label itself and this is where we begin dragging our widget to it's a little difficult to explain but if you can find combine combine all of these together you'll get the new coordinates of where you want to drag this component this widget to so we need to replace this widget so label dot place x equals x and y equals y so then when you combine all of these together we have our widget and we can drag it and drop it someplace else within the window now wait a second what if we have more than one widget well with the way that our functions are written now they wouldn't be compatible with more than one widget just this label itself so what if we were to create a second label so i'm going to call the second label just label two so i'm just going to rename them and let's change the background color to maybe blue and i'm just going to place this somewhere else within our window so maybe where x is 100 and y is 100 and we'll need to bind label two as well so make sure to bind label two so we have label one binded it's just called label and the same thing with label two all right let's see what happens i'm going to attempt to drag label 2. the label 1 is moving that's because with our functions we stated we're getting the coordinates and we're storing them within the attributes of label 1 and not necessarily label two so in order to make these functions compatible with all widgets we can actually add one line of code widget equals event dot widget so this is going to get the widget of the event that we're dealing with and we're going to temporarily rename this as widget so now we're going to replace all instances of where we use label and replace it with widget be sure to do the same thing too with drag motion and then we will need to add this line at the top of drag motion so now these functions are now compatible with any widget that we create and we should be able to drag and drop both widgets all right well that's the basics of dragging and dropping widgets in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of dragging and dropping widgets in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can move an image on both a window and a canvas in python so sit back relax and enjoy the show all right my fellow bros i'm going to divide this video into two different sections in the first section we're going to move a widget within a window and in the next section we're going to move an image on a canvas so let's begin by moving a widget within a window so we'll need a window window equals tk followed by window.mainloop and we'll also need to set some geometry for this window window dot geometry let's make this 500x500 500 x 500 and let's take a look okay that should be a decent size let's add a label to this window so i actually have a race car image that i want to use if you would like an image feel free to pause the video and download one what i would like to do is create a photo image from this png file that i have i'm just going to call this my image equals photo image file equals since this is within my project folder i can just list the file name otherwise you might have to list the file path and for me this is called racecar.png i want to add this image to my label not necessary but it'll be helpful for this example i'm going to call my label just a label label equals label i'm adding this to the window and i'm going to set the image to equal my image that i created it's a photo image if you do not have an image that you want to use you can simply just change the background color you could say bg i don't know red oh then we need to place this so be sure to do that label dot place and i'm going to place this in the top left corner that is where x equals zero and y equals zero and then we should have a race car or whatever image you used and a red background you can get rid of the background color if you prefer that's just if you don't have an image to use you can set the background color just for a visual to show you where the label currently is let's set some key bindings for this window and let's add them maybe here before we create the label and our image so let's find the w key for up s for down a for left and d for right so we do that with window dot bind and we pass in an event as well as a function name so we want to tie the w key to a function and we'll call this move underscore up and then we will need to define this so outside of the window let's define move underscore up and this takes an event so we'll place that as a parameter and to move our label up we're going to take label dot place and we're going to place this at some new coordinates x equals the label's current position relative to the window that it's in so that is label dot w info underscore x all right so then for y it's similar y equals label dot w info underscore y but we're going to subtract maybe one all right so this is all we need although this is only going to move up so i'm going to press w and our label our race car or whatever image you used is going to move slowly up i'm going to increase this to 10 so the change is more drastic so now our race car is drifting off into space let's find a few other keys s a and d sad all right so s will be down move underscore down a for left move left and d for right move right we'll just copy what we have here and make a few changes let's begin with move down the only thing we're going to change within here is in place of subtracting 10 from the y coordinate we're going to add 10 and with our race car oh i guess we have to define these so let's do that real quick uh so we have left move left we're going to subtract 10 from the x coordinate and keep y the same and then the same thing for move right move underscore right and this time we are going to add 10 to x and y will stay the same okay now with our image we can move up down right and then left and y stop there we combine these to our arrow keys so up is just up with a capital u down is down these are all capital by the way left is left and then right is right and now i can use my arrow keys to move this image now for this part of the video i'm going to teach you guys how we can move an image on a canvas this time and not just within a window but we'll need a window to begin with window equals tk followed by window.mainloop and we're going to create a canvas canvas equals canvas we're adding this canvas to the window and let's set a width and height for the width let's make this 500 and the height 500 as well so this is an even square and we'll need to pack or place this canvas canvas.pack should take care of that and let's run this and this is our canvas at this step we need to add an image to our canvas and i have an image of a racecar that i want to add so i need to create a photo image from this file so we can do that let's give this photo image a unique name i'm just going to call this photo image to keep it simple photo image equals photo image and i can list the file path or the file name since this image is within my project folder i only have to list the file name and my file is called racecar.png this next step we need to give our image a unique name the image that's being added to the canvas i'll call this my image equals and we need to turn this photo image into an image added to the canvas so we type in the name of the canvas canvas dot create underscore image we first need to list the coordinates of where we want to place this photo image so let's place this in the top left corner that is where x is 0 and y 0 and we need to set the image of the image that we're creating so we can do that with saying image equals the name of our photo image and let's see what we have so far so this image is somewhat cut off in the top left corner we can easily fix that by anchoring our image when we create it so let's at the end add anchor equals northwest so that should fix that problem and we now have our image that we want to use and to move our image we can set some key bindings so we type in the name of the window dot bind and we pass in two arguments an event as well as a function name let's tie pressing the w key to moving up so the first argument is going to be w and the second is going to be a function name so let's say move underscore up and let's find some other keys w for up s for down a for left and d for right we'll need to define these now so at the top outside of the window let's begin by defining move up def move up this has an event as a parameter and let's create the other definitions here so i'm just going to rename these so we have move up move down move left and move right okay now this next step we can use the canvases move function to move an image a certain amount of pixels on the x-axis and y-axis so let's begin with move up we type in the name of the canvas dot and use the move function and this has three arguments the image that we want to use and this image is called my image the one with the race car the next argument is the amount of pixels we're moving this on the x-axis with up we can keep this the same but on the y-axis let's say we want to move this up 10 pixels so that would be -10 and let's repeat the process for move down move left and move right for move down we're going to change y to 10 for move left we'll keep y the same at zero but we're going to subtract 10 and then move right we are going to add 10 to our x's and that should be it so we can move up down right left and if you want to bind these to some arrow keys all we have to do is just change the event so we can bind these to our wsad keys as well as up down left and right and this time i'm going to use my arrow keys up down right and left all right so that's a few of the basics of moving either widgets or images on a canvas or window if you would like a copy of all this code for both examples i'll post both of them in the comments down below but yeah that's the basics of moving widgets and images in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can create some simple 2d animations in python so sit back relax and enjoy the show alright my fellow bros in this video we're going to be animating an image on a canvas we're only going to be moving this image up down left and right feel free to download an image that you want to use i'm just going to use this ufo emoji that i found so we'll need two imports at the top from tk enter import everything that's what we usually have we'll also need to import time as well we'll need a window window equals tk followed by window.main loop we'll need a canvas i'm going to call the canvas canvas canvas equals canvas we're adding the canvas to the window i'm going to create something that's called a constant we're going to create a constant for the width and the height of our canvas so a constant is a variable or value that you don't plan on changing later at all and a common naming convention for a constant is that the name of the constant is all uppercase so i want the width and the height of this canvas to be constants so for the width this is going to be all uppercase it's not necessary to make it all uppercase but that's a common naming convention for the width i'm going to set this to 500 and the height set to 500 as well and for the width of this canvas i'm going to set the width to equal my constant which is 500 and the height to my constant height so the reason that i'm making constants is that we'll be reusing these a lot later in this program so we might as well just declare them now and get it over with so for the canvas we're adding this to the window we're setting the width to our constant of width and the height to our constant of height and we need to follow this by packing this or place canvas dot pack pack to make it simple so we should have a canvas on our window now if you have an image that you want to use we're going to animate it i need to create a photo image from this file it's a png file it's called ufo but yours is probably going to be named something different so don't copy me exactly i need to create a photo image from this i'm going to call this photo underscore image but name it whatever you want this equals photo image and i need to list the file path or the file name since this file is within my project folder i only have to list the file name and for me this is called ufo.png our next step is that we're going to take our photo image and add this photo image to the canvas and we'll also give this image a unique name i'm going to call this my image equals we're going to use the canvases create image function so canvas dot create image there's a few arguments that we need to pass in where we want this image to appear we need a set of coordinates if we want this to appear in the top left corner that is where x is zero and y is zero for the image we're going to set this equal to our photo image whatever you named this and lastly we should anchor this i'm going to anchor this in the northwest corner to keep it simple and we should have our image on our canvas in the top left corner and here is my ufo that's being piloted by a green alien that's waving to me aliens are usually not that friendly unless they're abducting you our next step is to create a while loop so we'll say wow true this will continue forever until we close out of the program if you're looking at the code for a game this might say instead while running running will be a boolean variable that contains either true or false so if this is true while the game is running they're going to continue moving all of the characters on the screen and then if somebody pauses the game or closes out of the game then they'll flip this running variable to false but to keep things simple we'll just say wow true but that's something that you might see what we'll want to do is get the coordinates of our image within the canvas and this will return a list of coordinates so let's create a list called coordinates so coordinates equals canvas and we can use the chords function to get the coordinates i guess that's short for coordinates and we're getting the coordinates of my image so we'll pass this into this function and then let's print this just to see what this returns we'll print coordinates okay now to update the window after each cycle of this while loop we can use the update function of our window so window.update will also have this thread sleep for let's say 0.01 seconds so time dot sleep 0.01 one so here's a quick rundown of what we have going on so far within this while loop we're going to first get the coordinates of where our image is located we'll print the coordinates to the console window this part isn't required but it's going to help us for learning purposes we'll update this window for any changes and then our thread which is in charge of running the program is going to sleep for i believe that's a hundredth of a second so when we run this our image is staying in place and we know that our while loop is running because it's continuously printing the coordinates the first number is the x position the second number is the y position and now we're going to give our image a speed or velocity i like to call it velocity and in fact i'm going to give this image two velocities one for how fast this image is moving on the x-axis and another for how fast it's moving on the y axis so i'm going to create two variables one called x velocity and i'm going to set this equal to one and y velocity and i'll set this to one as well okay so what we need to do now is update the position of our image so let's do that before we update our window so i'm going to type in the name of the canvas and use the move function this move function takes three arguments what you want to move i want to move my image my ufo and how far i want to move this image on each axis each coordinate so what i want to do is update the x velocity the x position of my image so i'm going to pass in my x velocity variable and then y we'll just keep the same for now so we'll just say zero so after each iteration of this while loop my ufo is going to move one pixel to the right and it's just going to go off into the void forever and now if we replaced x velocity with zero and for y we set this to our y velocity this image is now going to travel down and it will continue into the void forever and then if we combine both of these together we're going to move diagonally down and to the right so what if we want this image to bounce off the walls we're going to add some if statements we're going to begin by just having this image bounce off the left and right walls for now let's set y velocity to zero so that this image is only moving left and right so before we move this image we'll add an if statement we're going to check to see if the x position of our image is either greater than the width of the canvas or if it's less than zero so we take our coordinates and we're going to get the first element from this list so that is zero that is x the x value if coordinates at element zero is greater than or equal to the width of this window and this is a constant so we can just place that here if coordinates well x within our coordinates is greater than or equal to width or coordinates at index 0 is less than 0 then we want to reverse the direction or flip the velocity so we want to change our x velocity and make this a negative number one easy way to do that is that we can take x velocity equals x velocity times negative one or another way of writing this is just to say x velocity minus negative velocity now what ends up happening is that when this image reaches the right border it's going to bounce back however it only bounces back after it reaches the top left corner of the image we need to factor in the width of the image as well so we're going to create two new variables and let's do this right before the while loop we'll want to determine what the height and the width are for our photo image that we have so this is what we're going to write let's call these two values image underscore width and image underscore height so we need to determine what the width and the height is for our photo image and there is a function to do that type in the name of the photo image dot and there is a width function and the same thing for height photo image dot height and then we can reuse these so i'm just going to add one line to the sift statement if the x position of our image is greater uh greater than or equal to the width of our window minus the width of our image and i'm just going to put these within parentheses just to keep these more organized and what ends up happening now is that when the right portion of our image hits the right wall it's going to bounce off and let's do the same thing for our y velocity we're going to replace coordinates at index 0 with 1 and change that here as well replace with with height and this is image underscore height and we're going to change the y velocity this time and when we move this image let's also add the y velocity and now our image is just going to bounce off the walls forever but it's kind of predictable since we set x and y to equal one now let's change the speeds to kind of spice things up let's say for the x velocity this is three and y velocity this is now two this is going to go in a completely different direction so you can mess with the speeds however you want so guys how about we add a background image to this well because we can i'm going to reuse this image of space from my java video on this same topic i need to create a photo image from this and i'm going to copy what we did for our normal image that we were moving and animating so this is called space.png well that's the name of my file and i'm going to give this image a different name maybe i'll call this background underscore photo and then i'm going to add this photo to the canvas and i'm going to call this a different name i'll just call this background all right so our window should have a background now and then our image moves on top of the background so make sure you add and create the background before you add any other images otherwise the background might overlap your image alright so that's the basics of some simple animations in python if you want to copy all this code i'll post all of this in the comments down below but yeah that's the basics of some animations in python hey what's going on everybody it's your bro here hope you're doing well and in this video i'm going to teach you guys how we can animate multiple objects in python so sit back relax and enjoy the show welcome back my fellow bros in this video we're going to be animating multiple objects within a window more specifically we'll animate some circles and each of these circles will have their own characteristics speeds and directions so we'll need two imports to begin from ck enter import everything we'll also be importing everything from the time module as well we'll need a window window equals tk followed by window.main loop i'm going to create two constants one for the width and one for the height let's set the width equal to 500 and the height equal to 500 as well we'll create a canvas and we'll be animating the circles that we're going to create on the canvas so let's create a canvas canvas equals canvas we're going to be adding the canvas to the window and we'll set the width of our canvas equal to our constant width which is 500 and our height equal to our constant of height which is also 500 and we will add this canvas by using the pack function canvas.pack here's our canvas and we're going to be creating multiple circles let's pretend that they're all different sports balls like a tennis ball baseball volleyball bowling ball they'll all be bouncing off of the borders and once each of them encounters a border they will change direction since we're going to be creating multiple objects i think it's best if we do this with another class so let's create another class i'm going to go to file new python file and let's call this class ball and click python file and we need to define this class class ball and we also need a constructor for this ball class we can create one with def two underscores i-n-i-t two underscores again and we can set up the parameters of what we want to receive if we were to create a ball object so let's pretend that we're going to be creating a volleyball to begin with so let's call this ball volley underscore ball equals ball and we'll pass in some arguments so let's set up the parameters first what do we want to receive one we want to receive our canvas so that we can actually draw this oval we can draw this ball we should also have an x and y position a diameter x velocity y velocity and a color all right so when we create a ball like a volleyball we're going to pass in whatever the parameters require so we need a canvas x y a diameter an x velocity y velocity and a color so within the constructor for the ball we're passing in our canvas it's kind of like what we do with widgets we're specifying what we're going to be adding this widget to we're going to be adding this ball to our canvas we also need x y and a diameter let's make this simple by setting x and y to both zero for the diameter let's set this to maybe 100 and we also need an x velocity and y velocity let's set this both to one and a color so let's pass in a string like white let's head back to our ball class and finish assigning all of these arguments that we're going to receive the first step is that we'll say self dot canvas equals the canvas that we receive when it's passed to us as an argument our next step is to draw this oval draw this ball and we'll say self dot image equals canvas dot create underscore oval and with creating ovals we can pass in x y and with circles the diameter is equal for both the width and the height so we'll pass in our diameter twice and lastly a fill color and we'll say this is equal to the color that we receive which is white we're going to set the x velocity and the y velocity this is related to the direction that it's initially going to head in so self dot x velocity equals the x velocity that we receive and we'll do the same thing for y velocity self.y velocity equals y velocity now since this is in another class we need to import this class from ball import everything and you can see that this red underline went away so let's see what happens now we have our volleyball but it's not currently moving so that's the next step so let's create a function within the ball class called move that we can call upon so we'll do this after the constructor cef move and this will take self as an argument the first thing that we should do is get the coordinates so we'll say coordinates and this is a list coordinates equals self dot canvas dot c o o rds and we'll pass in self dot image and we will print these coordinates just to see what's here all right now we'll create a while loop within our main class so let's add that near the end and we'll just say while true so while this is running let's move our volleyball so volleyball dot move so this will call the move function of our volleyball and then we will update the window window dot update so that this refreshes and we will sleep for maybe a hundredth of a second time dot sleep 0.01 but you can put whatever you want here so this is going to at first just print the coordinates of this ball so it's not currently moving and this time with our list we have four coordinates zero zero that's the top left corner and 100 100 that's the bottom right corner so this time we have four coordinates that we have to deal with the top left corner as well as the bottom right corner our next step is that we should move this image self dot canvas dot move what object are we going to move we're going to move self dot image and in what directions self.x velocity as well as self dot y velocity now our ball is going to move across the window and it right now it's displaying all of the coordinates we don't have any bounds set up so it's just going to continue into the void forever so we should set up some if statements to check to see if one of the borders touches one of the walls of the window if so it's going to change direction so let's check to see if the left or right side of our ball touches one of the left or right borders so let's write an if statement if and then let's take a look at these coordinates if coordinates at index 2 that is this one 0 1 2. so this is the bottom right corner with these two sets of coordinates if coordinates at index 2 is greater than or equal to i'm going to put these within parentheses self dot canvas and we need to get the width of the canvas one way which we can do that is to use the w info underscore with function so this is going to get the width of the canvas and then let's add one more thing or coordinates at index zero is less than zero so if this ball touches the left or right border we want to change direction so we can flip the x velocity self.x velocity equals negative self x velocity and let's do the same thing for the top and bottom borders so let's copy what we have and we'll replace coordinates at index two with three and we'll also replace w info underscore width with height and coordinates at index one change self dot x velocity with y velocity same thing here as well alright and that should be everything let's try it so let's see if this ball actually bounces off the borders which it does pretty cool so that's everything we need to do within our ball class now if we need to create multiple balls we can just construct them so let's say this time we would like a tennis ball i'm going to name this volleyball as tennis ball and let's make the diameter smaller like five but we'll make this a lot faster like for the velocity let's say four and three and the color let's make this yellow and we also need to call the move function of this tennis ball so within the while loop tennis ball dot move and then we should also have a tennis ball moving across the screen in a different direction now technically we don't need to print the coordinates but i tend to do that just for teaching purposes to better demonstrate all of this now our ball class is acting as a blueprint for how balls should be created and the behavior that they exhibit and if we need to create a ball we can just come up with a name for the ball and call the ball constructor to take care of that for us kind of like what we've been doing with widgets so all we need to do to create another ball is come up with a unique name for the ball and instantiate it using our ball class that we created so this time let's create a basketball i'll rename this as basketball and we'll pass in different arguments based on how we want to customize this unique ball so for the diameter let's say this is now 125 and the x and y velocity let's set this to something very fast like eight and seven and with the color let's change this to orange and make sure you also call the move function so basketball dot move and we should have a basketball moving across the screen all right everybody so that's the basics of animating multiple objects in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's how to animate multiple objects in python hey what's going on everybody it's ibro here hope you're doing well and in this video i'm going to teach you guys how we can create a clock program in python so sit back relax and enjoy the show all right my fellow bros in this video we're going to be creating a clock gui program so we'll need a few imports from tk enter import everything and from time import everything as well we'll need a window window equals tk followed by window.main loop and in this program we're going to be creating three separate labels one for the time another for the day of the week and another for the date so let's begin with just displaying the time and work on the day of the week and the date later so let's create a label for the time called time label equals label we're adding this to the window and let's set the font because we can i'm going to choose maybe ariel and then a size of 50 so that this is somewhat large i'm going to change the foreground color that is the font color and i will pick a hex value of green so that is 0 0 f 0 0 but feel free to pick whatever color you want and i'm also going to set the background color and you can pick a hex value or a color name i'm just going to say black and then i'm going to pack this label time label dot pack now we're going to call a function and we'll call this update and we'll define what this does after every second has passed we will use a recursive function to keep on updating the time every one second or so so let's define what this function does def update there is a function within the time module called strf time which we can use to return the current time and format it however we want so we're going to actually place this within a string variable and we'll call this time string and this function is strf time i'm actually going to go to python's website just to give you an example of how this works here we are on python's website and this is the strf time function and this converts a tuple representing a time as returned by gm time or local time to a string as specified by the format arguments so when we call this function we can pass in directives as arguments based on what we want to display if we want to display the current time there is a few directives that we can pass in so let's say that we want a 12 hour clock as represented by a decimal number between 1 and 12 well we would pass in percent i as an argument if we want the minutes that would be right here percent m and if we want the seconds that is percent s so we're going to pass in these directives as if they are arguments so within this function we'll pass in those format specifiers or directives so i want percent i followed by percent m and percent s alright uh but these also have to be within quotes so don't forget that because i just did okay this will display the current time oh then we also have to update our time label so time label dot config text equals our time string because remember that this returns a string of text text equals time string so this will display the current time and right now it is six in the morning or so however we just get one long jumbled number so it would be a good idea if we separated some of these numbers so within our strf time function i'm just going to add some colons to separate these values and this will display the current time it is currently 6 46 in the morning let's add am or pm to the end of this so the directive for that is percent lowercase p 6 46 am now how do we update this label every one second to reflect the current time well that's a good question and i'm glad you asked it so we're going to use the time labels after function we pass in a delay and then a function that we want to call after that delay so let's say we want to call this function update every 1000 milliseconds or one second so we'll pass in the delay as an argument 1000 milliseconds and the function that we want to call and we're going to perform what is known as a recursive function we're going to call a function within itself so after 1000 seconds we're going to call update again and it's going to repeat the process it's going to return the time and format that time and update our label with the new time so what ends up happening now is that our clock is going to update every 1000 milliseconds now let's add a few other labels let's say the day of the week i'm going to copy what we have here and let's rename this as day label but i probably don't want this to be the same size for the font let's say ink free because i like that font and a size of maybe 25 and i'll get rid of the coloring it's the same process as before really so let's replace time string with day string the directive for strf time to display the day of the week is percent a and we're going to replace time label with day label text equals day string and this will display the day of the week and it is currently wednesday and if we want to display the current date we can create a label and we'll call this date label and i'll make the font slightly bigger maybe 30. we'll copy what we have for our day string and rename this as date string so we have a few options for the date i want to display the name of the month the day and then the year so that would be percent capital b percent lowercase d i'm going to add a comma to separate the day and the year and percent capital y and then i want to set the text of my date label to my date string so that this will now display the current date there's just one quick change that i think we should make right now we have three different labels a time label a day label and a date label and right now we're using the after function of the time label so since we have all of these different labels i think we should replace time label with our window because our window has an after function as well so that after 1000 milliseconds has passed we can update the time the day of the week and the date all right so that's the basics of creating a simple clock program in python if you want a copy of all this code i'll post all of this in the comments down below but yeah that's the basics of creating a clock in python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to show you all how we can send an email using python so sit back relax and enjoy the show oh a quick note for you all you're going to need a gmail account to sign into as well as your username and password so once you have those set you're ready to begin all right let's begin by importing the simple mail transfer protocol library we'll need a couple variables to hold strings let's say we have a sender a receiver a password a subject for your email as well as a body for the email okay sender is going to be you sending the email so enter your email in here i'm just going to make up one you at gmail.com actually sender would be better i would say let me change that sender at gmail.com let's say we have a receiver this is who you're going to send the email to receiver gmail.com don't actually enter in these emails use your owner the person that you intend to send the email to for your test because these will probably not work i'm assuming then enter the password for your gmail account so let's say password123 and a subject uh let's say python email test and a body what do you want to say within your email i wrote an email okay so that should be good so remember that you're going to want to change these to your actual gmail account and you'll want to send it to a valid email address too and make sure that you use your password for your gmail account okay now we're going to create a header for our email and the syntax on this is a little strange we're going to say message f and then triple quotes so what this triple quotes is is that a triple quote string can span multiple lines of text so the first thing we'll enter is from within our header from and then since we're using an f-string we can insert a variable at a given location when we insert a pair of these curly braces so from will be sender the next line to colon receiver then the next line subject colon subject this will be the title of the email then i'm going to add a new line and then insert the body and if you want you can give yourself a name when you send this email let's say maybe snoop dogg and if there's somebody you want to send the email to and give them a name you can say like nicholas cage but these aren't necessary okay so we have our header completed let me just add a note that this is our header okay we're going to create a server object server equals smtplib.smtp there are two arguments the first is smtp the other argument is the port number and that is going to be 587 that is the default mail submission port 587 now we're going to take our server object and start tls transport layer security okay now we need to log in so server dot login we will pass in our sender email that's us as well as our password password and let's print logged in we'll eventually place all this within a try and accept block later all right and then to send an email type server dot send mail and we pass in our self sender receiver and our message sender comma receiver comma message and let's print a confirmation print email has been sent now if you were to run this program you may encounter this error smtp authentication error that either means your username password combination was not correct or you need to turn on the less secure app access on your gmail account which you can find here however i would recommend turning that back off when you're done with this program just because your account will be less secure and i'm not liable if you get hacked hey you know what let's place this code within a try block we will try all of this code and then if we encounter this exception we can catch and handle it properly so we will try these four lines of code and we will handle our exception of smt lib dot smtp authentication error that means we could not sign in so let's print unable to sign in so i'm going to run this one more time and instead of getting that ugly error we should get a simple message that says unable to sign in once you have the proper username password combination for your gmail account and if you need to set less secure app access to on but make sure that you turn it back off when you're done with this you should be able to send an email let's try it logged in email has been sent here is a snapshot of the email that i received i blurred out my actual email because i don't want it public because some of you guys are weird so we have our sender our receiver and i gave myself a nickname of snoop dogg that's why it says snoop to nicholas the receiver but you don't actually need a name for these as long as you have the sender and receiver fields filled in you should be good we have our subject python email test as well as our body i wrote an email well everybody that's how to write and send a simple email using python if you would like a copy of this code i will post this to the comment section down below but yeah that's how to send a simple email using python hey what's going on everybody it's you bro hope you're doing well and in this video i'm going to show you all how we can run a python file using command prompt so sit back relax and enjoy the show hey y'all in today's video i'm going to show you all how we can run a python file with command prompt so first we'll need a script to work with let's just make a very simple program let's say print hello world and then maybe we will ask for some user input name equals input what's your name and then at the end we will print the word hello plus the user's name okay so let's save this to a place that will remember perhaps my desktop now to save this file to a separate location go to file save as you can pick a name for this python file then to directory click these three dots and pick a location you want to save this to to make this easy i'm going to save this python file to my desktop and then click ok so the name of this python file of mine is hello underscore world dot py then click ok now our second step is to open command prompt to open command prompt just search for cmd if you're using mac i believe it's terminal step number three is that we need to navigate to the directory that contains our python file i saved this python file to my desktop so if you right click on your file and go to location you can just copy this address now within command prompt type cd to change directory space and then paste that directory that contains your python file hit enter and for the last step we need to invoke the python interpreter by typing python space and then the name of the script and the name of my script is hello underscore world dot p y hit enter to run the script hello world what is your name bro hello bro so that is how to run a python file with command prompt i will post all of these notes to the comments section down below and well yeah that's how to run a python file with command prompt it's you bro hope you're all doing well and in this video i'm going to show you all how we can use pip for python to download packages and modules so sit back relax and enjoy the show alright people pip for python pip is a package manager for packages and modules from the python package index if you're using python version 3.4 or above pip should already be installed if you're using a python version below 3.4 one option is that you can always update your version of python just click download open when done go to customize installation make sure that pip is checked go to next and add python to environment variables then install now to use pip open up command prompt and type pip for a help menu all sorts of different general options and commands will appear if you need to check your version of pip type this command and here's a cheat sheet that i wrote so to check the current version of pip type pip dash dash version enter and currently the version that i'm using is 21 if you need to upgrade pip use this command pip install dash dash up grade pip mine should be the latest version yeah requirement already satisfied and if you need a list of installed packages type pip list so here's all of the packages that i currently have installed some of these you might recognize like numpy pie game pie installer those are just a few to check to see if any of your packages are outdated type pip list dash dash outdated and this might take a second here are four packages that are outdated on my computer babel pi game pi tz and setup tools if you need to upgrade one of your packages type pip install the name of the package let's say that i would like to update pygame then dash dash upgrade i just realized that in my notes i'm missing updated package so i just added that here now you can see that pie game has successfully updated and let's just check to see if it has by using pip list outdated pip list dash dash outdated and pi game is no longer in here so it is up to date and if you would like to install a package type hip install and the name of the package you would like to download let's say i would like to download pandas pip install the name of the package in this case pandas two valley boring minutes later and it's done so i should now have pandas installed and let me check pip list and here it is i have successfully downloaded the package of pandas so those are a few commands for pip and if you're interested in downloading more packages head to python's package index on second thought i should probably show you all where that is python's package index is located at pipi.org and you can do a search for all sorts of different projects and packages so everybody that is pip4 python i will post my notes in the comments section down below and well yeah that's how to use pip for python hey what's going on everybody it's bro hope you're doing well and in this video i'm going to show you all how we can convert a python file to an executable so sit back relax and enjoy the show here's a quick disclaimer before we begin windows defender and other anti-virus programs may prevent your executable from running but if you head to the settings section of your anti-virus you can disable that so that your python file can run also please be sure that pip and pi installer are both installed and up to date i have a separate video on that if you're interested now the program that i'm going to be converting to an executable has a gui portion to it i created a clock program in a previous video so i'm going to turn this clock program into an executable now i recommend creating a new folder on your desktop just because this process is normally somewhat messy so we'll create a folder to contain it all now copy any relevant python files and or images and paste them to within this folder if you have an image that you would like to set as an icon for your executable i recommend moving that to the same folder as well our next step is to open command prompt and we need to change the directory of command prompt so that it's pointing to that folder that contains our python file so on your python file right click on it go to properties and copy this location and in command prompt to change directory type cd space and then paste that location now here's the cheat code to convert a python file to an executable make sure that pi installer and pip are installed and both up to date so type pi installer dash capital f to make all of this one file if you need the terminal window in your program then omit this next part since i'm running a gui application i do not need that terminal window so to remove that window type dash w if you have an icon that you want to set type dash i and the name of your icon however it should be an ico file so if you have some other image that you would like to convert to an ico file here's how if you need to convert an image to an ico file you can just google convert to ico but one website that i commonly use is icoconvert.com just pick a file to upload so choose file i'm going to convert this png file of an alarm clock upload it there is a bunch of different settings you can use convert ico and then download my icon and once your ico file is downloaded i will drag and drop it to my folder and i will rename this let's rename this as icon dot ico and here's that cheat code one more time pi installer dash f dash w if you do not need the terminal window dash i if you would like to add an icon the name of your icon it should be an ico file followed by the name of the python file and mine is named clock.p.y then hit enter alright looks like building our executable has completed successfully so open that folder back up your executable is located within this dist folder i would recommend just dragging and dropping it to your desktop and we can get rid of this old folder but close out a command prompt and by clicking on this executable this executable will now run my python program well everyone that is how to convert a python file to an exe file i will post my notes to the comment section down below and well yeah that's how to convert a python file to an executable what's going on everybody it's you bro hope you're doing well and in this video i'm going to show you all how we can create a basic calculator using python so sit back relax and enjoy the show let's create a calculator after importing tkinter we'll need to define three separate functions our first function will be named button press and there is one parameter which we will call num we're not going to fill this in quite yet we'll get back to it later we'll use pass as a placeholder we'll also need an equals function to calculate our expression and a function to clear our calculator okay that's it for our three functions let's create a window window equals tk and at the end of our program we'll write window.mainloop let's set a title window dot title calculator programs good but make sure you spell title right and let's set a geometry of 500 500 should be decent now we're going to create a string named equation text equals a set of quotes this will effectively be empty for the time being and we'll need to create a string var and i will call this equation label equals string var let's create a label label equals label we're adding our label to our window i will set our text variable equal to our equation label you can pick a font if you wish i'll set the background color equal to white a width of 24 and a height of two and we need to finish this by using label dot pack and we should have a blank label within our calculator this will display our numbers that we're entering in or our expression okay this is the tedious part we have to create all of the buttons and i think we should place these all within a frame frame equals frame we're adding our frame to our window frame dot pack now let's create button one we'll do some copying and pasting later so it's not as tedious so button one equals button we're adding our button to our frame i'll set the text equal to 1 the height equal to 4 and the width equal to 9 and a font size of 35 okay we'll need a command command equals i'll write a lambda function here lambda we will call button press i think i'm going to put this on the next line just so it's easier to read button press and we will pass in the number one and we need to add our button to our frame button one dot grid and i'm going to set a row equal to zero and a column equal to zero and let's just test it okay let's add the other buttons i'm going to copy and paste everything that we have for button one and change button one to button two set the text equal to two pass into to button press and for the row and column i'm going to set the column equal to one but keep row the same okay button three it's gonna be the same process really so text equals three button press three row zero column two and button four text equals four button press four column actually let's set this to row one column zero and i need to change that too okay let's just double check this okay button five so button five text equals five button press five and let's set column equal to one okay number six i told you all this is going to be tedious okay so row one column two button seven okay so row two column two actually let's change that to column zero much better okay button eight eight eight eight eight row two column one number nine row two column two and lastly zero so button zero text equals zero button press pass in zero and this will be row three column zero okay not too bad now let's fill in some of the symbols so we need plus i'm just going to rename this as plus the text will equal the plus sign put that within quotes and button press will be plus oh and we should probably put this in a row and column so let's say row 0 column three so it should be on the right hand side here okay we need minus let's change plus to minus and place this at row one column three we need multiply that is an asterisk row two column three and divide that is a forward slash row three column three i promise we're near the end of creating these buttons we'll need an equal sign let's say equal equal text is the equal sign and our command is going to be equals the function and this will be row 3 column 2. we need a decimal let's change the text to a decimal row three column one okay and lastly we just need a clear button let's put this at the bottom so clear clear let's set the text equal to the word clear and the command will be our clear function and i think i'm going to pack this at the end but let's change frame to window okay let's check out all these buttons okay not too bad i think i'm going to change the width on our clear button so it's a little bit wider let's change the width to 12. that's a little bit better okay let's fill in some of these functions let's start with button press we're going to state global equation text then our equation text is equal to equation text plus we're converting whatever number or symbol that we receive to a string and our equation label which is a string var will be set to our equation text and let's test this so we can type in any combination of numbers or symbols okay let's work on our equals function next so let's say global equation text total equals eval now eval will parse the expression that we pass in equation text and our equation label will be set to whatever our total is and if we want to reuse our total let's set our equation text equal to total 2 plus 2 equals four minus three equals one times five equals five divided by two equals two point five now what if we divide by zero well we'll run into that ugly zero division error so let's write our code within a try and accept block so i'm going to indent some of this and let's write try all of this code and we will catch a zero division error exception so accept zero division error and i will set our equation label set let's say arithmetic error equation text equals a set of quotes okay so we should be able to catch this exception now five divided by zero equals arithmetic error now what if we have a syntax here like we type in just a bunch of symbols and hit equals we'll probably want to catch the syntax error as well so let's write an additional accept block before zero division error or after i guess it doesn't matter accept syntax error let's change arithmetic to syntax and we can keep equation text the same so now our program won't crash if we type in a bunch of symbols syntax error now let's work on the clear button so that is within the clear function so we will set global equation text equation label dot set to a set of quotes to effectively clear it and our equation text equal to a set of quotes as well and that should be it for this program let's run this one last time let's say 3.14 times 2.1 equals 6.594 divided by 2.1 equals 3.14 minus one i'm just making up numbers here plus ten equals twelve point one four and let's clear this and start again one plus two plus three plus four equals ten i think that's good enough all right everybody so that's how to create a basic calculator in python i will post all of my code in the comments section down below if you would like a copy for yourself but yeah that's how to create a basic calculator using python hey what's going on everybody it's your bro hope you're doing well and in this video i'm going to explain how we can build a basic text editor program in python so sit back relax and enjoy the show okay people let's create a text editor here's all the different imports that you'll need and we'll begin by defining all of the different functions that we'll need so let's say we have a change color function to change the color of our font and for all of these functions i'm going to write pass as a placeholder so we have change font and this function will accept a varying amount of arguments so we'll use that args keyword we will need to open a file new file open file save file cut copy paste yeah there's a lot of functions here about this is for an about section and lastly quit so how many do we have one two three four five six seven eight nine ten ten functions let's create the main window that we're gonna work with window equals tk and at the very end window.main loop okay so let's create a title for this window window title notepad program i guess or maybe text editor program would be more appropriate text editor program okay and we will need a file to work with and i'll declare that now file equals none we'll need a window width and height window with equals 500 is good and a height okay so let's attempt to center this window because right now it just appears to the side so our next step is to get the screen width equals window dot w info screen width and i'll copy this for screen height okay so we need to figure out how much we're going to move our window on the x and y axis so let's say x equals screen width divided by 2 minus window width divided by two and we're going to cast all of this to an end so add an inch cast around this let's copy this do the same thing for y except this will be screen height and window height okay let's set the geometry for the window window geometry i'm going to use a string format method so let's say these will be placeholders for our values so we have window width for the first value window height x and y so this should be near the middle cool we're going to create a string var variable to hold the font name font name equals string var and pass in your window and you can set this to what do you want your default font to be so let's say font name dot set and then pick a font i'll use ariel i think let's create a font size string bar as well we're going to add this to the window and we can set a default size perhaps 25. okay let's create a text area text area equals text we're adding this to the window i'm going to set a font equal to font name dot get the name of the font that we want to use will be the font that we set within our font name string var so now we'll use a size of font size dot get font size dot get okay now we need a scroll bar scroll bar equals scroll bar writing this to our text area so pass that in and i'm going to configure my window using grid row configure this will allow our text area to expand but we're going to set a weight equal to 1 so that it doesn't back expand and then we need column configure okay and text area dot grid i'm going to use the sticky keyword and this will stick north plus east plus south plus west so my text area should take most of the window this is some sample text hooray so it goes down to the next line once it runs out of room on one line unless you resize the window which is exactly what we wanted let's create a scroll bar while we already created it we just have to add a few details to it so that will be near the bottom and why don't we say scroll bar dot pack side equals right fill equals y and then we just have to configure our text area with the scroll bar so text area dot config y scroll command equals scroll bar dot set so that should work but let's test it to be sure okay i'm just going to type a bunch of f's okay look at that our scroll bar works cool okay let's head to this portion and we'll create a bunch of buttons well a button an option menu and a spin box for the font color the size and the font style so i'm going to place all of these different widgets within a frame frame equals frame add it to the window and then i'm going to use frame dot grid okay let's create a color button to change the fonts color color button equals button i'll add my button to my frame i'll set the text of the button equal to color and i will associate a command of change color which we have already defined at the top where is it at the top here change color and then actually that's it for this portion so then we need to add this button color button dot grid i'll set the row equal to zero and the column equal to zero so let's be sure that this appears make sure you spell grid right okay and we have a color button but this button doesn't do anything so let's head to the change color function within the change color function we're going to say color equals color chooser dot ask color and you can set a title to pick a color or else you don't technically need a title and then text area dot config oh i should probably print this color so let me do that um i'm just gonna explain something here so this color is going to be i believe a tuple so let's print it so let's say that i would like white okay so we have a tuple we just need one of these values not both of them so i'm going to say text area dot config foreground equals our color but we do not want to assign a tuple to our color we just need one of these values so let's say i would like this hex value so i'm going to say at index 1 and let's try it color perhaps i would like my text pink for some reason so we're going with pink this is some text i suppose and we can change this back too by using this color button now i would like blue and we have blue text okay so that is the change color function i'm going to minimize this because we do not need it anymore okay we're going to change the font next so head to the portion of our code right after the color button and we'll create an option menu to list all of the different fonts available to us so let's say font box equals option menu we're adding this to our frame we need to set a variable a string var so that will be our font name that we declared up here now here's a trick to add all of the fonts as options to our option menu we can use the unpacking operator which is an asterisk followed by font dot families and then call this function so this will return all of the different fonts available to us and we just need to set a command and when we use our option menu we'll call change font and we need to add our font box to our grid row equals zero and column equals one so this should be on the right hand side of our color button yeah it's going to look something like that and you can see the default is arial that we set and we can change it to something else like comic sans or whatever uh however it's not going to change it quite yet so that'll be the change font function before we fill in the change font function there's another widget that's going to share the same command of change font so we should create that next so our next widget is a spin box which i will name sizebox this will be in charge of increasing or decreasing the font so size box equals spin box we're adding the spin box to our frame and we'll set a range so from underscore you have to add that underscore it's kind of weird this is the range of our spin box for the font size from 1 to let's say 100 the text variable will be font size and our command equals change font so when we use our spin box and call this command of change font it's going to pass in our font size as an argument whereas with option menu it doesn't pass any arguments that's why with our change font function we're accepting a varying amount of arguments because one's going to pass in an argument and the other isn't and we just need to add our spin box so that would be size box dot grid row equals zero and column equals two so we should have a spin box right on the bottom and it's set to 25 that was our default for our font size string var which we set as the text variable okay so we can fill in this function of change font now which will apply both to our option menu and our spin box so that is all the way at the top within the change font function we're going to take our text area dot config set the font equal to font name dot get and the size will be size box dot get and that's it for this function i'll minimize it for now and let's test it this is some sample text hey how you doing good looking okay so let's change the font uh let's pick comic sans or whatever you want and we can increase or decrease the size and we can change the color how about red this time all right nice now let's add a menu bar at the top so we can save this file or open a file or create a new file and some other stuff on second thought i'm going to move these two last lines of code to this section here where we create our scroll bar just so that it's more organized okay so at the bottom let's create various drop-down menus so we'll need a menu bar to begin with so let's say menu bar equals menu we're adding this to our window make sure that's capital by the way and window dot config menu equals menu bar so we'll create a file menu edit menu and a help menu so let's begin with the file menu to add to the menu bar file menu equals menu we're adding this to our menu bar and set a tear off equal to zero we'll need a cascade for it to actually be a drop down menu so that will be menu bar dot add cascade label equals file comma menu equals file menu let's see if anything appears yet yep so we have a file menu but there's nothing to drop down yet so we need some options well commands technically file menu dot add command label equals new and the command will equal our new file function actually i'll put these together okay so let's copy this and paste it we have open the command will be open file we have save the command will be save file and i'll add a separator file menu dot add separator and lastly we will have exit command quit okay let me show you what this looks like so here's our drop down menu that separator is this bold line going across so if i was to remove this then we wouldn't have that bolt line you can keep it in or get rid of it do whatever you want and this is the tear off so i'm going to remove the tear off and you get this like tear off line at the top i guess it's the default i usually don't like it so i set tear off equal to zero so that is our file menu let's work on a edit menu edit menu equals menu menu bar make sure that's capital two tare off equals zero we'll need a cascade menu bar dot add cascade label equals edit menu equals edit menu edit menu dot add command label equals cut to cut some text command equals copy actually that's cut my bad okay next is copy so let's copy this and paste it cut copy we have paste command paste all right let's take a look oh make sure you spell label right okay there we go okay so we can cut copy and paste and lastly we should have a help menu help menu equals menu menu bar tear off equals zero i think i'll copy this for my cascade so menu bar dot add cascade help menu equals help menu what we'll be doing for a command is that we'll be creating an about section that will bring up a pop-up window if you need to display any like help information or anything uh so let's say about and the command will be about okay let's take a look so we have help and we'll have an about section that will tell you more about this program but we need to work on some of these functions let's head to the quit function this one's fairly easy this is found within the file menu window dot destroy that will close out of the window so go to file then exit to exit the program we don't need it anymore so let's minimize this okay let's go to the about function let's bring up a message box show info this first argument is the title so let's say about this program and the text will be whatever you want to tell the user about this program this is a program written by you okay so we should have a pop-up window when you go to help then about about this program this is a program written by you the next function is the paste function so we can paste some text text area dot event generate and the event is going to be within quotes and double angle brackets paste let's copy this and change paste to copy and then cut okay so we should be able to cut copy and paste hey how's it hanging okay let's highlight this edit copy let's move down to the next line and paste and we should be able to cut as well edit cut nice head to the new file function and we'll set the title of our window to maybe untitled until we save something so untitled and i need to delete any text within our text area text area dot delete and we need to set a range so this has to be a floating point number the first character until the end let's try it so i'll write some sample text and we are going to go to file new that changed the title and it deleted our text so that is the new file function let's work on open file we are now within the open file function and we'll say file equals ask open file name so we have a default extension if you would like one default i think i spelled that wrong extension equals let's say a txt file comma what are the accepted file types i'll set this equal to all files comma and then we need asterisk dot asterisk for all file types as well as text documents so these are what is accepted when we look for a file so we have either all files or all text documents text documents comma asterisk dot txt okay so then let's try some code we'll set our window title equal to os dot path dot base name of our file so that we will change the title of the window to match whatever the file is that we opened then let's take our text area delete what's currently here from one until the end take our file use the open function open our file and read it so pass in our text area dot insert beginning at index of 1.0 file dot read that you can catch any exceptions to i'll just write accept exception but it's better to name specific exceptions i'll just print couldn't read file and we should close our file at the end within a finally block finally file dot close we'll need a sample file to read so i'm going to create a new file on my desktop i'll call this test.txt and let's write something whoa you can actually read this awesome okay let's save close out of it add run our program file open test.txt open whoa you can actually read this awesome nice so we know that the open function is working if we need to create a new file just go to file new and that will delete our old text so lastly we have save file underneath the save file function file equals file dialog dot ask save as file name so this will be the default name for the file but you can change that initial file equals let's say untitled dot you txt set a default extension default extension equals let's say txt file types equals all files comma then asterisk dot asterisk for all file types and any text documents text documents asterisk dot txt okay if file is none that's if they close out of our file dialog we'll just return else so we'll set the window title first window title os dot path dot base name file file equals open open our file and write file dot right take our text area and get the text from index one through the end catch any exceptions it's better to name them instead of just doing a general accept exception but i'm just going to print couldn't save file and finally close our file file dot close all right so let's test it so i'm going to change the font i wonder if impact is in here yes it is i'll change the font size maybe 30 and i'll pick a color how about this swamp green color okay so write something perhaps some lyrics to a song you like i should probably test copying and pasting edit copy edit paste nice all right let's actually try and save this now i'll go to file save the default file name is untitled because we set it to that i'll say all star lyrics and save now i should be able to open this so i'm going to go to my desktop here's that text file i'm going to open it and here are the lyrics that i wrote within my text editor and let's try and read this so let's go to file open find your text document open and would you look at that my lyrics are still here however this program doesn't save the font so i thought of a fun last minute project that we can do we can actually use our text editor to write a python file much like what we do with pycharm so let's write a program using our text editor program it'll be just a simple program let's print hello world and ask for some user input let's say name equals input what's your name and we will print hello plus our name variable and you can change the font and everything too if you want okay so let's save this file save i'll save this to my desktop but make sure you save it as a py file a python file i'll name this as hello dot py and save now to run a file using command prompt we need to find the directory that contains our python file mine is hello.py and it's located on my desktop so i need the location right click go to properties you can copy the location then within command prompt or terminal you can change directory by typing cd space and then paste your new directory the new location enter then to run a python program type python space and then the name of the program the python file mine is hello dot py hit enter hello world what is your name bro hello bro i just thought that would be a fun last minute project that we can do you don't even technically need an ide to write a python program screw you pycharm well everyone that is a basic text editor program i will post the code for this program in the comment section down below and well yeah that's a basic text editor program using python all right ladies and gentlemen let's create a game of tic-tac-toe to begin we'll need to import tkinter as well as random and let's begin by defining all of the different functions that we'll need let's define a function named next turn for the time being we'll just write pass we'll fill this in later on we'll need a function named check winner a function named empty spaces to check if there are any empty spaces left and lastly a function named new game that will launch a new game for us okay we have our four functions now let's create a window let's create a window window equals tk and at the end of our program we need to use window dot main loop and when we run this we should have just a small basic window let's set the title window dot title let's set this to tick tack toe we'll need a list of players players equals x comma o and with the way that we're writing this program we can swap these symbols with a different character for example we could say dollar sign is playing against the at symbol too but i'll demonstrate that later let's keep it as x and o for now now we need to select a random player to begin player equals random dot choice and pass in our list of players now we'll need nine buttons i'm going to create a 2d list of buttons named buttons and this will be the first row this will be the second row for the time being i'm just going to initialize these with 0 for everything and put these all within a list so we have a 2d list named buttons and to better visualize this i'm going to place each row on a new line so that's what our board is going to look like we have a 2d list named buttons we'll need a label to display whose turn it is label equals label i'll set the text equal to player plus the word turn and i'll set the font to font equals pick whatever font that you want and i am going to pack this label label dot pack and set the side equal to top and let's run this just to test it okay looks like it's x's turn let's try it again oh stern okay that's fine for now let's create a reset button reset underscore button equals button i'll set the text equal to restart it's going to be a restart button or reset button pick a font maybe i'll set the size to 20 and we'll need a command command equals new game when we click on this button it's going to call this new game function for us and we need to pack this button reset button dot pack and i will set the side equal to top okay let's see if that appears alright so we have our turn order a label that will display whose turn it is as well as our reset button now we'll need to create all of the buttons to add to our 2d list named buttons but i'm going to place these all within a frame frame equals frame we're adding our frame to our window and i'm going to pack this frame frame dot pack now we'll take our 2d list of buttons and add a button to each spot and i think the best way to do this would be to use nested for loops we'll have an outer for loop in charge of the rows four row in range three remember we only have three rows and three columns the inner for loop will be in charge of the columns four column and range three and inside the inner for loop we're going to create a new button we'll say buttons at index row and column we have two indexes because we have a 2d list so buttons at row whatever column whatever depending on what iteration we are within our for loops we'll create a new button and we'll set the text oh first add this to the frame almost forgot about that we're adding our buttons to our frame and adding the frame to the window now we'll set the text equal to a blank set of quotes because we don't want any text we'll set the font i'll just copy what we have here for label for a width let's say five and a height let's say two i'm going to hit enter just to move down to the next line because we still have a few more things to fill in okay we'll need a command command equals and i'm going to set this equal to a lambda function so we need some arguments actually i think i'll pass in some keyword arguments row equals row and column equals column then our expression is next turn and we will pass in row and column now we also need to add our buttons to our frame buttons at index of row and column we'll use the grid function for this grid row equals and column equals column and it's always a good idea to test your program after making any major changes so we should have our label our reset button and our grid of buttons now that the main body of our program is complete let's head to the next turn function and remember that we're passing in row and column as arguments so we need to set up those parameters within the next turn function row and column and the first line within here we would like access to our player so let's say global player so that we have access to it and we're first going to check to see if the button that we click on is empty so buttons at index of row and index of column to access the text of a button just add a third index operator and type in text if the text of our button that we click is equal to a set of quotes that means it's empty and when we call check winner winner winner chicken dinner and it's false there is no winner then we will fill in that button with our player our player's character whatever it is x or o or whatever we decide so within here let's check to see if player is equal to players at index zero that is our first player and remember that we created a list of players and we're planning on swapping these later we could say like if player is equal to x but that would make our program less flexible if we want to pick like a different character instead of an x so if player is equal to player at index zero whatever symbol is there then we are going to take buttons at index of row index of column take our text and set it equal to our player and we should check to see if there's a winner after filling in this button if check winner and we still need to fill in this function returns false then we will switch players player equals players at index of one and label dot config text equals players at index 1 plus the word turn so what we did here is that we're checking to see if after placing our text of our player on that button that we click if there is no winner then we're going to swap players player equals our next player and we're configuring our label so that it displays the next player's turn players at index 1 turn now what if there is a winner let's say else if check winner is true then we will take our label dot config and set the text equal to players at index 0 plus the word wins now let's add another else if statement else if there's a tie let's say check winner is equal to the word tie because we are already using false and true then let's change our label and i'm just going to copy this text equals the word tie okay so let's create an else block so that goes right here so if it's not player one's turn player at index zero then it's our other player's turn player at index of one so oh then so we just need to mostly just copy this text and change a few things around so i'm going to copy all this and within here let's set player equals players at index zero then players at index zero's turn players at index one wins and that is it now our next turn function is now complete let's head down to the check winner function and we need to check all of the different win conditions and return it true if somebody won false if there is yet no winner and the word tie if it's a tie so let's check all of the horizontal win conditions so we can do this using a for loop for row in range three we need to check the text of each button in each row if buttons at index of row and column index of 0 we'll use the index operator to check the text is equal to the next button in our row so i will copy this and change zero to one check to see if that is equal to buttons at index of row index of two and i'm going to check to see if this is all not equal let me move this a little bit to a space so if that is the case that means somebody won so if all of these buttons are the same and they are not equal to an empty space that means they're all the same so let's return true that means that somebody won no we need to check the vertical win conditions if anybody has the same character all the way down a single column this next for loop is going to be four column in range three for the first button this will be button at index of zero and column then one and column let me just paste that and two and column now we need to check the diagonal win conditions so if buttons at index 0 0 that's the top left corner if the text of that button is equal to buttons at indexes of one one is equal to the indexes of button two two and if all of this does not equal an empty space then return true so there is a winner and we have one last win condition to check that is the other diagonal win condition so we just need to change some of these indexes around so we have zero two one one and two zero i'm going to change this statement to an else if statement no we need to check to see if there's any spaces remaining else if we will call the empty spaces function which we have yet to fill in if this returns false then we will return the word tie and lastly else else there is no winner and no tie so we will return false and that is it for the check winner function let's test this so this doesn't account for a tie quite yet but we can fill in some of these spaces looks like x wins and we can no longer fill in buttons and we cannot start a new game quite yet either within the empty spaces function let's create a local variable named spaces and set this equal to nine whenever we call this function four row in range three and we'll create a nested for loop for column in range three we will check the text of each button if buttons at indexes of row and column and we will check the text to see if it's not equal to an empty space if that is the case spaces minus equals one then we'll write an if statement if spaces as in spaces remaining is equal to zero that means we will return false and there are no spaces left else we will return true okay let's test it so this time i'm trying to get a tie yep looks like it's a tie this next part's optional but i would like to change the color of each button for the winning combination so within our check winner function underneath the first win condition i'm going to take buttons at index of row and index of zero use the config method and set the background color equal to let's say green and i'm going to repeat this process for the other buttons within this win condition so that is row zero row one and row two i'll copy all of this paste it and switch some of these around so these should all be matching so zero and column one and column and two in column okay so we have zero zero one one and two two and one more zero two one one and two zero now when we have a winning combination the color of the buttons involved in that combination are going to change to green now if there is a tie let's change all of the buttons to let's say yellow so i'm going to write nested for loops for this four row in range three for column in range three take our buttons at row and column and change the background color to yellow or some other color of your choosing so if there's a tie they should all be yellow i'm trying not to win here it's actually more complex than what i thought yep it looks like it's all a tie and the last thing that we need to do is to fill in the new game function so that we can begin a new game so let's say global player we would like access to our player from inside this function and set player equal to a new random choice random dot choice and pass in our list of players and we will change our label label dot config and set the text equal to player plus the word turn and we also need to reset all of our buttons for row in range three for column in range three buttons at index of row and index of column dot config text equals a set of quotes so it's empty and we'll change the background color factors previously so the default color for buttons is actually hexadecimal f 0 f 0 f 0 so this function will begin a new game for us and let's test it to be sure i'm going to start a new game reset reset i'll actually try and win this time and reset okay so it looks like the new game function is working now another thing that you can do too is that you can change the players around let's say we would like to play as dollar sign and at sign so this program is flexible enough so that you can change the icons of the players all right everybody so that's a basic game of tic-tac-toe for python if you would like a copy of this code i will post all of this to the comments section down below but yeah that's how to code a basic game of tic-tac-toe for python hey what's going on everybody it's your bro hope you're doing well and in this video we're going to create a game of snake using python so sit back relax and enjoy the show first thing we should do is import from tkinter as well as the random module and let's define all of the different classes and functions that we'll need so let's create a class for our snake object as well as our food object so for the time being i'm just going to write pass for my classes we'll fill these in later so we have class snake and class food and let's define all of the different functions that we'll need so let's say we have a function named next turn change direction check collisions and lastly game over okay for change direction i'm going to have one parameter a new direction now when i create a game i like to place a bunch of constants at the top of my game constants are variables that you do not want to change later they're kind of like the settings however in python there are no constants compared to other programming languages so we're just going to create a bunch of variables that will behave like them so constants are values we do not want to change and they're kind of like the game settings and i placed them at the top for convenience and the naming convention for a constant is that all the letters are uppercase so these will be settings like the game width the speed etc so let's say the width of our game will be 700 but feel free to take the liberty to pick whatever size you want so we have game width game height i'll set this to 700 as well so it's a square let's say we have a speed the speed of the snake how often will our canvas update so let's say 50 but the lower the number the faster the game and a space size how large are the items in our game like the food and body parts of the snake so i'm going to pick 50 but you can change this and body parts how many body parts does our snake have when we begin a game let's say three how about a snake color you can pick a color name you can use rgb values or you can use a hexadecimal value so i'm going to pick green 0 0 ff00 but you can pick any color you want how about food color equals red and that is ff000 and what about a background color for the canvas background color i'll pick black so that is six zeros feel free to mess with some of these colors too so we have a green snake our food is going to be red and our background is going to be black so that is all of the constants for our game but you can feel free to adjust them if you like let's head down to the bottom and make our window so we have window equals tk and at the very end we should have window dot main loop let's set a title for this window window dot title snack game okay fine i'll spell it right snake game and if you do not want your window to be resizable you can use resizable and then you have to pass in false twice it's kind of strange but it's how it is okay we should have a small window and we cannot resize this even if we tried okay let's create a score label but we probably need a score first so let's say score equals zero and an initial direction direction equals let's say down now let's create a score label so let's say label equals label we're adding our label to our window let's set the text equal to score colon then i'm going to use the format method and we will pass in our score whatever it is and i'll set a font pick whatever font you prefer and 40 is a decent size and then i'm going to pack this label let's test it okay we're getting somewhere we'll need to create a canvas canvas equals canvas we're adding it to our window i'm going to set the background color equal to our background constant i'm going to set our height equal to the game height and the width equal to the game width that we set and we need to pack this canvas dot pack and we should have a game board i'm going to try and center this window when it appears so we can do that using a few lines of code the first thing we'll do is update our window so that it renders and then we need to find some dimensions so let's say the window width equals window dot w info width and window height equals window dot w info height we'll need our screen width equals window dot screen width and screen height equals window dot w info screen height where is it there it is okay then we need to see how much we're going to adjust the position of our window so let's say x equals screen width divided by 2 minus window width divided by two and do the same thing for y except this will be screen height and window height and that will be why okay then we need to set the geometry window dot geometry we're going to use an f string so let's set the window width times window height and then add plus x plus y so when we pass in x and y these cannot be floats they have to be whole integers so let's add a cast around x and y okay now this should be fairly close to the center yeah that's not too bad now when we begin a new game we should create a snake object as well as a food object snake equals snake and called the snake constructor and food equals food okay let's fill in our food class first because i think that'll be easier than our snake class so let's head to the food class now let's create an init method so def init this will construct a food object for us and we need to place our food object randomly so for the x coordinate let's say x equals random dot rand int and we need a range the range is going to be zero comma now with our game board i view it like a chess board there's a given amount of spaces so 700 divided by our space size is 14 possible spots on the x-axis and then 14 possible spots on the y-axis so i need to pick one of these spots randomly so let's say game width divided by our space size so we'll get a random number between 0 and 14 however this should be exclusive so let's say -1 and for good measure i'm just going to add a set of parentheses around this okay and then we'll convert this to pixels so let's multiply all of this by our space size the size of each item in the game and we'll do the same thing for y but change game width to height okay we should be good all right now let's set the coordinates let's say self dot coordinates equals a list of x and y and that's it but make sure you spell coordinates right now we need to draw our food object on our canvas canvas dot create oval you can pick a square two if you like we need a starting corner that will be where x and y is and an ending coordinator so that will be x and y plus our space size the size of an object in that game so x plus space size y plus space size and you can set a fill color too fill will be our food color that we declared and i recommend adding a tag as well that'll make it easy to delete this object so tag will equal the string food now let's just test this so we should have a random circle or a square if you picked a square appear someplace at some spot on my game board cool seems like it's working let's work on the snake class next our snake class we'll need a constructor and we will set a body size equal to our body parts we'll need a list of coordinates fill this in later and a list of square graphics so that will be a list okay so we need to create a list of coordinates we can use a for loop for that so let's say for i in range zero through body parts we will take self dot coordinates and append a new list and the coordinates for each body part at the start of the game will be 0 0 so that our snake will appear in the top left corner now we'll need to create some squares okay so for x y in self dot coordinates and remember that we have a list of lists so that's why we're using x y in self coordinates we'll create a square equals canvas dot create rectangle so we need a starting corner that will be x and y then x plus our space size the size of each object in the game let me use the constant though space size y plus space size and let's set a fill color equal to our snake color all right and let's set a tag for convenience tag equals a string of snake okay so we have a list of squares and we can append each square into our list self dot squares dot append and pass in whatever square that you create so we have a snake that has a body size a list of coordinates and a list of square graphics now after testing this we should have the head of our snake in the top left corner and now we just need the snake to move in a given direction every turn so the initial direction is down but we'll be able to change that later so let's head to the next turn function and there's actually two things we'll need as parameters that i forgot to fill in snake as well as food and we will call this function when we begin our game so let's unpack the head of the snake so that's x comma y equals snake dot coordinates at index of zero so that's the head of the snake the coordinates will be stored in x and y so let's check to see if our direction our initial direction equals up and we'll need some else if statements we'll fill this in just a moment else if our direction equals down then left and then right okay if our direction is up then let's take our y coordinate for the head of our snake minus equals our space size so that we move one space up and then down is plus equals space size left is x minus equals space size and lastly right is x plus equals space size okay then we need to call the next turn function again for the next turn so we can use window dot after we need the time so let's say our game speed we're going to call the next turn function and we need to pass in our arguments of snake and food snake food oh and make sure you're not actually calling the next turn function inside of the after method you just have to write the function name of next turn without the parentheses okay so let's update the coordinates for the height for the snake and write that before we move on to the next turn so snake dot coordinates and we will insert a new set of coordinates after updating one of them so zero will be the index the head of the snake and we will insert x and y coordinates at this new location now we're going to create a new graphic for the head of the snake square equals canvas dot create rectangle pass in x and y for the starting corner of our rectangle and the ending corner will be x plus our space size y plus our space size then i will add a fill color of snake color and then we need to update our snakes list of squares so that will be snake dot squares and insert at index 0 a new square that we create okay let's test this one last thing that we'll need to get this program to run is that after you create your snake and food object we should call it the next turn function and pass in our snake and food object so we should be able to test this so our snake is going to move but we need to delete the last body part in our snake within the next turn function but before we update to the next turn let's delete the last body part of our snake so delete snake dot coordinates at negative index of one that is the last set of coordinates we will update our canvas canvas dot delete snake dot squares an index of negative one and lastly delete snake the list of squares at index of negative one so it should appear that our snake is moving cool we need some controls for our snake so at the bottom of our program let's bind some keys let's do that here so window dot bind let's find the left arrow key and we will use a lambda the argument is event and we will call the change direction function and pass in the word left okay then we have to do the same thing for the other directions so we have right pass in right up pass in up down pass in down let's head to the change direction function we need to access our direction global direction this is the old direction if our new direction that is passed in is equal to left and if our old direction this direction does not equal right because we do not want to go backwards and do a 180 degree turn then we will set our direction equal to our new direction and we just need to repeat this for the other directions for new direction and i'm going to change this to else if else if new direction is right and our direction is not already left then we have up if our direction is not down and down if our direction is not up okay so we should be able to change the direction of our snake sweet okay we need to eat that pesky apple next so let's work on that there's nothing else that we need to change within the change direction function so i'm going to minimize this function and head to the next turn function we'll place an if statement here if x remember that we unpacked the coordinates for the head of the snake if x the x coordinate for the head of the snake is equal to our food objects coordinates at index of zero that's the x-coordinate for our food object and y is equal to food coordinates at index of one that means they're overlapping let's take our score and increment it by one and change our label label.config the text will equal score and then i'm going to use the format method and pass in my new score let's delete our food object and we gave our food object a tag so we can just use the name of the tag to delete it and create a new food object then i'm going to write this part of our program within an else statement we will only delete the last body part of our snake if we did not eat a food object okay let's test it again so i have three body parts now i have four five six seven eight nine ten you can see that the score is going up too okay let's work on collisions next because i should not be able to go off screen like this there's one thing that we're going to change so let's add an if statement that will check collisions this will return true or false if we detect a collision and pass in our snake object if there is a collision we'll call the game over function else we will update to the next turn okay let's fill in the check collisions function and we no longer need our function of next turn actually we don't need these classes either so i'll minimize them okay check collisions so it looks like we will need a parameter of snake so be sure to set that let's unpack the head of the snake x y equals snake dot coordinates at index of zero and let's check to see if we cross the left or right border of the game if x is less than zero or x is greater than or equal to our game width then return true i think for testing purposes i'm going to print something to the console window game over let's test it okay i'm going to go over to the right border game over and our game stopped let's go over the left game over cool so we know that it's working okay let's do the same thing for y we can use else if here if y is less than zero or y is greater than or equal to our game height let's print game over and return true and we should probably test it okay i'm going up game over and let's go down game over so what if our snake touches its tail or another body part so let's say four i actually i isn't too descriptive let's say for every body part in snake dot coordinates we're going to set this to everything after the head of the snake we're going to check to see if any of the coordinates are matching if x is equal to body part at index 0 and y is equal to body part at index 1 then return true and i'll print game over to test it print game over otherwise we can return false there are no collisions i think i'm going to change the size of the snake to 10. okay let's run into each other cool game over and the last thing that we need to do is to fill in the game over function because it looks like everything else is fine so head to the game over function take your canvas and delete all and we'll create some game over text canvas create text i would like this in the center of my canvas i'll take canvas w info width divided by two comma canvas w info height divided by two i'm going to put some of this on the next line for readability i'll set a font pick whatever font that you want we'll need some text text equals game over pick a color red's decent i'll add a tag too for convenience game over and that should be it for the game over function i'm going to change the body parts of the snake back to what it was originally and we should probably test that game over screen all right it appeared okay so let's change some of these settings around you can create a larger game board let's say 1000 by 700 that still works you can slow down the speed or speed it up so 100 will be about half as fast it's going pretty slow now but what if we set it to 20. you can change the space size so everything is a lot smaller now including the food object you can change the body parts what about 20 to begin with that's fairly excessive i'll change that back to three you can change the snake color let's say we would like a blue snake so that is for a hex color four zeros and then two f's you can change the food color so let's say we would like a yellow food object so that would be four f's and then two zeros kind of resembles the python logo that color scheme you can change the background color too so let's say all white that would be six apps i do not like that go back delete delete delete alright well that should be everything let's run this game one last time [Music] [Music] well everybody that is a very basic game of snake for beginners i will post all of this code to the comment section down below but yeah that's a basic game of snake using python hey you yeah i'm talking to you if you learned something new then help me help you in three easy steps by smashing that like button drop a comment down below and subscribe if you'd like to become a fellow bro [Music] you
Info
Channel: Bro Code
Views: 1,342,825
Rating: 4.985805 out of 5
Keywords: python, python tutorial, python language, python full course, python course, learn python, learn python programming, python tutorial for beginners, python programming tutorial, python programming language, software development, programming tutorial, yt:cc=on
Id: XKHEtdqhLK8
Channel Id: undefined
Length: 720min 0sec (43200 seconds)
Published: Mon Feb 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.