Transcript for:
Fundamentals of Python Programming

what's up everybody in this video I'm going to teach you everything you need to know to start coding with python I've also included 20 different Hands-On projects to help you learn you can find the entire list in the description of this video our final project will be a weather app that fetches real-time weather data from an API even if you've never coded anything in your life before I'll walk you through the basics the ABCs of programming if that sounds good to you then I encourage you to sit back relax and enjoy the show this course doesn't cost you anything but if you would like to help me out you can help increase its reach by hitting the like button leave a random comment down below and subscribe if you'd like to be a fellow bro thank you I appreciate it I don't like boring introductions so I say we just jump right in there's two things we'll need to download the first is a python interpreter to convert our written code to machine code we're going to head to python.org or go to downloads and download the latest version we will open this executable if you're on Windows you'll want to check this checkbox add python exe to path and we will install now the setup was successful and that's all you need to do to download the python interpreter the second download we'll need is an IDE an integrated development environment basically a place where we can write code for idees there's two popular choices when writing python code pycharm and vs code if you already use vs code you can stick with that just be sure to download the python extension I find pycharm more beginner friendly if you've never coded before if you would like to use pycharm go to jetb brains.com pycharm and we will click this green download button there's two versions of py charm the professional version and the community version the professional version is paid for I would not recommend using it only because there's plenty of free Ides on the market we'll use the Community Edition the free one because I don't like to pay for things and I'm sure you don't either select the correct download for your operating system I'm running Windows I will download pycharm we will open this executable click next you could select a destination folder I'll keep it as is next I'll create a desktop shortcut but you don't necessarily need to click next install and we'll just have to give it a moment okay the setup is now complete I'll check this check box to run py charm when we click close this window after opening py charm we're going to create a new project you can rename your python project I'll keep it as is you can select a location again I won't change that you can create a sample welcome script but for this tutorial we won't let's select the latest python version and create our new project in the menu to the left we're going to create a new python file file file new python file let's name this file main but really you can name it anything and select python file python files end with the py file extension we should have our main python file within our python project folder now we're going to print something to the console window within our main python file we're going to write a print statement so type print add a set of parentheses between the set of parentheses we will add a set of double quotes to print something or single quotes either one my own preference is double quotes normally in a programming tutorial the instructor would tell you to print something such as hello world but we like to be different here instead think of your favorite food in this case I like pizza I will print I like pizza to run our Python program we will click the screen Arrow to run our main python file we should have a console window that displays our output I like pizza or whatever your favorite food is let's print another line of code let's print it's really good by adding a second print statement we are printing a second line of code now we'll discuss comments the python interpreter doesn't output comments to write a comment you use a pound sign I like to call this a hashtag my comment will be this is my first Python program comments are used as notes for yourself or for other people reading this code if I were to run this code again this comment is not displayed to the output we still have I like pizza it's really good all right everybody so that is your very first Python program and in the next topic we'll discuss variables all right everybody we are moving on to variables a variable is a container for a value there's four different data types we'll discuss strings integers floats and and booleans yes I know that's a silly name a variable behaves as if it was the value it contains each variable should have a unique name let's say we have a variable of first name to assign a variable you use the assignment operator of equals for text a string is a series of text this can be double quotes or single quotes my own preference is double quotes why don't you type in your first name this very ible a first name will behave as if it was this value the series of characters so to demonstrate this I'm going to print my first name variable so place it within a print statement without quotes that will print your first name now you don't want this within quotes because then you're literally printing the word first name you could use your variable along with some text by using what is called an F string that's the easiest way to display a variable so you type f then a set of quotes the f means format so let's say the word hello then we will add our variable we will insert our variable into this text when using an F string to do that you need a set of curly braces then insert your variable so the result is hello whatever your first name is in my case bro let's create another variable let's say we have a variable of food food equals think of your favorite food for me I will type Pizza let's print the following you like add a placeholder again I'm using an F string our variable of food hello bro you like pizza let's create an email use your own email or make up one let's say my email is bro1 123 fake.com then let's print our email your email is at a placeholder display our email variable your email is bro1 123 fake.com so these are string I'm going to add a comment that these are strings a string is a series of characters they can include numbers but we treat them as characters now we have integers an integer is a whole number an example of this could be somebody's age how old are they according to my YouTube statistics many of you are between the ages of 18 through 24 let's say that I'm 25 let me zoom in a little you're integer should not be within quotes because it would be a string then technically if I would like to work with this variable again I'll use an F string let's say you are at a placeholder display our age variable years old you are 25 years old another example of an integer could be a quantity you are buying a certain amount of something maybe I am buying three items I wouldn't have half an item this would be a float technically rather than an integer we are buying three of something so let's print the following you are buying at a placeholder display our quantity items you are 25 years old you are buying three items another example of an integer could be an amount of people let's say num of students like a classroom there are 30 students in our class then we will print your class has at a placeholder students we will display the number of students num of students your class has 30 students those are integers they're whole numbers and again make sure they're not within quotes because then technically they would be a string integers we can use in arithmetic Expressions if they were strings we couldn't then we have floats float means floating Point number a float is a number but it contains a decimal portion an example would be a price what is the price of something $1.99 let's print our price print I'll use an F string the price is add a placeholder display our price the price is $10.99 let's preat our placeholder with a unit of currency I'll pick American dollars but feel free to pick something else the price is $10.99 so floats contain a decimal portion what about a grade point average GP let's say my GPA is 3.2 then I will print your GPA is display our GPA your GPA is 3.2 what about a distance a distance can contain a decimal portion 5.5 kilm Maybe then I will print youan at a placeholder display our distance then I'll add km for kilometers or you could add Mi for miles but I'll stick with kilometers you ran 5.5 km okay then we have booleans a Boolean is either true or false let's say we're a student is student equals if we are a student we could say that this is true true starts with a capital T if we weren't a student let's say we graduate we could say that this is false again the first letter is capital booleans only have two options true or false so let's say that I am a student then I will print are you a student then we will display our Boolean value of a student are you a student that is true with Boolean values we really don't output them directly you're more likely to see them used internally within a program such as when working with if statements this is a topic we'll discuss in the future so don't worry you may see if is student if this variable is true then we will print the following now we don't need to use an FST string we're not going to insert any variables you are a student If This Were false we can add an else Clause where we will print you are not a student our variable of is student is true we will print the if statement you are a student If This Were false we will print whatever is within else you are not a student let's think of a few more examples is something for sale like a car or a product of some sort let's say that is true I'll write another if statement if for sale if this variable contains true we will do the following let's print that item is for sale else if it's false we will print something else that item is not available for sale is set to true this variable is true we will print that item is for sale else if it were false we print that item is not available one more example let's say we have a Boolean variable of is online is somebody on online I will set that to true if is online if that's true we will print you are online else we will print you are offline is online is set to true we will print you are online else if it were false we print your offline all right everybody so those are variables a variable is a reusable container for a value there's four basic data types for beginners a string which is a series of text integers which are whole numbers floats which are numbers but they contain a decimal portion and booleans which are either true or false they're binary your assignment in the comment section is to post four variables post a string an integer a float and a Boolean try and think a unique example if you can and well everybody those are variables in Python all right everybody so we are moving on to type casting typ casting is the process of converting a variable from one data type to another we have various functions to convert a value or variable to a string an integer a float or a Boolean let's create some variables we will create a name variable type in your full name name an age make up some age a GPA for grade point average let's say minus 3.2 and a Boolean of a student are we currently a student let's say that's true now you actually could get the data type of a variable or a value by using the type function then pass in a value or variable however when I run this there's no output so I need a print statement we will print what is returned by the type function get the type of our name variable then print it so our name variable is a string St Str our age variable is an integer and int GPA is a float is student is a Boolean using these typ cast functions we can convert from one data type to another here's how let's start with something simple let's convert our GPA to an integer currently it's a float I will reassign GPA use the int function to typ cast to an integer then pass in my GPA at the end we will print our GPA if we typ cast 3.2 to a whole integer what would the result be a whole integer of three we truncate the decimal portion let's convert our age to a floating Point number we will reassign our variable of age use the typ cast function of float then insert our age variable let's print our age variable and it should be a floating Point number 25.0 now we'll cover strings let's typ cast our age to be a string age equals call the typ cast function of string St Str passing our age variable so the result is still going to appear the same 25 however it's a string not an integer and to prove that I will enclose my age variable with the type function the type of variable age is a string it would be the same as if we're taking this number and enclosing it within quotes So this would make a difference because let's say that I add one to age age plus equals 1 well we would get a type error can only concatenate strings not integers to a string however if I were to add a string of one to the end we would be using string concat ation so let's say it's my birthday and I add one to 25 well since we're working with strings now the result would be 251 I am 251 years old so strings and numbers behave differently with numbers we can use them within arithmetic Expressions strings not so much we will take our name variable and typ cast it to a Boolean name equals call the typ cast function of BU passing our name variable this has an interesting result so I'm going to print name booleans are either true or false if I typ cast my string of text into a Boolean that gives me true now it really doesn't matter what I write here if I were to change my name to a single character such as B this would still be true if our string variable was empty there were no characters within it that would actually give us false we could use this to check to see if somebody enters in their name or not if somebody types in their name then we typ cast it to a Boolean if somebody skips entering in their name that would return false we could reprompt the user to enter in their name again all right everybody so that is typ casting it is the process of converting a variable from one data type to another this is especially useful with handling user input because user input is always a string there may be at times where you want to convert it to an integer a float or a Boolean and well everybody that is typ casting in Python all right everybody in this topic I'm going to show you how we can accept user input in Python we use the input function it's a function that prompts the user to enter in data and it Returns the enter data as a string here's here's an example to accept user input we will call the input function when I run this program we need to enter in data to our console window like so then hit enter however we need a prompt we need to tell the user what we want them to type in so let's ask a question our prompt will be within quotes let's say what is your name let's try this again what is your name I can type in something why don't you go ahead and type in your full name then hit enter now with this input we're not quite doing anything with it the input function is going to return some data as a string we can assign it to a variable if we would like let's create a variable of name name equals our user input then once we have our name let's print a message I'll use an F string we will print hello add a placeholder then insert our name variable within that placeholder let's try this what is your name type in your name hit enter hello whatever your name is let's try a different name I will pick SpongeBob many people are familiar with SpongeBob hello SpongeBob this time we will ask a user how old they are let's assign a variable of age equals accept some user input we need a prompt within quotes how old are you once we have our age variable let's print I'll use an F string you are at a placeholder our variable age years old what is your name type in your name how old are you let's say that I'm 25 hello whatever your name is you are whatever your age is years old all right so let's say that it's our birthday before we print our age variable let's say happy birthday since I'm not inserting any variables within this print statement this doesn't need to be an F string you'll want to use an F string if you want to insert variables before we display the user's age let's take the user's age and increase it by one we could say age equals age + 1 but there's one problem with this type in a name how old are you type in an age and we have a problem we have a type error can only concatenate strings not integers to strings when we accept user input we store that input as a string before we increment our age by one we'll need to convert it to an integer we can't normally use strings within arithmetic Expressions but we can do that with integers and floats though after we accept some user input for our age variable we could take our age variable and typ cast it as an integer which we talked about in the previous lesson so let's say age equals our age after we typ cast it then increment it by one so type in your name type in an age and we get this message hello your name happy birthday you are whatever your age is years old so strings we can't normally use with arithmetic Expressions we would have to typ cast it to an integer or a float however we could condense some of these steps we're taking up an extra line to type cast our age as an integer what we could do instead is that when we accept our user input we can enclose the input function within a typ cast to int and that would work the same type in your name type in an age and this works the same and it takes less lines of code and is more readable I would say when we accept user input it returns that input as a string data type then we just have to typ cast it to another data type if we need to and in this case for age we do now we'll go over a couple exercises because it's important to practice what you've learned in this first exercise we're going to calculate the area of a rectangle we need to prompt the user to enter in a length and the width of a rectangle so we will create a variable of length we will accept some user input using the input function what is our prompt let's say enter the length let's do this with width I'll just copy and paste what we have width equals enter the width so we have the length and the width to get the area of a rectangle we have to multiply the length by the width so let's say area equals our length variable now to use mult multiplication you use an asterisk we'll discuss different arithmetic operators in the next lesson so we have length time width that is the area I'm going to print our area because I need to test something enter the length let's say 5 5 in 5 cm doesn't matter enter the width six we get a type error can't multiply sequence by non-int non- integer of type string when we accept user input it returns a value of the string data type we can't use those strings in arithmetic Expressions we're multiplying the length times the width we would need to tycast them as an integer or a float since we're working with basic geometry such as calculating the area let's do float so let's typ cast our user input as a float for both length and width okay let's try this again let's say 5 * 6 the area that's returned to us is 30 30.0 this result contains a decimal it's a floating Point number a float so when we print the area I'll use an F string this time the area is I'll add a placeholder display our area variable let's add a unit of measurement afterwards I'll pick centimet now since we're working with areas if we would like to technically be accurate so we could say to the power of two or we could add a superscript so if you would like superscript 2 and you're on Windows make sure numlock is on hold alt then type on the numpad 0178 so we have a superscript of two again it's not really necessary for this lesson I just think it'd be cool to include it because then it's technically accurate all right let's say that the length is 6.1 and the width is 7.2 the area is 43.92 cm squared because we're working with areas let's cover a second exercise this time we will create a shopping cart program exercise two we're going to create a shopping cart program we need three variables an item a price and a quantity of those items we will create a variable of item we will accept some user input what item would you like to buy what are we trying to purchase we'll keep the data type of the user input as a string then we need a price what is the price of each item we're buying use the input function what is the a price a price should be a floating Point number for example we might have dollars and sense we need a decimal so let's typ cast our input as a float then a quantity we will accept some user input our prompt will be how many would you like quantities they should be whole numbers let's type cast our input as an integer then we will have a total What's the total that we have to pay so let's take the price of each item use an asterisk for multiply our quantity then let's do a test run let's print our total what item would you like to buy let's say a pizza what is the price $10.99 how many would you like I would like five pizzas and our total is 54.9 let's say that before we display the total let's print the following I'll use an F string you have bought insert a placeholder display our quantity X item or items I'll add SLS then we will print I'll use an FST string again your total is display our total what item would you like to buy I would like to buy a pizza what is the price $10.99 how many would you like I would like nine pizzas they're all for me I'm going to eat all of them you have bought 9 x pizzas your total is 98.91% all right everybody that is how to accept user input in Python and we've covered a few exercises in the next topic we're going to create a Mad Libs game and that is how to accept user input in Python all right everybody in this video we're going to create a game of Mad Libs not because we have to but because I want to it would be a good exercise for us just so we're more comfortable with accepting user input if you're not familiar with Madlibs Madlibs is a word game where you create a story by filling in the blanks with random words so we're going to create a story template the story is going to be missing some components we will fill in those components with random words that we type in here's a story that I've written myself print use an FST string today I went to a insert a placeholder Zoo for our placeholder we'll insert an adjective we'll insert a variable named adjective adjective adjective one you're going to get an English lesson today too and adjective is a description of something so for our Zoo adjective one could be expensive large dirty an adjective describe something we'll fill this in when we accept user input for our second print statement let's print the following in an exhibit I saw a placeholder will include a noun noun one a noun is a person place or thing in English maybe a gorilla a gorilla named harambe for example print use an FST string let's say our noun one whatever this is we can reuse variables was we will create a second adjective adjective 2 we will be describing whatever noun one is this person place or thing and we will insert a verb verb one a verb is an action such as running or eating then for our last statement let's print I was at a placeholder we'll create adjective three adjective 3 will describe us now we're going to fill in these variables by accepting user input we're going to fill in adjective one we'll accept user input using the input function enter and adjective I'm going to add a reminder that an adjective is a description of something then we need noun one noun one equals input enter a noun a noun is a person place or thing then we have adjective two I'll just copy adjective one paste it change one to two then a verb verb one equals input enter a verb I want verb one to be in current tense I'll ask ask the user to end the verb with ing enter a verb ending withg then it's current tense our person place or thing of noun one is currently doing something such as eating and then adjective three and I'll just copy one of these adjectives adjective three equals input enter an adjective okay and then we are ready to run this enter an adjective an adjective describes something I will say suspicious or some kids like to say sussy or sus even I've also heard of kids nowadays using the word skibidi feel free to type in whatever you would like it is your story after all I'm going to say suspicious enter a noun a person place or thing I like to poke fun at Mark Zuckerberg so I'm going to say my person is Mark Zuckerberg enter an adjective that is a description angry enter a verb ending with ing so it's current tense uh screeching enter an adjective happy here's my story today I went to a suspicious zoo in an exhibit I saw a Mark Zuckerberg Mark Zuckerberg was angry and screeching I was happy that's our game of Mad Libs it's a word game where you create a story by filling in the blanks with random words also post the output of your Mad Libs game in the comment section down below because I really want to read them I want to see what you guys came up with and well everybody that is a Mad Libs game using python hey everybody in this video I'm going to show you all of the different math that we'll need throughout the rest of the series I have a lot to cover and I'll split this video into different sections we'll cover some basic arithmetic operators built-in math functions a few functions from the math module and then a few exercises be sure to look at the time stamps if you would like to skip ahead to another section let's begin with some really easy stuff we're going to cover some basic arithmetic operators let's say we have a variable friends current ly you have zero friends if you need to increment a variable by one you could say friends the name of the variable equals the name of the variable again + one so the plus sign is the addition operator and I think we do have a little bit of experience with that already so if I were to print my variable friends guess what you now have one friend we could also shorten this line of code you could say friends plus equals 1 that would do the same thing this is known as an augmented assignment operator that will give you the same result I prefer to use augmented assignment operators just because they take less text and I think they're easier to read now let's use subtraction friends equals friends minus two so of course minus is the subtraction operator uh you have netive -2 friends I guess if you were to use the augmented assignment operator that would be friends minus equals 2 there you still have -2 friends okay multiplication let's change friends to how about five friends equals friends time 3 you now have 15 friends then the augmented assignment operator version of this would be friends times equal 3 so again you have 15 friends let's cover division friends equals friends divided by 2 so we have 2.5 friends somebody was cut in half we have half a friend maybe it's just their legs or torso or something then the augmented assignment operator would be friends ID equal 2 and the result is still the same now exponents friends equals friends to the power of two so if friends is currently five friends to the power of two would be 5 * 5 which is 25 the augmented assignment operator version of this equation would be friends exponent equals 2 and again friends is 25 then we have modulus modulus gives you the remainder of any division suppose we have 10 friends instead of five I will assign a new variable remainder remainder equals friends the percent sign is known as the modulus operator it will give us the remainder of any Division if I were to divide my group of friends by three will have one remaining I'll store the remainder within a separate variable we would have a remainder of one it's kind of like in class when the teacher says for everybody in the class to go into groups at three then there's always that one kid that's by themselves that's kind of the same concept we're dividing our friends into groups of three then the modulus will give you the remainder if we divided our group of friends into groups of two well 10 divides by two evenly so there is no remainder so that is the modulus oper operator it's fairly popular to use this operator to find if a number is even or odd because it will divide by two evenly if that number is even if the remainder is one that means that the original number is odd okay so yeah those are some basic arithmetic operators addition subtraction multiplication division exponentiation then modulus now what we're going to do is cover some built-in math related functions suppose we have three variables x = 3.14 y = 4 Z = 5 it doesn't matter if these are floating Point numbers or whole integers the first is the round function we have a variable named result I'm going to round X so there is a built-in round function after the set of parentheses we can add some value or variable to be rounded so we will round x to the nearest whole integer then print the result so our result is three so that's the round function with the absolute value function we can find the absolute value of a number uh let's change y to be4 instead of four we'll take result equals ABS which means absolute value of y the absolute value is the distance away from zero as a whole number the absolute value of -4 is 4 let's change y back to four there's a built-in power function result equals pow then we'll need a base and an exponent what's y to the power of 3 that would be 4 * 4 * 4 which is 64 that the power function you can raise a base to a given power the next two are really useful using the max function we can find the maximum value of various values what's the maximum value between X Y and Z then I'll just need to store this value uh results equals the max between X Y and Z well the maximum value is five other wise there's Min what's the minimum value between X Y and Z that would be 3.14 now in this next section we do have some very useful constants and functions from the math class but we'll need to import the math module at the top of our text editor so import math if you need the value of pi you'll type the name of the math module do PI and I'm just going to print this print math. Pi the value of pi is 3.1459 and a bunch of digits that come after if you're working with physics I do know that people use the constant e a lot we won't be using e in this video series but if you ever need access to it just type math. e and that will give you e which is 2.71 something something something I believe e is known as the exponential constant if you need the square root of a number let's say result equals math.sqrt we can place a variable or a value within the square root function uh let's say we have X again x = 9 what is the square root of x then I will print whatever the result is the square root of 9 is three that is the square root function there's a ceiling function result equals math do Seal Seal will always round a floating Point number up suppose X is 9.1 so 9.1 rounded up is 10 otherwise there's floor which will always round a number down result equals equal math. floor let's change X to 9.9 9.9 rounded down is nine those are some useful math functions let's go over some exercises okay this first exercise we are going to calculate the circumference of a circle we'll need the help of the math module because there's some good functions in there to calculate the circumference of a circle the formula is 2 * < * r let's ask a user for a radius because that's what R is we'll accept some user input enter the radius of a circle we will type cast the input as a floating Point number to calculate the circumference again the equation is 2 * pi we can get that from the math module times whatever the radius is and the user is going to type that in then we will print whatever the circumferences print we'll use an FST string the circumference is our variable circumference enter the radius of a circle I'll enter 10 actually 10.5 their circumference is 65 .97 if you want to round and truncate some of these numbers we can use the round function around circumference then round to a given decimal place I'll round to two digits again 10.5 rounded is 65.9 7 you could add a unit of measurement too let's say centim 10.5 is 65.9 7 cm all right that is the first exercise for this next exercise let's calculate the area of a circle we'll import the math module we'll ask for a radius much like before radius equals input enter the radius of a circle we'll cast our input as a floating Point number the equation for the area of a circle is pi times radius squared we could easily use the built-in power function to raise our radius to the power of two then we will display the area print I'm using an F string the area of the circle is our area to some unit of measurement let's say centim squared and enter the radius of a circle 10.5 the area of the circle is 34636 but I would like to round this number to two decimal places I'll use that round function and I'll Place area and the number of digits to round two within this function let's try that again 10.5 the area of the circle is 34636 cm squared that is the second exercise for this last program we're going to find the hypotenuse of a right triangle the formula to calculate the hypotenuse of a right angled triangle is C = theare < TK of A2 + b^2 we'll Begin by importing the math module we'll ask the user for the lengths of side A and B A equals input enter side a we'll cast the input as a floating Point number we'll do the same thing with side b b equals enter side B now this part's going to be confusing we'll calculate C we'll need a^2 + b^2 will take a to the power of two plus B to the^ of two then we'll need the square root of all of this whatever the result is I will surround this equation with math. square root and that should give us our answer let's print using an F string side C equals whatever C is so enter side a three side B will be four side C is five all right everybody so that was everything related to some arithmetic operators and math related functions in Python and in the next video we're going to cover a few things involving string [Music] formatting hey everybody in this topic I'm going to explain if statements an if statement is used to do some code only if some condition we set is true l we could do something else it's a basic form of decision making if it's true we do something if it's not true we don't do it let's ask a user for their age age equals input enter your age I will type cast the input as an integer depending on what the user's age is we can do one of a few things let's pretend that the user would like to sign up for a credit card but in order to do so their age needs to be greater than or equal to 18 well we can check that to use an if statement type if then some condition what would we like to check let's check to see if the user's age is greater than or equal to 18 then add a colon then hit enter any code underneath the if statement should be indented make sure to pay attention to that because that's easy to miss if the user's age is greater than or equal to 18 let's print you are now signed up if I were to run this code I'll type in my age I'll type 21 hit enter this statement is true therefore we will execute any code found within the if statement you are now signed up what if this condition was not true let's say my age is 13 well nothing happens if the condition we check is instead false we skip over this code if you need to take a different course of action you could add an else statement if this is true do this else we can do something else let's print a different message you must be 18 plus to sign up I'll type in my age again I'll say that I'm 13 hit enter you must be 18 plus to sign up that's basically an if statement do some code only if some condition is true else you can do something else entirely it's a basic form of decision making the lse statement is kind of like a last resort we can check more than one condition before reaching the lse statement we can add an else if statement which we just shorten to e l meaning else if else if let's check if age is less than zero then we'll print a different message you haven't been born yet now if I run this code I'll say that my age is NE -1 this condition is false we skip this code this condition is true therefore we will execute this code and we skip the lse statement you haven't been born yet let's add another LF statement you can add as many El if statements as you want let's check to see if somebody's age is greater than or equal to 100 we'll print a different message let's print you are too old to sign up if I were to say my age is 111 years old well it states you are now signed up the reason that we didn't reach this part of our else if statement that's because this condition is still technically true you do need to pay attention to your order of if and else if statements if I want to be sure that nobody over 100 is signing up I should probably move this to the beginning if age is greater than or equal to 100 then else if age is greater than or equal to 18 we'll do something else and to your age I am 111 years old you are too old to sign up so those are if statements if some condition is true do something else if you can check something else if no above conditions are true you could do something else entirely it's kind of like the default here's another example we'll ask a user if they would like some food response equals input would you like food we'll have the user type in y for yes or n for no if our response now to check to see if two values are equal you would use double equals if the response is equal to Y then we will print have some food the doubles equal sign is the comparison operator it will check to see if two values are equal you don't want one equals because that's the assignment operator python in this case thinks we're attempting to assign the character y to response so for comparisons use double equals else we can print no food for you so would you like food I'll type why have some food let's try again I'll type no and for no no food for you here's the third example we'll have a user type in their name name equals input enter your name if our name is equal to an empty string that means they didn't type in anything so let's yell at the user you did not type in your name else we will print using an F string hello whatever the name is enter your name I'm just going to hit enter you did not type in your name let's run this again I'll type in my name and we have executed the L statement this time hello bro so one important thing that you should know is the use of Boolean with if statements suppose we have some Boolean variable named for sale I'll set this to be true now using an if statement you can just use the Boolean variable in place of a condition because a condition would evaluate to be true or false we could just say if for sale if that's true then let's print this item is for sale else we will print this item is not for sale for sale is set to be true this item is for sale if this variable were false well then the item is not for sale let's try a different variable how about online if online the user is online else the user is offline so the user is offline I'll change the Boolean to true the user is online so with if statements you can either write a condition or you could use a Boolean all right everybody so those are if statements do some code only if some condition is is true else you can do something else it's a basic form of decision making and those are if statements in Python hey everybody this is a remake of my python calculator program for absolute beginners all you need to know to complete this exercise is just if statements and how they work so let's get started for this exercise a user is going to select an arithmetic Operator Operator equals input we will ask the user to to enter n operator this will be plus for addition minus for subtraction as risk for multiplication and a forward slash for division you could enter more than this but I don't want to make this exercise too complicated we will create a variable of num one to contain our first number let's say we would like to add two numbers together what is the first number going to be enter the first number and let's do this with the second number num two enter the second number let me show you something I'm going to add num one and num two together num one plus num two we'll do a test run enter an operator I would like to use addition enter the first number 10 and 11 well the result is 101 when we accept user input they are string data types what we've ended up doing is string concatenation we've concatenated the string of 11 to 10 that's why we ended up with 101 we'll have to convert these two strings to be floating Point numbers by typ casting them as a float so enclose your input functions with a typ cast a flat and now we should be able to add those two numbers together so let's add 10 and 11 and we get 21.0 depending on the operator that the user selects we'll use some if statements to determine that we will check if our operator variable is equal to a character of plus and for now I'll write pass as a placeholder we'll get back to this later else if our operator is equal to minus we will use subtraction and for now I'll write pass else if operator is equal to an asterisk for multiplication we will multiply else if our operator is equal to a forward slash for division we will divide if our operator is addition let's create a variable of result result equals num one plus num num two for subtraction it's going to be num one minus num 2 multiplication would be num one times num 2 then division would be num one divided by num two then we just have to print the result print our result be sure to do this with each of the LF statements as well and let's see what we have let's add 5.5 + 6.9 that gives us 12.4 let's subtract 420 - 0.69 that gives us 41931 let's test multiplication multiply 3.14 * 3.14 which gives us 9.85 96 then division let's divide 69 by 13 and that gives us a really long number so you could round a number if you would like we would enclose our result within the round function and we'll just update each of these print statements this will round to the nearest whole integer so let's divide 420 by 13 let's say that we would like three digits after the decimal within the round function we could add comma 3 for three decimal places enter an operator let's use division divide 420 by 69 so that gives me 6.87 so we can round to a given digit after a decimal in in this case three places what if somebody types in an operator that doesn't exist like the word pizza then I will divide two numbers well let's add an L statement if somebody selects some input that is invalid let's let them know I'll use an F string let's say that the operator that the user has selected is not valid and let's try this again enter operator Pizza enter the first number 420 and 69 Pizza is not valid let's say is not a valid operator instead that makes more sense pizza will be my operator first number is 420 second number is 69 Pizza is not a valid operator all right everybody so that is a very simple python calculator program you can make make as a beginner hey there it's me again in today's topic we're going to create a weight converter program in Python this is an exercise that will follow up the lesson on if statements we'll convert pounds to kilogram or kilog to pounds the user is going to decide we will Begin by creating a weight variable we will assign some user input enter your weight we will convert this input into a floating Point number so add that cast then we will ask for a unit is this weight in kilog or pounds input kilograms or pounds we want the user to type in either K for kilogram or L for pounds and these are capital letters by the way using an if statement let's first check to see if our unit is equal to a capital K that means the current weight is in kilogram we need to convert that weight to pounds let's reassign weight equal to our weight times 2.205 else if unit is equal to l we need to convert to kilog weight equals weight ided 2.205 else the user did not type in something that was valid let's print using an F string unit was not valid at the end of our program we will print the new weight I'll use an F string your weight is our new weight after it's assigned now we need a unit of measurement this is what I'm thinking we'll do within our if and else if statements let's reassign our unit we're reassigning unit to be lbs for pounds else if unit equals kgs for kilogram in our results we will display our new unit let's take a look enter your weight actually I'm just going to make one change I'm going to add colon space there that's much better enter your weight let's say I'm 180 lb this is in pounds I'll type capital L your weight in kilogram is 81.6 3 I think I'm going to round this I will enclose the weight variable within a round function we will round to one decimal place let's try this again ENT to your weight maybe I'm 81 kilg I'll type K for kilogram your weight is 178.6 lb let's make sure that this lse statement works too enter your weight 18 180 pizzas pizzas was not valid so we're still displaying our output we would want to avoid that if somebody doesn't type in a valid unit so let's cut this line then paste each within the if and else if statements when we exit the else statement we're not printing the output so let's make sure that this works and to your weight I am 180 pizzas pizza was not valid all right everybody well that is a weight converter program in Python I thought this would be a helpful exercise now that we have finished the section on if statements and yeah that is a weight converter program in Python hey everybody in this topic we're going to create a temperature conversion program as an exercise we'll Begin by asking what the current unit of measurement is unit equals we'll accept some user input is this temperature in Celsius or Fahrenheit C slf then we will ask for the temperature I'll store the temperature in a variable named temp meaning temperature temp equals input enter the temperature then we should cast our user input as a floating Point number if unit is equal to C I'll fill this in momentarily I'm just going to write pass as a placeholder else if unit is equal to F we will do something else else let's print something just an error message of some sort using an fstring unit is an invalid unit of measurement Let's test this lse statement is the temperature in Celsius or Fahrenheit what if I were to type K for Kelvin I'll make up some temperature like 100 K is an invalid unit of measurement all right we know the L statement Works let's convert Fahrenheit to Celsius using this formula we will take our temperature equals 9 * R temp / 5 + 32 I'll take all of this and use the round function we'll round to one decimal place then we will print the current temperature in fahrenheit I'll use an F string the temperature in Fahrenheit is our temp variable degrees Fahrenheit Let's test this if statement is the temperature in Celsius or Fahrenheit it is currently in Celsius what is 33° in Celsius converted to Fahrenheit the temperature in Fahrenheit is 91.4 De all right so this section is working let's work on the else statement else if our unit is currently inir will convert to Celsius that formula is temp equals our temperature - 32 * 5 / 9 then I will round the result to one decimal place then we'll print the temperature in celsius the temperature in Celsius is is temp de C for Celsius is the temperature in Celsius or Fahrenheit it is currently in Fahrenheit enter the temperature 91.4 the temperature in Celsius is 33.0 De C well everybody that is a simple temperature conversion program in Python all right people we're talking about logical operators today logical operators allow us to evaluate multiple conditions we can link them together there's three we'll discuss or and not we'll begin with OR with or we can check more than one condition if at least one of those conditions is true then the entire statement is true here's an example let's say we have an outdoor event and I will create two variables one temp meaning temperature let's say that this is in Celsius 25° C pick Fahrenheit if you would like and I will create a Boolean variable of is raining I will set that to be false it is currently not raining if the temperature is too hot too cold or it's raining then I will cancel this outdoor event we'll write an if statement to check that if our temp short for temperature is greater than let's say 35 35° C then I'll use the or logical operator or if our temp is less than zero or if is raining is true if one of these conditions is true we're going to cancel our outdoor event so let's print the following the outdoor event is canell else we will print something else the outdoor event is still scheduled the temperature is reasonable and is raining is false it's not raining so we print the else Clause the outdoor event is still scheduled what if the temperature was really hot like 36° C well the outdoor event is cancelled what if it's cold -5° C the outdoor event is cancelled this condition was true therefore we execute the if statement or what if the temperature is reasonable but it's raining is raining is true well then the outdoor event is still canceled so with the or logical operator at least one of these conditions needs to be true if one of these conditions is true you could consider the entire statement true now let's cover and with and we can link two conditions together both conditions must be true in order for that entire statement to be true so again let's say we have temp short for temperature and we have a Boolean variable of is sunny I will set that to be true we will check if our temp is greater than or equal to 28 degrees C and is it sunny is sunny if it's hot and if it's sunny if this is true let's print the following it is hot outside for fun I'm going to add an emoji but you don't have to I just think it's more entertaining that way but you do you and I will press it is sunny sometimes these emojis are formatted differently I'm just going to copy it from somewhere else that's better currently the temperature is 25 25° C and it's sunny this condition was false but this one is true with the and logical operator both conditions must be true in order for us to execute this block of code if our temperature was 30 30 de C well then both conditions are true it is hot outside and it is sunny let's write a few more let's add else if else if the temp is less than or equal to zero and is sunny we will print something else it is cold outside I'll change the Emoji and it is Sunny let's set the temperature to be -5° C it is cold outside and it is sunny both these conditions are true so we do this instead you can link as many conditions together as you would like let's see if our temperature is within a certain range else if temp is less than 28 and our temp is greater than zero and is sunny to check to see if something is within a certain range there is a shortcut too py charm is recommending this we can simplify change comparisons so this effectively does the same thing if 28 is greater than our temp and our temp is greater than zero and it's sunny then we will print it is warm outside rather than hot and it's still sunny so let's say our temperature is 20° CSI and it's sunny it is warm outside and it is sunny now we have the not logical operator it inverts the condition we are checking to see if something is either not false or not true so let's check to see if it's not Sunny really I'll just copy what we have and paste it else if nut is sunny then that means it's cloudy and let's use a cloud Emoji so basically not does the opposite of what you're looking for we are checking if not is sunny is sunny is false then this condition is true okay let's say our temp is 208 is sunny is now false it is hot outside it is cloudy what if our temperature was Zero it is cold outside it is cloudy what if the temperature was reasonable like 20° C it is warm outside it is CL cloudy so not it inverts the condition if it's true it's now false if it's false it's now true all right everybody so those are logical operators they allow us to evaluate multiple conditions with or at least one condition must be true with and both conditions must be true and not not does the opposite it inverts the condition we check if something is not false or not true and well everybody those are local operators in Python hey everybody so today I got to explain conditional expressions in Python a conditional expression is a oneline shortcut for using an IFL statement if you're familiar with other programming languages this is also known as the trary operator it behaves similarly using conditional Expressions we can print or assign one of two values based on a condition here's the formula return X if our condition is true else return y here's a basic example we will create a variable for number just num let's say our number is five I'm going to print then within our print statement I will write a conditional expression following this formula I'll just copy and paste it let's check to see if our number is positive let's print the text positive if our condition what are we checking let's check to see if if num is greater than zero that means it's positive if this condition is false we will instead print whatever comes after else else negative number is five that will print positive if our number was neg5 well this condition would be false we would instead print negative let's go over another let's check to see if our number is even or odd let's set numb to be six this time I will assign the result to a variable our result equals take our formula let's assign even if our num modulus 2 is our number divisible by two does that equal zero else return odd then let's print our result result number is six that is even if it's five then it's odd assign even if our number is divisible by two else return odd let's create variables A and B A will equal 6 B will equal 7 let's create a variable of Max num equals follow our formula again return variable a if a is greater than b else return B between A and B which is the maximum number that would be B of seven let's find the minimum this time minum a if a is less than b else return B the minimum number between six and seven is six this time we'll take an age age equals 25 we will create a variable of status equals use our formula again return a string of adult if our age is greater than or equal to 18 else return a string of child then we will print our status our age is 25 that's greater than or equal to 18 we will print adult if our age was 13 then we are a child we will instead return child let's work with the temperature temperature equals 30° C so that's hot let's create a variable of weather assign a string of hot if our temperature is greater than 20 else we will return a string of cold what's the weather outside today based on the temperature it is hot if our temperature was 20 then the weather is cold okay last example we will work with a user role I will set this to be admin we will Define a variable of access level equals again follow our formula return the text of full access if our condition of user rooll is equal to a string of admin else we will return limited access our user role is an admin let's print our access level and we have full access but what if we were a guest well then we have limited access all right everybody those are conditional Expressions they're a oneline shortcut for the if else statement it's similar to the tary operator and other programming languages using conditional Expressions we can print or assign one of two values based on a condition you follow the formula of return X if our condition is true else return y if it's false and well everybody those are a few examples of conditional expressions in Python hey everybody in this topic I'm going to cover a few useful string Methods that you may be interested in then at the end of this video we will work on an exercise where we will validate some user input as we know a string is just a series of characters let's ask a user for their full name name equals input enter your full name the first method I'll show you well technically this is a function the length function will give us the length of a string how many characters is it we will find the length of our variable name after the user types in some input this function returns an integer I'll store that result within a variable uh let's just say result then I will print whatever the result is why don't you go ahead and type in your full name the length of this string in my example is eight characters that does include spaces too 1 2 3 4 5 6 7 8 if you ever need the length of a string there is the length function let's move on if we were to type our variable name followed by a DOT we have access to a whole bunch of different methods we have the the find method the find method will return the first occurrence of a given character the position let's find any spaces I'll store the results within a variable named result I will type in my full name the first occurrence of a space that's what we set is at position three when working with indexes we always begin with zero this first character would have an index of 0 then 1 2 3 that's why the find method returned three in place of four let's find the first occurrence of a capital B see it's zero how about oh for me that would be two so remember it's always the first occurrence if you need the last occurrence there is a different method which is all R find R meaning reverse we will find the last occurrence of an o that has a position of five 0 1 2 3 4 5 if python isn't able to locate a given character it will return ne1 let's find any I don't know uh Q's python could not find any lowercase cues the rfind method will return -1 if there are no results we can capitalize the first letter in a string by using the capitalize function name. capitalize this method will return a string I will reassign that to name then we will print our name capitalized I'll be sure to type in my name all lowercase since this is all one string only the first letter is capitalized even though I'm including a first and last name the upper method will take all of the characters in a string then make them all uppercase follow your variable that contains a string followed by Dot Upper then I will reassign the result to my name variable to overwrite it enter your full name all of the letters are now uppercase there is also lower to make all of the characters lowercase name equals name do lower yep all the characters are lowercase now the is digit method will return either true or false if a string contains only digits the result is a Boolean true or false I'll store that within a variable named result then print result so if I were to type in my full name is digit returns false there are not only digits within that string if my string was some combination of alphabetical characters and numbers this method will still return false it only returns true if my string only contains digits I'll just type in one 23 see that's true that is the isdigit method otherwise wi we have is Alpha name. is Alpha the is Alpha method will return a Boolean true or false depending if a string contains only alphabetical characters I'll type in my full name so the reason that this came up false is because my full name contains a space which is not an alphabetical character if I typed in my full name excluding any spaces this would now be true is Alpha would also return false if my name contained any sort of digits foro 1 23 and that is also false that is the is Alpha method now let's ask for a phone number phone number equals input enter your phone number with the phone number they typically contain dashes let's count how many dashes are going to be in somebody's phone number phone number dot count method let's count the amount of dashes so place a character within the account method this method will return an integer let's store that within a variable results equals phone number. count method so type in some phone number 1-23 4-56 7-8 901 we have three dashes within the string 1 2 3 that is the count method we can count how many characters are within a string we also have the replace method honestly the replace method is probably one of the most useful methods of strings we can replace any occurrence with one character with another replace let's replace any dashes with maybe a space this method will return a new string I'm going to reassign this to our phone number variable then print the phone number enter your phone number 1-2 3 4-56 7-8 901 so here's my new phone number but we've replaced all of the dashes with spaces even better yet we could eliminate all the dashes completely by replacing the dashes or another character with an empty string 1-2 3 4-56 7- 8901 here's our new phone number without any dashes we've replaced all dashes with an empty string no characters if you would like a comprehensive list of all of the string Methods available to you you can use the help function type in the data type Str strr meaning string then I will print whatever the result is here's a bunch of methods you might be interested in in the future capitalize case fold Center count en code ends with just to name a few all right everybody here's an exercise for you we will validate some user input we would like a user to enter in a valid username however there's a couple rules the username can be no more than 12 characters long the username must not contain any spaces and the username must not contain any digits let's assign a variable named username equals input enter a usern name first let's check to see if our user input is more than 12 characters long we can do that using the length function we will find the length of our username the length function returns an integer let's check to see if the length of our username is greater than 12 characters if it is we'll print a message your user name can't be more than 12 characters else we will print using an FST string well welcome whatever our username variable is let's try it I'll type in my first name last name then add a whole bunch of characters afterwards your username can't be more than 12 characters let's type in something that's under 12 characters yep and that appears to work okay so we have accomplished task number one our username can't be more than 12 characters next our username must not contain any spaces we can use the find method of a string username doind we will find any spaces that's a character if no spaces are found this method will return -1 using an else if statement I'll add not if the find method of username equals -1 if the result is not -1 meaning we found a space we will print your username can't contain spaces I'll type in my first and last name you might need to think of something that's underneath 12 characters your username can't contain spaces so we have accomplished rule number two three username must not contain digits we can use the is Alpha method of strings the is Alpha method returns a Boolean if a string only contains alphabetical characters so let's copy that I'll add another LF statement not username is Alpha then we will print your username can't contain numbers I guess technically is Alpha would check for spaces too but I'd rather have that be handled within a different if statement all right I'll type in a username I'll include some digits your username can't contain numbers all right I think we've accomplished this let me make up a username following these three rules yep it seems to check out all right everybody and that is a few useful string Methods that you may be interested in hey everybody in this topic I'm going to explain string indexing indexing allows us to access the elements of a sequence using a set of square brackets also known as the indexing operator using this set of square brackets following a string there are up to three fields that we can fill in we can access a starting point in the string an ending point and a step here's an example suppose we have a credit card number credit number equals and I'll just make up some number 1 2 3 4-5 6 7 8- 9012 d34 5 6 good enough if I need the first character within the string I can type Ty the name of my string variable followed by the indexing operator which is a set of square brackets the first position has an index of zero computers always start with zero so that's why the first index is zero then I'm going to go ahead and print this print credit card number at index of zero that would be one if I were to change the index to be one 0 1 that should be two index 2 would technically be three then four is the dash within our string as you can see here with the indexing operator there's up to three fields that we can fill in a start and and step if you have just one field listed without any colons it's assumed you're filling in the starting position so now what if you would like the first four digits of the string well we would type the name of our string variable indexing operator we'll need a starting index colon then an ending index the first four digits would be 0 colon 4 then I will print this and I'm just going to turn this first line into a comment yeah there we go we have the first four digits of our credit card number 1 2 3 4 just so you know with the ending Index this index is exclusive this first number would be 0er 1 2 3 4 so we did not include that Dash within the number the starting index is inclusive the ending index is exclusive so you can omit the zero in the beginning you could just say colon 4 python assumes the starting position will be the beginning of the string so that would work too let's get the next set of digits 56 78 credit number indexing operator Ator let's find where the starting index would be 0 1 2 3 4 5 5 colon 6 7 8 9 then we will print whatever is here the next set of digits is 5 6 7 8 maybe we need the last 12 digits well what we could do in that case we will take our string variable credit number set the starting index to be let's see 0 1 2 3 4 5 five colon if you need everything up to the end of the string you don't need to list an ending index just be sure to add that colon python then assumes you need everything up to the end of the string so I will print whatever we have then we should have everything besides the first four digits yep 5 67 8 9 012 34 5 6 you could also use a negative index credit number if you need the last last character in a string you would set the index to be -1 then I will print this print credit number at index of -1 that would be 6 -2 is 5 -3 is 4-4 is three and then 5 would be that Dash right here yeah you can use negative indexes too let's talk about step using the step field we can access the characters in a string by a given step we can count by twos or we can count by threes so here's an example so let's take our credit number if we're not filling in the starting or ending Fields but we need a step we would need two colons then python is assuming everything from the beginning of the string to the end then our step will be two this will print every second character within our string yeah here we are we have 1 3 Dash 6 8 9 1 so on and so forth if I were to change the step to three we would count every third character beginning with 1 4 6 Das 1 3 6 all right here's a practical example let's create a program to get the last four digits of a credit card number I'm going to assign this to a new variable last digits equals our credit number indexing operator so we need the last four digits where would the starting index begin well we could use negative indexing this last digit is1 -2 -34 we will begin at4 colon we can omit the ending index python assumes we need the rest of the string then really that's all we need so let's print I'll use an F string uh maybe some xes maybe we're hiding somebody's credit card number except the last four digits okay then variable last digits all right and here's our credit card number where only the last four digits are visible hey you know what let's add one more exercise let's reverse the characters in The String I'm going to reassign credit number equals credit number if we need the entire string we don't necessarily need a starting index or an ending index but for the step this will be negative -1 will reverse a string then let's print whatever our new credit card number is print credit number and yeah there is our credit number backwards to reverse a string you set the step to be NE -1 so yeah everybody that is string indexing in Python we can access elements of a sequence using the indexing operator which is a set of straight brackets you can list a starting position ending position and even a step if you need to skip over characters but yeah that is string indexing in Python hey everybody in this topic I'm going to explain format specifiers format specifiers when used in the context of an F string they allow us to format a value based on what flags are inserted following your value you would type a colon and then some Flags depending on what flags you insert it will format your output a certain way you could add decimal point Precision allocate space zero pad values left justify right justify Center align all sorts of things let's have some practice I'll create three prices price one price two price three price one will be 3.14159 these values aren't in and cents yet but they will be price two will be [Music] is price two price three is price three within our placeholder following the value we can add a Colin then some Flags those flags are the format specifiers they will format our value a particular way depending on what we insert after the colon to add decimal point Precision you would type after the colon dot then the amount of decimals to be displayed maybe two then F meaning Flo Point number let's do that with price two and price three colon. 2f price one is now 3.14 price two is 987 65 price 3 is 12.34 I think I'm going to add some dollar signs before the placeholder yeah that's much better for Less Precision maybe one decimal place you can change the two to a one so. onef each number only displays one decimal .1 6.3 whereas in 3F would display three decimal places1 142 650 340 even though price two and price three only have two decimal places in the original numbers we will concatenate some additional zeros to allocate space to display a value after the colon add some number some number for that many spaces how about 10 each value now has a total of 10 spaces to display the output 1 2 3 4 5 6 7 8 9 10 if you were to preedee a number with zero well these numbers would be zero padded each number is now zero padded to left justify a value you would use a left angle bracket all these numbers are now left Justified then we have all of the space after they're all uniform right justify would be a right angle bracket and I believe that's the default cental line I believe is the carrot symbol yep our numbers are now centered if you have any positive values and you would like to display a plus sign just use plus any positive number is preceded with the plus sign any negative number is preceded with the negative sign or you could use a space for any positive numbers so colon space these numbers are lined up evenly even though we have a negative number number in here there is a thousand separator which is a comma we should probably increase the value of our prices 3,00 9,870 1,200 each thousand's place is now separated with a comma we could also mix and match Flags I would like a thousand separator along with decimal point Precision of two decimal places and why not I will preedee each number with a plus sign if it's positive yep here we are so based on what you're looking for you can add some combination of flags so yeah those are format specifiers everybody within your placeholder insert your value a colon then certain Flags based on what you're looking for exactly but yeah those are just a few formats specified in Python hey everybody in this topic I'm going to explain while Loops a while loop will execute some code while some condition remains true here's an example we'll use an if statement first we will ask a user for their name name equals input enter your name if our name is equal to an empty string that means the user didn't type in anything let's let's print a message you did not enter your name else we will print using an F string hello our users's name if I were to skip this prompt we would execute this if statement then we continue with the rest of the program what if I would like to continually prompt the user to type in their name we can't continue until they type in something something well we could replace this if statement with a while loop while this condition is true continue to execute this code within the while loop I'm going to reprompt the user to type in a name then if we were to exit the while loop then we will print hello whatever your name is so let's run this enter your name I'm going to hit enter you did not enter your name enter your name no no no okay I give up I'll type in my first name hit enter hello whatever your first name is while this condition remains true execute this code potentially forever until this condition is no longer true so that's one of the main benefits of a while loop if it's not true then you exit out of the while loop and that's why we're able to continue then print our name hello name you do want some way to escape out of the while loop otherwise you'll run into what's known as an infinite Loop so let's say while name is equal to an empty string we will print you did not enter your name so I'm going to hit enter so we are stuck in an infinite Loop we can't actually escape this Loop we didn't give ourselves an exit strategy that's why previously we repr prompted the user to type in something we're giving them a chance to escape in a way it kind of works like an if statement but instead of executing some code once it's potentially infinite here here's another example this time let's ask for a user's age age equals and I will convert the input to an integer enter your age we'll need the user to type in a positive number while age is less than zero let's print a message to let the user know that they can't do that age can't be negative then we need some strategy to escape let's reprompt the user to enter in their age once they type in something that's valid we can escape out of the while loop so let's print using an FST string you are age years old so enter your age I'm going to say negative 1 age can't be negative --2 1 million okay I give up how about 21 you are 21 years old so that was another example while our age variable is less than zero repeat this code forever let's go over example three I'm going to introduce some logical operators we will have the user type in a food they like food equals input enter a food you like but in order to escape I need to press Q to quit while food is equal to the letter Q continue this while loop however I'm going to make one change we want to exit the while loop when they press Q so you could say while not food equals Q So within this while loop let's print the food that they stated that they like I'll use an F string you like your variable food then we will prompt the user to enter in another food that they like enter another food you like Q to quit then once we escape the while loop we will print just buy okay enter a food you like C to quit I like pizza you like pizza I like sushi you like sushi I like Ramen you like Ramen okay this program kind of lame so I'm going to press Q to quit and we escape the while loop we have printed by so you could do something while something is not true by using the not logical operator all right last example example four we will use the or logical operator we'll ask a user to type in a number between 1 and 10 let's say num equals input enter a number between 1 through 10 then I will typ cast the input as an integer while our number is less than one or our number is greater than 10 let's reprompt the user let's print using an FST string our variable num is not valid then we will reprompt the user enter a number between 1 and 10 once we escape the while loop then we will print our number using an FST string your number is our variable num enter a number between 1 through 10 0 Z is not valid 1 100 nope uh five your number is five that's an example example of how you can add logical operators to Wild Loops while this condition is true or this condition is true execute this code Forever all right everybody so those are while Loops a while loop will execute some code while some condition remains true it's fairly useful for verifying user input if a user types in some input that is not valid you can reprompt them and there's many other uses that we'll discuss in the future but yeah those are while Loops in Python why hello everybody in today's video we'll be creating a compound interest calculator in Python for those that don't know interest is a charge for the privilege of borrowing money to some individual or organization when you place money in a bank account you typically acre interest we'll create a program to tell you what your new balance will be after acre interest for so many years but the user is going to decide the initial principle that's the investment the rate of interest and the time and years that this balance has been acre interest so let's begin let's declare three variables a principle a rate that is rate of interest and time time will be in years we've recently learned about while Loops I would like to include those within this program just so we get the hang of using them we will ask the user to type in an initial principal investment we will continue to prompt the user to type in a principle that's above zero our condition will be while principal is less than or equal equal to zero we will take our principal assign it some user input enter the principal amount then we would like to typ cast our input as a floating Point number if our user input principal is less than or equal to zero we need to inform the user principal can't be less than or equal to zero so I'm going to test my program by printing the principle at the end just temporarily enter the principal amount I can't type A negative number and continue what if my investment was $1,000 principal can't be less than or equal to zero how about zero nope can't do that either is a th000 okay yep a th000 works that is for the principle let's copy this while loop paste it replace principle with rate this is the rate of interest enter the interest rate interest rate can't be less than or equal to zero and let's copy this again paste it change rate to time let's typ cast our input as an integer because we're working with whole years enter the time in years time can be less than or equal to zero I'm going to print my principle rate and time we have principle rate time okay we know that principle Works enter the interest rate can my interest rate be ne1 no it can't can it be zero nope how about 10 10% all right that works time can time be zero no it can't can my time be netive 1 no it can't what about 3 years all right so we know that our while Loops are working now here's the formula to calculate interest let's say our total that's our total balance equals our principal times 1 + r rate / 100 I'm going to enclose this function with the set of parentheses this portion of our function will take our interest rate which is a whole number then create a decimal enclose this function within the power function raise this function to the power of time and that is how to calculate compound interest then we will print the New Balance I'll use an FST string balance after our variable time the word years I'll add a placeholder we will add our total then I'll include a dollar sign maybe this will be in dollars but pick any unit of currency you would like I will format this variable with the format specify fire we will display two decimal places 2f okay let's try this enter the principal amount I invest $1,000 into maybe the stock market the interest rate is maybe 10% this year the time in years will be one so after one year at 10% interest my new balance is $1,100 let's try it one more time for good measure maybe $500 with an interest rate of seven over 2 years your new balance would be $572 45 all right now there is another way of writing this program what if we would like to allow the user to enter in values that are equal to zero while principle is less than zero if principal is less than zero principal can't be less than zero let's do that for rate interest can't be less than zero time time can't be less than zero here's what happens to our program remember that we're declaring our variables at the top uh nothing happens we go straight to the results so the reason that this is happening is that when we reach the wild Loops this condition is false from the beginning we never end up entering these while Loops we skip over them because these three conditions are all false we can write a different variation of this while loop where we could say while true true is a Boolean that means this while loop will continue forever unless we explicitly break out of the while loop we're going to add an else Clause else we will break break will break out of a loop with our second while loop change rate is less than zero to while true then we will add an else CLI laws else break out of the loop while true else break out of the loop we should be able to enter zero values in now enter the principal amount 0 0 0 balance after 0 years is 0 this should work the same as before but we should be allowed to enter in zero values $1,000 interest rate of zero after one year is still $1,000 well okay then everybody I thought that would be an interesting project to create now that we know how while loops work you could write either a standard while loop with a condition such as principal is less than or equal to zero or you could say while true this Loop would continue forever you would need to explicitly break out of the while loop using this break keyword which we'll cover again in four Loops but yeah that is a compound interest calculator in Python hey everybody in this topic I need to explain for Loops a for Loop will execute a block of code a fixed number of times you can iterate over a range a string a sequence anything that is considered iterable I'll have more examples for you in future topics there is a lot of overlap where you could use either a while loop or a for Loop but for Loops tend to be better in situations where you have to do something only a fixed number of times here's an example suppose we need to count to 10 if we were to use a for Loop we could write something like this we would type four then we would need some sort of counter typically you see people write x 4 x in then we will use the range function what number would we like to start at I would like to start at 1 then count to 10 but the second number is X exclusive so really we're going to write 11 if we want to count to 10 so then colon then hit enter whatever code you would like to repeat a certain number of times you will list underneath the for Loop and make sure the code is indented too I will print whatever our counter X is when I run this code we will begin at one then stop once we reach 11 so yeah there we are we have begun at one and we have counted all the way to 10 so that's the basic syntax for for Loop for some counter really you can name this anything sometimes you'll see people name this as counter and that would work too but let's stick with x in some range where would we like to begin where do we stop okay now let's count backwards let's start at 10 then count down to zero when we escape the for Loop let's print happy New Year when we print Happy New Year we are outside of the for Loop to count backwards you can enclose your range function within the Reversed function reversed so we begin at 10 count down to one then print happy New Year in this case to count backwards you would enclose the range function within the Reversed function there is an additional parameter too you could add that is the step if you would like to count by twos you would add comma two so I'm going to get rid of happy New Year let's print the numbers 1 through 10 but we will count by twos and this does begin at one though so 1 3 5 7 9 if you were to change the step to three you would count by threes beginning at 1 4 7 10 so the range function isn't the only thing you can iterate over you can iterate over a string let's say we have a credit card number credit card equals I'll make up some credit card number with dashes that is good enough for X in credit card print x x will hold our current position at first it'll be one then 2 3 4 dash so on and so forth so here's our credit card number 1 2 3 4-5 6 78 I think you get the idea so you can iterate over a string with the for loop as well we'll have a few projects involving that there are two useful keywords as well these aren't exclusive to for Loops you can use these within while Loops as well they are continue and break suppose we going to count to 20 for X in range we will begin at one stop at 21 I think this is kind of a dumb example but it gets the point across 13 is considered an unlucky number right what if our counter reaches 13 I would like to skip over it well we can do that with the continue keyword if x is equal to 13 we will continue and skip over that iteration else we will print whatever our counter is so let's take a look yeah we have the numbers 1 through 20 but we have skipped the number 13 to skip over an iteration you can use the continue keyword whereas the break keyword we will break up of this Loop entirely if x is equal to 13 then break so yeah we have only counted to 12 once we reach 13 we have escaped the loop so yeah everybody those are four Loops you can execute a block of code a fixed number of times you can iterate over a range a string a sequence anything that is considered iterable there is a lot of overlap where you could use either a while loop or a for Loop while Loops tend to be better if you need to execute something possibly infinite amount of times such as when you're accepting user input for example but yeah everybody those are four Loops in Python what is going on everybody in today's topic we're going to be creating a countdown timer in Python we'll be using what we learned in the previous topics let's begin we'll need to import the time module there's a pretty cool function within the time module that is the sleep function type time do sleep add a set of parenthesis within the set of parenthesis our program will essentially sleep for a given amount of seconds like three after 3 seconds let's print something this is just a demonstration times up when I execute this code nothing happens for 3 seconds but after 3 seconds passes it displays our message times up so you can use the sleep function of the time module to sleep for a given amount of time we will ask the user how long would they like to set the timer for we will create a variable let's say my time my time will be in seconds we will create a prompt enter the time in seconds then we should typ cast our input as an integer we'll need to create a loop we could use either a while loop or a four Loop there's a lot of overlap where you could use either one I'll use a four Loop in this case four we'll need some sort of counter X in our range Z through my time after each iteration we will sleep for 1 second Let's test what we have so far I would like to sleep for 3 seconds I think that's approximately three but now we are going to print whatever X is print x x is our counter 0o 1 2 times up we're getting somewhere but I would like to count backwards what we could do is enclose our range function within the reverse function but another technique that we can use is by using a step let's replace zero with my time then end at zero but we will set the step to be Nega -1 then we can increment backwards using this function that's another technique too to count backwards so let's wait for 3 seconds 3 2 1 times up now let's display a digital clock of some sort but we would have to calculate how many hours minutes and seconds there are so let's calculate seconds seconds equals x x is our counter remember modulus 60 within our print statement we'll use an F string we are displaying hours minutes and seconds I'll add some placeholders for each of these fields we have seconds with our digital clock we can't go above 60 for either seconds or minutes that's why I'm using modulus 60 the modulus operator gives you the remainder of any division let's begin at 11 so 11 10 9 so it is counting down but I would like to add some zero padding and we can do that with a format specifier after seconds I will add colon I need to display two digits then zero pad those digits let's try that again I will wait for 11 seconds seconds 11 10 9 yeah and we do have some zero padding so that's looking more and more like a digital clock let's add minutes then so to calculate minutes let's assign variable minutes equal to x / 60 because there's 60 seconds within a minute but then I'm going to typ cast the result as an integer modulus 60 we would not like this field of minutes to go above 60 so let's add a placeholder we're displaying minutes format specifier 02 now I'm going to wait for 65 seconds that is 1 minute and 5 Seconds then I just want to be sure that we go below a minute yep it's working then let's calculate hours oh by the way to stop your program from running hit this red square up in the corner Corner let's calculate hours hours equals x / 3,600 there's 3,600 seconds in an hour then we will typ cast the result as an integer within our FST string we will display ours format specifier 02 then I will run this program let's wait for for 3,65 seconds that is 1 hour and 5 Seconds and I just want to be sure that we go below 1 hour yeah all right so that works so the reason that I didn't add modulus 24 I don't have days within my fstring we can display any amount of hours I will exclude modulus 24 all right everybody well I thought that'd be some good practice with working with loops we should try and do a as many exercises as we can and yeah that is a countdown timer program in Python hey everybody so I guess in today's topic I'm going to be explaining nested Loops it looks like so a nested Loop think of it as a loop found within the code of another loop you have a loop right any code within that Loop is indented underneath that Loop well you could have a looping structure found within the code of another looping structure the loop on the outside is the outer loop the internal Loop within the outer loop is known as the inner loop where you'll encounter nested Loops it's really situational you could have a while loop inside of a while loop a for Loop inside of a for Loop a for Loop inside of a while loop a while loop inside of a for Loop Etc so here's a demonstration let's begin by displaying the numbers 1 through 9 but we'll use a loop for x x is our counter in range 1 comma 10 remember that the second number in this case 10 that's exclusive then I will print our counter X this program will print the numbers 1 through 9 now we have an exercise at the end of this topic I should probably explain this feature so with a print statement we end each print statement with a new line character if I need all of these numbers on the same line at the end of my print statement I can add comma end equals an empty string normally with a print statement each ends with a new line character but we can set that to be something else so when I run this again all of these numbers are on the same line or you could add a different symbol like Dash or a space each of these characters is now separated with the space but let's stick with an empty string okay so we have used a loop to count the numbers 1 through 9 what if I would like to repeat this three times Well I could create another loop for X in range you could say 1 comma 4 or you could just say three either way whatever code is within this Loop will be executed three times let's cut our original for Loop then place it within the code of our new loop our outer loop will have this code repeat entirely three separate times uh but we do have one thing we need to pay attention to we have two counters with the same name you'll want to be sure that they're different let's rename the counter of the inner loop to be y instead of X and be sure to change that here as well now when I run this code we're completing let's see 27 iterations to exit this four Loop we need to count the numbers 1 through n once we do so that is one iteration of the outer loop but our outer loop is saying hey we still need three total iterations now if you would like these on separate lines let's make this look a little different let's add each iteration of the outer loop onto a new line so within the outer loop but not within the inner loop I'm going to create just a blank print statement this will just print a new line let's try this again with the inner loop we count the numbers 1 through n after we exit the for Loop we will print a new line then repeat this all over again until our outer loop is satisfied so that's basically a nested loop it's just a loop that's inside of another looping structure so let's create a project we're going to print a rectangle made of some symbol that we set we'll have the user type in how many rows and columns this rectangle will have we'll reuse this code that we have already written so this time let's accept some user input rows equals input enter the number of rows then we should typ cast this input as an integer let's copy this line paste it change rows to columns for the second line enter the number of columns then let's create a symbol symbol equals input enter a symbol to use we already have this rectangle structure right think of it as the outer loop is in charge of the rows let's change in range three to in range rows the in Loop will be in charge of the columns for y in range columns we will print our symbol whatever the user chooses so let's try this again enter the number of rows how about four rows 10 columns I'll use a dollar sign so here's our rectangle we have four rows then 10 columns 1 2 3 4 5 6 7 8 9 10 let's try it one more time three rows five columns and I'll use an asterisk yep three rows five columns so yeah that's a nested Loop really it's just a loop that's inside of another loop Loop the type of loop really doesn't matter as well as what's within each loop it's just a situation where you have a loop inside of another loop and yeah those are nested Loops in Python well hello everybody today I will be explaining a few different types of collections in Python there's four general purpose collections three of them are lists sets and tles there are also dictionaries but I'll save that for the next topic because they can be kind of tricky a collection I would think of them as a single variable and I'm saying that within quotes that is used to store multiple values that's how I would explain a collection to a beginner for example let's say we have a variable variable fruit fruit equals some value like apple and then I can print this fruit which is Apple I could turn this variable into a collection by surrounding my values with either a set of square brackets for a list curly braces for a set or parenthesis for a tuple let's begin with the list if I would like to store more than one value in this variable I will surround my values with a set of square brackets this variable is now a list I can store multiple values separated with a comma not only do we have an apple in this variable but we have an orange a banana and coconut one naming convention that I like to use if I declare a collection such as a list set or toule I like to take the variable name and make it plural just so that it's more obvious that this is a collection of values technically in the English language fruit would still be plural English is a weird language we now have a list of fruit named fruits if I were to print my list this is the result we have all of our values enclosed with a set of square brackets to access one of these elements found within your list you can use the index operator much like what we can do with strings the first element would have an index of zero that would print my value Apple index of one would be my orange two is banana three coconut what about four we don't have a value there list index out of range each value in a collection is also known as an element if we attempt to access an element that's not not found within our collection you'll run into an index error with the index operator you could set a beginning index an ending index and a step I would like the first three elements you could say zero colon three that would give me Apple orange banana technically you don't even need the zero you need that colon though we can even use a step I would like every second element apple banana it's every second element beginning from index zero maybe I would like my fruit backwards I'll set the step to be 1 coconut banana orange Apple you can use the index operator with collections much like you can use with strings another cool thing you can do too with collections is that you can iterate over them with the for Loop for X in my collection fruits what would we like to do I will print whatever X is so we have iterated over our list Apple orange banana coconut now X isn't really too descriptive what you'll see some people do is that with their collection name it's plural their counter will be the singular version of that word if our collection name is fruits let's rename X as fruit singular it's not mandatory but that's a common convention it's more readable that way for every fruit in fruits If This Were cars you could say for car in Cars our counter is storing whatever value is within our collection so what are all the different methods that we can use with collections to list the different methods that are available to a collection you can use the dur function within this function add your collection fruits but we would need to print this let's surround this function with a print statement these are all in alphabetical order we have attributes which I have not explained yet but I in a future topic but if we scroll to the end we have a bunch of different methods that this list can perform append clear copy count extend index insert pop remove reverse and sort if you would like a description of each of these methods there is a help function help add your collection to the parentheses then we would need to print this here's the description of all the methods and attributes for example we have our sort method and here's a description sort the list in ascending order and return none and then a bunch of other stuff if you ever forget what you're capable of with a list or other collection you can always use the help function to print a description of the attributes and methods available if you need the length of how many elements are within a collection there is the length function return the length of my list fruits then let's print it there's four elements within my list the length function returns four if I were to add an extra element like a pineapple then that number would be five let's remove that using the in operator we can find if a value is within a collection is our value Apple in fruits but then we would need to print this this operator will return a Boolean so let's print whatever that is is Apple in fruits that is true but is pineapple pineapple is not it's false you can use the in operator to find if a value is within a list and that applies for your other collections too with lists they're ordered and changeable duplicates are okay we can change one of these values after we create our list let's take fruits at index of zero I will set this equal to be a pineapple then let's iterate over our fruit using a for Loop okay the first element is no longer an apple it's a pineapple then orange banana coconut using an index you can reassign one of the values if I were to change zero to one well now we have an apple pineapple banana coconut let's cover some of the methods that are found within a list we can append an element type the name of the list do append what would we like to append to the end of this list let's append a pineapple I'm going to get rid of this for Loop I'm just going to display my list there we have an apple an orange banana coconut pineapple to add an element to the end of a list use the append method to remove an element you can use the remove method fruits. remove let's remove our Apple our apple is no longer there we have an orange banana coconut using the insert method we can insert a value at a given index fruits. insert list an index zero would be the beginning then a value pineapple now we have a pineapple Apple orange banana coconut the sort method will sort a list for roots. sort these are all in alphabetical order now apple banana coconut orange to reverse a list you would use the reverse method fruits. reverse coconut banana orange Apple however these are not in Reverse alphabetical order these elements are reversed based on the order in which we place them if you would like reverse alphabetical order you can first sort and then reverse now we have orange coconut banana apple to clear a list use the clear method fruits. clear all of the elements are gone we can return the index of a value let's return the index of Apple fruits. index list an element then we will need to print this let's print the index that is returned the index of Apple is zero coconut that would be three what if we don't find a value like a pineapple well we have an error pineapple is not in list you could count the amount of times that a value is found within a list because duplicates are okay fruits. count let's count how many bananas are in this list banana then print it one banana is found within this list how about pineapples there are zero now those are lists surround your values with a set of square brackets these values are ordered and changeable duplicates are okay now let's talk about the next collection which is a set to create a set surround your values instead with with a set of curly braces our collection of fruits is now a set a set has different benefits the values are unordered and immutable meaning we can't alter these values however we can add and remove elements a set does not include any duplicates I'm going to delete these methods then print fruits we have all of the same values but they're not in the same order as they were originally a set is unordered if I were to run this again they will likely be in a different order see now we have a banana apple coconut orange to display all of the different attributes and methods of a set you can use the dur function and here's all of them some of these methods are a little more advanced but there's a few we might recognize like add clear copy for an in-depth description of these methods you can use the help function much like what we did before to find the length of our set we can use the length function which is four we can use the in operator to find if a value is found within this set unfortunately pineapples are not within our set now if I was to use the index operator of my set this is what would happen we have an error set object is not subscriptable we're not able to use indexing on a set because they're unordered much like what we can do with a list or string we can't change the values of a set but we could add a remove elements let's use the add method to add guess what a pineapple that is okay orange Apple pineapple coconut banana we can remove an element fruits. remove let's remove our Apple our apple is gone coconut orange banana we can pop the pop method will remove whatever element is first but it's going to be random though orange coconut banana apple coconut banana apple banana coconut you can clear fruits. CLE the elements of our set are gone those are a few of the more useful methods for beginners as a summary a set is a collection that is unordered and immutable you can't change the values but adding and removing elements is okay no duplicates are allowed let's try that real quick I'm going to add a second coconut yeah see we only still have one coconut sets may work well if you're working with constants maybe colors for example you need to find if a color is within a set all right now lastly let's talk about tupples a tupple is a collection that is surrounded with a set of parentheses topples are ordered and unchangeable duplicates are okay one benefit of a topple over a list is that topples are faster than lists if you're working with a collection and it's okay if the collection is ordered and unchangeable you might as well use a tupple because it's faster when I print our topple all of these values are surrounded with a set of parentheses again we have the dur function to display the attributes and methods there's not as many for a tle for methods we only have count and index again there's also help to display a description of these attributes and methods you can find the length of a tle with the length function we have five elements within here using the in operator we can find if a value is found within our tupple our pineapple is not within our fruits so there's only two methods we have access to let's find the index of Apple fruits. index Apple then I will print whatever is returned apple is found at index zero there's also count fruits. count how many coconuts are found within our tupple fruits count the Coconuts then print this how many coconuts we have two coconuts and then again with any of these collections they're iterable so you can iterate over them using a for Loop for fruit and fruits yep Apple orange banana coconut coconut all right everybody so those are collections think of them as a single variable used to store multiple values there's four general purpose collections for beginners lists sets tles and then dictionaries which we'll talk about next each of them has unique benefits lists are ordered and changeable duplicates are okay a set is unordered and immutable but adding and removing elements is okay no duplicates allowed a tupple is ordered and unchangeable duplicates are okay and they are faster than lists use topples if you can over a list but yeah those are a few collections in Python hello everybody today we will be creating a shopping cart program this program will be an exercise to follow the previous lesson on lists sets and tles the more that we practice with those collections the better we'll be at using them so I thought we'd create an exercise to get the hang of it before moving on in this program we will have two lists Foods these lists will be empty we'll declare them but not use them quite yet and prices then a total total equals z the reason that I'm not using topples is that tles are unchangeable we're going to ask a user what food they would like to buy we can't depend any elements to a tle we're not using sets because sets are unordered I mean I guess technically you could but at the end of this program I'm going to print our shopping cart in order so I think lists would probably be the best we have an empty list of foods and an empty list of prices we'll use a while loop while true if our condition is set to True we'll need some way to break out of the while loop we'll need a break statement somewhere we'll get to that later we will ask the user what food would they like to buy let's declare variable food equal to input enter a food to buy to exit the while loop you need to press Q Q2 quit then let's check if food is equal to Q lowercase Q then we will break we're not done with the program but let's at least test it Pizza hamburger hot dog Q to quit okay it looks like it works now what if somebody types in uppercase q Pizza hamburger uppercase q well we can't actually quit after accepting our user input if food. lower method this will take our input make it lowercase just for a comparison let's try that again Pizza hamburger I'll type capital Q to quit and that is valid follow food with the lower method to temporarily make the user input lowercase just in case they type in capital Q if the user doesn't want to quit let's add an else statement else let's take our Foods use the append method then add whatever food the user typed in we'll also need a price let's ask a user for the price price equals input enter the price of let's use an F string a whatever food the user types in pick a unit of currency I'll pick dollars we are working with numbers we should typ cast our input as a floating Point number since we're working with prices so we will accept a price add our food item to our list of foods do the same thing with prices prices do append whatever the price was and that is the while loop Let's test this program again to be sure that everything's working pizza pizza will be $59 999 enter a food to buy Hamburger hamburgers will be 350 hot dog hot dogs will be 175 I would like to quit I will type either capital Q or lowercase Q both will work and we have escaped the while loop so the while loop is now complete outside of the while loop let's display our shopping cart let's print some decorative text maybe five dashes your cart then another five dashes I will then iterate over all of the elements found within my Foods list for every food in my list of foods let's print each food item let's take a look so far again we have a pizza the price was $5.99 hamburger the price was 350 hot dog 175 CU to quit Okay your cart that will display the individual list items if you would rather have these list items arranged horizontally in one line you can add this keyword end equals this end keyword will replace the new line character at the end of a print statement with some other character like a space let's try that again I'll try not to take too much time pizza $ 5.99 hamburger 350 hot dog 175 you to quit yeah that's much better we are horizontally listing all of the different items within our list you could revert back to the vertical list if you'd prefer that I'll keep my output like this then we will need to iterate and add up all the prices for every price in prices we do have a total variable that we declared let's utilize that total equals total plus price otherwise we could shorten this to plus equals price that would do the same thing then we will display the total print I'll use an F string your total is I'll add a unit of currency I picked the dollar sign whatever the total is okay let's run this program One Last Time enter a food to buy pizza which was $5.99 hamburger which was 350 hot dogs they are 175 CU to quit here's your shopping cart I'm just going to add one new line real quick right before we display the total just an empty print statement here are the results your cart Pizza hamburger hot dog your total is $124 all right everybody well that is a shopping cart program I thought this would be a fun exercise to follow the previous lesson on lists sets and topples and well yeah that is a shopping cart program in Python hey what's going on everybody so today I'm going to be explaining 2D lists 2D meaning two-dimensional you do also have the capability of creating 2D tuples I thought today we would use 2D lists just because they're pretty flexible a two-dimensional list is just a list made up of lists it's really useful if you ever need a grid or Matrix of data kind of like an Excel spreadsheet let's create three lists a list of fruit vegetables and meat I'm going to speed up this video feel free to pause if you need to catch up here I have three lists a list of fruit vegetables and meat each of these lists is a one-dimensional list to create a two-dimensional list well you would begin by creating a one-dimensional list let's create a list of groceries all I would need to do is add my individual lists as elements to the outer list the 2D list we have fruits vegetables and meats normally to print a list or your other collections you would print the name of the list in my list fruits I have apple Orange banana coconut to access or change one of the elements you would type the name of the list then use the index operator so fruits at index of zero is a pineapple again with a 2d list it's a little different if I were to print my 2D list of groceries we would lay out the entire 2D list flat we have individual lists separated with a comma all enclosed within a set of square brackets taking the elements found within our 2D list I'm going to line these up kind of like this it kind of represents a gitter matrix with rows and columns each individual list resembles a row each element resembles a column if I were to print groceries at index zero in place of returning one element found within one of the lists that would return an entire row so groceries at index zero is my fruits list groceries at index one is my vegetables list groceries at index 2 is my Meats list for one of the elements found within one of the rows you would need two indices if I need the Apple from the first row within my 2D list of groceries that would be row0 column Z it's kind of like coordinates row 0 column 0 that would be my Apple 01 which is an orange 0 02 is banana 03 is coconut for the next row I would set the first index to be one row one column zero that would be celery I'm going to speedrun this real quick just to show you all the different elements one one is carrots one two is potatoes if we try to access 1 three that index is out of range because we only have three elements within this row so then the next row would have an index of two column zero would be chicken 21 is fish 22 is turkey 23 is out of bounds to access an element from a 2d list you would need two indices in place of one because using just one would return the entire row like so now when you declare a 2d list you don't need to necessarily give each inner list a name we could do something like this I'm going to replace these names with the rows I'm just going to put these on a new line to make it more readable there that would work too just separate each inner list with a comma then enclose everything with the set of square brackets if you ever need to iterate over the elements of a 2d list you can use NE Loops if I were to use a single for Loop let's say for every uh maybe collection for every collection in groceries let's print what our collection is using a single four Loop would iterate over the rows but to also iterate over the elements found within each row we would use a nested Loop for every food in our collection let's print what our food is using nested Loops we can iterate over all of the elements found within our 2D list but I'm going to make this more organized like that grid structure we have I'm going to replace the new line character at the end of a print statement with a space then when we exit the nested loop I will print a new line by using just an empty print statement there that kind of resembles our grid structure we have rows and we have columns with two-dimensional collections you're not limited to just lists you could create a list of tles so the inner rows will be surrounded with a set of parenthesis you know this is also valid too or you could make a 2d tupple it's a tupple that's made up of tuples you could make a tupple made up of sets sets are enclosed with a set of curly braces here we have a tuple made of sets use whatever is best for your own programs let's go over an exercise let's create a two-dimensional keypad that you would normally find on a phone we have three data types a list a set or a tupple the elements in a set are unordered so we can't use that these numbers need to be in order if we have the option A tupple is faster than a list a tupple is ordered and unchangeable so we should use it if we can and that's perfectly fine let's create a 2d tupple this time I will name this 2D tupple numpad we have an outer set of parenthesis then an inner set of parentheses for each row we will have four rows the first row will be 1 2 3 the second row I'm going to put put this on a new line 4 5 6 the next row will be 7 89 then the last row will be an asteris character then zero then the pound sign so numpad in this case is a 2d tupple let's use a for Loop to iterate over every row this will be the outer loop for every maybe Row for every row in numpad let's begin by printing our row so we're printing every Row in our numpad but I'd like to remove the parentheses let's create a nested Loop for every maybe num for Num in row print whatever that num is we have one long vertical line let's replace the new line character at the end of our print statement with the space then when we escape the nested Loop let's print a new line and there is our telephone number pad you can see it's a grid made up of rows and columns so yeah that's a 2d list well a 2d collection it's a collection that's made up of collections then with our numpad we made a 2d tupple if you ever need a grid or Matrix of data a 2d collection would work perfect and there you have it everybody those are 2D collections in Python hello again everybody so today we're going to create a quiz game in Python let's declare all of the different Collections and variables that we'll need first we will need a tuple of questions a 2d tle of options my quiz will have five questions but you can add more or less questions then a tuple of answers a list of guesses we will be appending guesses to our list that's why we're using a list rather than a tupple a score variable which I will set to be zero then question number this variable will keep track of what number question we're on all right let's begin with our questions I have five here are my questions they're all science related feel fre free to choose your own this is what I have how many elements are in the periodic table which animal lays the largest eggs what is the most abundant gas in Earth's atmosphere how many bones are in the human body which planet in the solar system is the hottest these are the questions but we'll need options let's add four options for every question that's why we're using a two-dimensional tupple each inner tupple will consist of four elements they will be options A B C or D let's copy these elements then paste them within each tle this first element corresponds to my first question how many elements are in the periodic table I'll come up with some answers I'll add some answers for the rest of these tuples too we have a coule of correct answers the orders are c d a a b if you come up with your own options your answers may be different now that we have all of our different Collections and variables taken care of let's display each question I will iterate over our Tuple of questions they are iterable for every question in questions I'm going to print some decorative text I think that's probably good then I will print each question we're iterating over so let's see what we have so far there's all five questions after we display every question I need to display every option for every op option in options our options options is a 2d tupple let's add the index operator the index is going to be our question number variable it's a number so at first we're accessing options at index of zero then 1 2 3 4 5 we will print every option in options at a given row number Let's test this okay we have some options but all of these options are for the first question we will need to increment our question number so let's do that maybe here question number plus equals 1 that is much better before iterating the question number we will ask the user for a guess guess equals input enter a b c d in case the user types in something that's lowercase I will follow this input with the upper method to make the user input uppercase we will take our list of guesses use the append method add our guess to that list if our guess is equal to the answers tupple at index of question number that means the user guessed the right answer let's increase the user score score plus equals 1 then print the word correct correct else we will print incorrect I'll use an F string our answers at index of question number is the correct answer all right let's answer some of these questions C correct which animal lays the largest eggs um um definitely the whale because the whale is the largest creature right incorrect D is the correct answer what is the most abundant gas in Earth's atmosphere nitrogen correct how many bones are in the human body D that is incorrect A is the right answer which planet in the solar system is the hottest Mercury because it's closest to the Sun right wrong incorrect B is the correct answer we're keeping track of our answer successfully once we complete all the questions let's print the results I'm going to add some decorative text not necessary but I think it would look cool I will display the results we will iterate over all of the answers and the guesses print answers I'm going to set the ending character to be an empty string for every answer in answers print each answer I will set the ending character to be a space to separate each answer then I'll add a new print line let's do this with guesses change answers to guesses for every guess in guesses print each guess okay I'm going to run this again I'm just going to make up some answers a b c d a here are the correct answers here are the guesses I guess none of them right then we will print a score score equals take our score divided by I'm going to use the length function then pass in our questions how many elements are within our questions tble then I will multiply all of this by 100 to give us a percentage then typ cast this whole formula as an integer so we're basically just reassigning our score variable then let's print using an F string your score is our score variable then add percent I'm going to intentionally get all the answers right c d a a b here are the answers here are your guesses your score is 100% this time I'll try and get a few incorrect intentionally c c c c c your score is 20% all right everybody well that is a quiz game feel free to add more or less questions or come up with your own questions and that is a quiz game written in Python hey everybody in today's video I'm going to explain dictionaries a dictionary is one of the four basic collection types for beginners a dictionary consists of key value pairs they are ordered and changeable no duplicates allowed a few examples of key value pairs could be an ID and a name an item and a price but in today's example we'll create a dictionary of countries and capitals let's name our dictionary capitals capitals equals enclose your dictionary with a set of curly braces much like what you do with sets the first country will be the USA to add a value to this key type colon then some other value the capital of the USA will be Washington DC separate at each key value pair with a comma then we can add another key value pair so the capital of India that will be New Delhi We'll add two more China the capital is Beijing Russia the capital is Moscow I think that's good enough just as a reminder if you would like to see all of the different in attributes and methods of a dictionary you can use the dur function pass in your dictionary capitals then we'll need to print this here's all the different attributes and methods of a dictionary if you would like an in-depth description of all these attributes and methods you can use the help function uh that's herp help there we go so yeah that's just a reminder all right let's cover a few of the methods to get one of the values from a dictionary you would get the key type the name of the dictionary capitals doget let's get the capital of the USA then we'll print it the value associated with this key the USA is Washington DC if I picked a different country like like India well then we would get that Associated value which is New Delhi another thing if python doesn't find a key this is what will be returned let's get Japan which is not in our dictionary this method would return none we can use this within an if statement if capitals do get Japan if a value is returned then we will print that Capital exists else we will print that Capital doesn't exist so Japan is not in our dictionary that Capital doesn't exist but Russia is that Capital does exist that's how to check to see if a key is within our dictionary you can use the get method All Right Moving On Let's update our dictionary capitals do update So within a set of curly braces I will add a key then a value Germany followed by Berlin then let's print our dictionary I'll use a print statement print capitals yeah and there's Germany right there use using the update method we can insert a new key value pair or update an existing key value pair let's also change one of the existing values with our key USA let's update the capital to be Detroit yeah see the value has been updated the capital of the USA is now Detroit Michigan to remove a key value pair you can use the pop method then passing a key let's remove China China no longer exists within our dictionary it's gone you can remove the latest key value pair within a dictionary by using the pop item method capitals do pop item with pop item you don't need to pass in a key pop item will remove the latest key value pair that was inserted then we have clear capitals do clear that will clear the dictionary it's pretty self-explanatory the next few methods are a little tricky to explain to get all of the keys within the dictionary but not the values there is a keys method capitals dokeys I think I'm going to insert this within a variable Keys equals capitals do Keys let's see what happens when we print this the keys method will return all of the keys within our dictionary technically Keys is an object which resembles a list I haven't discussed object-oriented programming yet this is a little bit above our level if you ever need the keys in a dictionary you can use the keys method one use is that we can use that within a for Loop they're iterable for every key in capitals dokeys method let's print every key if at any time you need to iterate over all the keys you can use a for Loop to iterate over every key that is returned from the keys method of your dictionary there's also the values method to get all of the values within your dictionary there is a values method values equals capitals Dov values method then let's print our values like before with the keys method the values method will return an object which resembles a list let's iterate and print over every value within our dictionary for every value in capitals Dov values print every value here are all the values within our dictionary this next one is probably the most tricky it is the items method capitals do items I will assign what is returned to a variable named items then we will print items items returns a dictionary object which resembles a 2d list of Tes it's really complicated how might this be useful this time we're going to use a for Loop to print every key comma value in capitals do items method we have in essence two counters this time I will print using an F string f every key value pair I will print every key as well as every value in our print statement so there's our dictionary laid out we have iterated over every key value pair it's kind of an advanced topic but I thought I would at least bring it up now so yeah that's a dictionary everybody it's a collection of key value pairs they are ordered and changeable no duplicates allowed you have a bunch of different methods such as get up dat pop pop item clear then you can get the keys the values or both which is the items method we'll be using dictionaries in a few game programs we'll be making in the future and well yeah those are dictionaries in Python hey everybody today we will be creating a program to mimic a concession stand much like what you would see at a movie theater we will be utilizing a dictionary to keep track of a menu item and an Associated price more or less this is just a program to help us get used to working with dictionaries let's begin we'll create a dictionary named menu what items are on the menu will'll need an item and a price I'll think of some I'm going to speed up this video feel free to pause if you need more time and here's my menu everybody I thought of a few food items you might find at a movie theater concession stand pizza nachos popcorn fries chips soft pretzels soda lemonade movie theater popcorn is really expensive for some reason okay we have our menu a user is going to select specific keys from this menu depending on what the key is we can get the associated value to calculate a total to keep track of the user selected items I will create an empty list named cart I will also declare a variable named total to keep track of the total we need to lay this dictionary down flat to display it to a user well we do have the items method of a dictionary which we covered in the last video for every key value in our dictionary menu do items method the items method of our dictionary will return a key and a value during each iteration I'm simply going to print every key and value I'll use an FST string I will print every key colon space then a value let's take a look so far here's our menu I'll make a few changes the price will be in dollar and cents but feel free to pick your own unit of currency I'll precede my value with the dollar sign then using a format specifier I will display two decimal places 2f that's better I will line up all the keys after the key I will add a format specifier then allocate 10 spaces yeah look at that it's all lined up now before and after displaying our menu with this for loop I will add some decorative text let's say menu then outside of the for Loop I'll display a bunch of dashes yeah look at that let's move on to the next step we will ask a user for some input what item would they like to buy from the menu while our condition will be true if our condition is set to True we'll need to break out of this Loop one way or another we will ask for some user input food equals input select an item Q2 quit if food is equal to a lowercase Q then we will break Let's test it select an item Pizza nachos soda Q to quit yeah it works okay what if the user types in capital Q well we can't escape the while loop if a user types in capital Q we're assuming that they would like to quit when we accept our user input I'm going to add do lower method this will take our user input and make it all lowercase so we should be able to acknowledge any uppercase letters yeah it works cool let's add an LSI statement what if a user types in an item that's not on our menu well there is a get method of dictionaries if menu. getet pass in our food which is user input if the user selection is not within our menu as a key it will return none so we can use that else if menu .g get food is not none then we would like to append that food item to our cart cart. append our food item so outside of the while loop I'm going to print our cart temporarily just to test it okay select an item Pizza soda pretzel how about a potato Q to quit we have our pizza soda and pretzel but not our potato we don't want that in our cart because that's not on the menu yeah you can just add that line else if menu item. get food is not none that will complete our wild Loop let's calculate a total for every food in our cart let's take our total variable set this equal to Total plus then we need a value associated with a key plus menu. getet method get the food item found within our cart but I'm going to shorten this to Total plus equals menu. getet the value associated with this food in our cart I will also display that food item print print food I'm going to avoid printing our food item on every line I will set the ending character in our print statement just to be a space okay let's see what we have so far I would like popcorn soda pretzel C to quit popcorn soda pretzel then we will display the total I will print a new line print I'll use an upst string total is add a unit of currency total I'll add a format specifier 2f to display two decimal places I'm going to add one line of decorative text let's copy maybe this all right let's test it out select an item popcorn pretzel soda potato CU quit all right here's our cart popcorn pretzel soda we did not include the potato that was not found within our dictionary the total is $1250 well there you have it everybody that is a concession stand program the point of this program was to help us get used to working with dictionaries a dictionary is a collection of key value pairs such as an item and a price and yeah that's a concession stand program in Python well hello again everybody it's me in today's topic I'm going to show you how we can generate some random numbers in Python then at the end of this video as an exercise we're going to create a number guessing program let's begin we will be importing the random module type import random the random module gives us access to a lot of useful methods involving random numbers for a comprehensive list you can use the help function pass in the random module and then we would want to print this here's what we all have access to we have a shuffle method set State seed sample random range random random int random bytes and there's a ton of others but we'll discuss a few of the more useful methods for beginners for a random whole integer maybe you're rolling a six-sided dice you would type the name of the random module dot that a method for a random whole integer type Rand int add a set of parentheses within the set of parentheses you will list a range if I'm rolling a six-sided dice I would like the numbers 1 through six 1 comma 6 then I will assign what is returned to maybe a variable print whatever my number is my random number is a four 3 1 4 all right I tend to play a lot of Dungeons and Dragons we use polyhedral dice that have more or less than six sides there is a 20-sided dice for a random number between 1 and 20 I would set the range to be 1 comma 20 here I rolled a 16 and a s and an 8 within the Rand int method you can place variables as well as long as they contain numbers I will create a variable named low I'll set that equal to one and a variable named High I will set that to be 100 I will replace the numbers with my variables that behave as numbers give me a random integer between my low variable and high variable so between 1 and 100 in this example I have rolled a75 now in 88 if you need a random floating Point number you can use the random method random. random then let's assign this to a variable number equals the random method of the random module that would return a random floating Point number between 0 and 1 you can pick a random Choice from a sequence in the future we're going to create a game of rock paper scissors let's say we have a tuple of options options equals rock paper scissors we are accessing the random module dot then use the choice method place your sequence within the choice method give me a random Choice from options I will store this within a variable let's say option equals random Choice from my options then I will print the option our computer has generated scissors paper rock so the choice method is a great use for games if you ever need a random element now there's also Shuffle this time maybe we have a deck of cards cards equals I guess I'll use a list this time I have a list of cards that you would normally find within a deck of playing cards well besides the suit 2 through 10 Jack queen king Ace using the shuffle method I can Shuffle this sequence access the random module do shuffle pass in your sequence in my case it's cards then I will print cards yeah look at that my cards are now shuffled in the future we'll be creating a game of Black Jack the shuffle method will be used then to shuffle our deck of cards those are a few methods found within the random module for some practice let's create a number guessing game as an exercise hey everybody so today we're going to create a number guessing game using python this is a project meant for beginners by completing this project it will help us reinforce our understanding of previous topics let's begin we will import the random module we'll need to pick a random number the random module is going to handle that for us what is the arrange of random numbers for our number guessing game we'll store those as variables we will have one variable named lowest number I'll set that to be one as well as a variable for highest number which I will set to be 100 feel free to pick a different range if you would like I'll set the range to be 1 through 100 a random number will be selected between this range which will be stored within a variable named answer what is the correct answer so to choose a random number between these two values we will access the random module called the Rand int method we will choose a random integer between these two values the two arguments will be lowest num comma highest num for the second argument let's perform a test run I will print my answer the number is going to be between 1 and 100 okay we know that that works here's a few more variables we need to keep track of the number of wrong guesses which I will store as a variable named guesses we want the user to keep guessing as long as our application is running we will create a Boolean variable of is running which we will set to be true once the user wins the game we will set is running to be false we will print a welcome message let's say python number guessing game we will prompt the user I'll use an F string select a number between I'll add two placeholders select a number between our lowest number and our highest number python number guessing game select a number between 1 and 100 now if I was to change the range of these variables that should be reflected temporarily I changed the lowest number to be 10 and the highest number to be 1,000 but let's set that back between 1 and 100 is good we'll need a while loop to continue the game each round we will say y while is running since is running is a Boolean we don't need to say while is running equals true we can just say while is running while this value remains true continue playing the game we will ask the user for some input we will create a local variable of guess guess equals use the input function then enter a prompt enter your guess there's one thing we want to check python number guessing game select a number between 1 and 100 and to your guess what if somebody doesn't type in a number like they type in the word Pizza we should let the user know that that's an invalid guess we'll write the following if statement if our guess use the is digit method if our guess is a digit a number then we will execute any code underneath this if statement for the time being I'll WR pass we'll get back to that later else we will do something else let's print the following print invalid guess let's copy this print statement because I'm lazy and I don't feel like typing it out please select a number between our lowest number and our highest number let's try that again I will guess Pizza which isn't a number and we get the message invalid guess please select a number between 1 and 100 all right that works underneath our if statement we'll write the following once we get a guess that is a digit we need to convert it to a number because when you accept user input it's a string we will reassign our guess equal to typ cast our guess as an integer then increase the number of guesses by one guesses plus equals 1 because we have already made one guess here's another scenario what if somebody guesses a number outside of this range like one kajillion well we should give a warning that that guess isn't valid if our guess is lower than the lowest number or our guess is greater than the highest number we will print the following that number is out of range and I will reprompt the user please select a number between between the lowest number and the highest number let's perform a test run I will guess one kajillion that number is out of range please select a number between 1 and 100 We'll add an lse if statement else if our guess is less than our answer we will print the following to low try again else if our guess is greater than our answer we will print to high try again if our guess isn't less than our answer and our guess isn't greater than our answer that means we must have the correct answer within an L statement we will print I'll use an F string string correct the answer was insert our answer our answer variable then print the number of guesses it took number of guesses add a placeholder place in our guesses within the placeholder now to escape the while loop we will take our Boolean variable of is running which is normally true and set that to be false to escape and that should be all we need let's run this one last time python number guessing game select a number between 1 and 100 let's select a number right in the middle 50 too low try again so the number is between 50 and 100 75 too high it's between 50 and 75 then 62 too high 56 53 55 correct the answer was 55 number of guesses it took me six all right everybody that is a python number guessing game you yourself can create as a mini project hey everybody in today's topic I thought we would create a game of rock paper scissors now that we know how the random module Works let's begin by by importing the random module we will create some options we will use a tupple we're not going to be changing the options so a tuple would be better than a list we have three options rock paper or scissors I'll create a variable named player to store the Player's Choice for now I'm going to set this to be none as well as a computer our computer is going to pick a random Choice from these options rock paper or scissors in order to do so we can use the choice method of the random module random. choice pick a random Choice from options let's have the player enter in some input enter a choice Rock paper scissors then we will display the Player's Choice and the computer's Choice I'll use an FST string player colon space the variable player let's copy that paste it then change player to computer let's see what we have so far enter a choice rock paper scissors so I pick Rock the computer picks scissors let's try it again just for good measure I pick paper this time the computer picks scissors I pick scissors the computer picks paper okay we know that the computer is successfully picking a random Choice from our options now what if the player picks something that's not within this tupple such as the gun well we would want to stop that right we need the user to pick a valid option only rock paper or scissors I think what we'll do is that when we accept the user input let's place it within a while loop so indent this line while this condition is going to be kind of weird while our player variable is not in our tle options let's try this again to see what happens I pick the gun enter a choice all right well if I can't pick a gun how about a sponge well I can't pick that either rock that works our condition is while the player variable is not found within our options if the player doesn't pick one of these options this while loop will continue forever once we pick something that's within our options we then escape the while loop let's check some win conditions now if the player is equal to computer that means it's a tie I will print it's a tie I'll add a few else if statements else if the player is equal to rock I'll use the and logical operator and the computer is equal to scissors that means you win let's print you win let's add another condition else if the player picks paper and the computer picks Rock then you also win you win else if the player picks scissors and the computer and the computer picks paper then we will print you win else if the Player's Choice is not the same as the computer's and we don't meet any win conditions that must mean we lose print you lose let's see if this works enter a choice rock paper scissors I pick the gun nope I can't pick that I pick Rock I pick Rock the computer picks scissors you win let me see if I can lose I'll pick paper you win again scissors I need to stop winning I need to see if the lose condition works okay it's a tie at least but I need to lose all right there we go I pick Rock the computer picks paper you lose what if the user would like to play again let's place all of this code with within a wild Loop let's do so right about here now I'm not going to write while true like I normally do this time I'm going to create a variable let's say running is our game running I will set that to be true while running equals true or we could shorten this to just while running that's simpler I will place all of this code within the wild Loop to mass indent some code just highlight all of the code then press tab hey everybody this is bro from the future I forgot to explain something the reason I'm not setting the condition of my while loop to be true is that if you have a lot of code within a while loop it can be really difficult to find where the break statement is if I set my condition to be a Boolean variable such as running it's a lot easier to find any instance where I use this variable if I were to highlight it we can see that running is found down here here if I need to change any instance of this variable and rename it to something you can refactor let's rename running as maybe playing then I will refactor so my variable running is now playing and that change was made down here too so it's a coding preference every time we start a new game I will reset the player as well as the computer let's move these two lines into the while loop at the beginning so when we start a new game we will reset the player the computer will pick a new random choice so let's see what we have so far Rock I pick Rock the computer picks Rock it's a tie then we have to play again so paper you lose scissors it's a tie now what if we would like to escape the while loop after our wi conditions I'm going to create a temporary variable let's name this play again then we will ask for some user input play again question mark y sln meaning yes or no if the user types in something that's capital I'm going to use the lower method to make it lowercase so if our play again variable is equal to Y we would like to escape what I would like to do is I would like to see if the player types in something that's not y I will precede this condition with the not logical operator if the user does not want to play again then let's take our Boolean variable running normally it's true and set that to be false running equals false that means we will escape the wild Loop once we escape the while loop I will print thanks for playing now I'm going to change this momentarily I just want to test it Rock play again yes paper play again yes scissors you lose play again nope thanks for playing this is entirely optional I try and create as few variables as possible I would personally rather avoid creating a variable here another way in which I could write this is that I can get rid of this variable let's move if notot in front of the input and follow our input here then use the comparison operator and add a colon if the user's input after making it lowercase does not equal a y for yes set running to be false so that should work the same Rock play again yes enter a choice paper play again no thanks for playing this line would work the same but it's a little more complex for beginners to read or you can use the other method that I showed you all right everybody well that's a game of rock paper scissors hello everybody today we will be creating a dice roller program in Python we will be utilizing some aski art I'll post all of the ask ke art that we'll need in the description of this video you can copy and paste it to save time if you'd like all right let's get started everybody we will Begin by importing the random module because we will be rolling some random numbers between 1 through six if we're going to create some esy art we'll be utilizing Unicode characters to enter in a Unicode character it really varies depending on your operating system I think the easiest way would just be to use Python to enter a Unicode character type award slash then a given code for each character here are all of the codes that we'll need after writing these seven Unicode characters let's run this program these symbols that are output let's copy them I'll add them to a comment then we can delete this line these are the Unicode characters we'll need to build some asy art some dice each die will be made out of five lines let's begin with the first we'll need a left corner nine dashes then the right corner for the second line copy this vertical bar add nine spaces then a vertical bar we can copy this whole line paste it two times let's use the left bottom corner add nine of these dashes then the bottom right corner and here's a basic box shape depending on what the number die is we can add one of these bullet points for a one we can add that right to the middle so that's good for now we'll delete this later let's create a dictionary I will name this dictionary dice art our dictionary is made out of key value pairs so the keys will be the numbers 1 through six beginning with one the value will be a tupple it's a dictionary made out of key value pairs where the value is a tupple within the tupple let's add these lines each separated with the comma I'm going to format these so they form a box shape let's take our bullet point place it right in the middle then add a comma to the end of this key value pair that is the first key value pair let's copy all of this paste it again change one to two let's move this bullet point we need two bullet points about right here and here let's repeat this process for Keys 3 through six be sure to get rid of the comma at the end and here is our dictionary of dice art each key is a number each value is a tupple made of strings let's create a list of dice our dice will be numbers randomly generated between 1 and six a total to calculate the total I'll set that to be zero then we will ask a user for a number of dice this will will be some input how many dice then typ cast the input as an integer we don't want somebody to write you know 2.5 dice you can't roll half a die to generate a random number you can use the Rand int method of the random module we need a random number between 1 and six then we need to append this number to our list of dice dice data pend then we can move this line to within the append method we need to do this a number of times depending on how many dice the user enters in we can place this line within a four Loop for every die in our range number of dice this will be a number let's print our list of dice to see what numbers we have in here how many dice I would like five dice 5 3 3 4 6 okay we know that that works let's calculate a total we'll need to iterate and sum all of the elements within our list we can do that with the for Loop for every die in our list dice take our total variable plus equals the current value within our dice then we will print a total I'll use an F string total colon space our total variable let's see what we have so far how many dice I would like five dice our total is 19 now between these two for Loops we will display our ASI art the easiest way would be to create some nested for Loops the outer for Loop will be in charge of the number of dice for every die in our range number of dice the inner for Loop will be in charge of printing every tupple for every line in then to get a value in our dictionary we would type the name of the dictionary dice art then use the get method what are we getting we're getting a value at a given key let's take our list of numbers dice at index of D our counter depending on what the user types in for the number of dice D will begin at one then increment within the inner four Loop we will print the line so let's take a look how many dice I would like three Dice and here's our aski art six + 2 + 4 that equals 12 if you would prefer we can display all of these dice on a single horizontal line instead of one vertical line it's a little more tricky though if you would prefer that approach let's turn this chunk of code into comments we will write this nested Loop a little different so each tupple is made up of five elements right so if we're printing a horizontal line let's say we roll the numbers 1 through 3 we would first need to display this line of the first dice then the first line of the second dice then the first line of the third dice during the next iteration of the outer loop we would display the second line of the first dice the second line of the second dice the second line of the third dice so it's a little more complex let's create an outer loop that will iterate five times for every line in range five then the nested Loop will be for every die in dice how many dice do we have within our list we will print we're going to get one of the values found at one of the numbers that we roll take our dictionary of dice art do get then a number 1 through six that will be the value found within our list of dice get the current die remember that this is a number 1 through six we would then need one of the elements found within our Tuple so get the first line then the second line third fourth fifth so let's add the index operator place our counter of line within the index operator let's see what we have so far we need to add one more thing how many dice three this is an Abomination there's one more change we need to make at the end of our print statement let's set the ending character to be an empty string and that should fix that how many dice three okay we're getting better results then when we escape the inner loop we will print a new line how many dice three and there we are 3 + 6 + 1 is 10 all right everybody so that is a dice roller program it is kind of complex but I thought this might be a good exercise if you would like a copy of this code I will post all of this in the comment section down below and well yeah that's a dice roller program in Python hey everybody today I need to explain function funs think of a function as a block of reusable code to invoke a function you place a set of parentheses after the function name to invoke it here's a scenario I need to sing Happy Birthday three times I know it's a weird example but it makes a lot of sense just trust me on this if I need to sing Happy Birthday three times I would write something like this I'm going to create my own version of the Happy Birthday song this is one verse if I need to repeat this code three times without using functions I could either repeat this code or maybe place it within a loop so here's my Happy Birthday song three times but there's a better way of handling this that doesn't involve repeating our code or using Loops what if I could write this code once then reuse it whenever I need to that's where functions come in to define a function you would type DF then a unique function name let's name this function the happy birthday function add a set of parentheses a colon any code that belongs to the function you'll want to indent underneath then to invoke this function I would type the name of the function happy birthday add a set of parentheses and that's it when you invoke this function you will execute this code once if I need to execute this code three times I would just call it two more times happy birthday happy birthday happy birthday to invoke a function you type the function name then add a set of parentheses I like to think of the parentheses as a pair of telephones talking to each other you call a function to invoke it hey happy birthday function execute your code with functions you are able to send data directly to a function using what are known as arguments you can send values or variables directly to a function place any data within the set of parentheses I'll send my function a first name any data you send a function are known as arguments but you need a matching set of parameters that are in order what exactly is the data we're sending in well it's a name I will add one parameter to my happy birthday function I will name this data name a parameter is kind of like a temporary variable that's used within a function I'm going to replace this instance of you with a name I will use an F string repl place you with a placeholder I will add my parameter name so happy birthday to bro we could pass in some other names what about Steve and Joe here we are happy birthday to bro happy birthday to Steve happy birthday to Joe when you invoke a function you can send more than one argument let's send an age this time I'll send 20 30 and 40 but when I run this we have an error we're passing in two arguments but our function is set up only to take one I would need a matching number of arguments to invoke this function we will need two parameters we have a name and we have an age then let's use this age you are let's make this line an F string a age years old let's try that again happy birthday to bro you are 20 years old happy birthday to Steve you are 30 years old happy birthday to Joe you are 40 years old when you invoke a function you can pass in some data those are known as arguments but you'll need a matching set of parameters the order does matter let's see what happens when I switch these two parameters age then name happy birthday 220 you are bro years old happy birthday 230 you are Steve years old happy birthday 240 you are Joe years old so the position of the parameters does matter same thing goes with the arguments you also could name these parameters something unique maybe X and Y happy birthday to X you are y years old that's also valid let's try another example I'm going to create a function to display an invoice there will be three parameters a username an amount and a due date let's print hello I should make this an FST string username we'll use another FST string your bill of amount let's preedee this placeholder with the unit of currency I will also add a format specifier point 2f is do on our due date whatever that parameter is to invoke this function we will type the function's name add a set of parentheses a username an amount and a due date let's make up some username an amount I guess $42.50 I'm just making up a number here then a due date the 1st of January I guess here's my invoice hello bro code your bill of $42.50 is due on January 1st let's change these arguments Joe Schmo is the username he owes $100 and 1 Penny due on the 1st of February or or January 2nd depending on how you read dates in your region hello Joe Mo your bill of $100 And1 is due on 1/2 that's another example now we need to explain the return statement return is a statement that is used to end a function and send a result back to the caller here's an example we have a variable z z will equal will invoke a function to add two numbers together such as the numbers one and two when we invoke a function we can send some data back after adding one and two we will send the result which would be three then this value can be assigned to a variable then we can print whatever Z is so let's create some functions let's create a function to add two numbers together the parameters will be X and Y let's say Z equal x + y then we will return our value Z so I'm not going to print Z directly right now let's subtract X and Y subtract z = xus y return Z multiply x * y then divide x / y return Z let's invoke our add function pass in two numbers 1 and two then I'm going to print the result after adding these two numbers together the result is three what about subtract subtract 1 and two the result is - 1 multiply the result is two then divide 1 / 2 is 0.5 after we resolve this function a value is returned just imagine that after we finish this function this function becomes whatever is returned three this function becomes - 1 this function becomes 2 this function becomes 0.5 let's write something a little more complex we will create a function to create a full name create name we'll need two parameters for a first name and a last name I'll name these first and last what do we want to do within this function let's capitalize the user's first name first equals first. capitalize method then do the same thing with the last name last equals last. capitalize then I'm going to return the user's first name plus their last name then I'll add a space in between their first and last name this is also valid outside of the function let's create a full name variable then invoke the create name function so this function is going to capitalize the first and last name for us I'll type in my first name all lowercase same thing with my last name then let's let's print our full name and here is my full name variable we sent our function some arguments we have some parameters set up we took those values made them uppercase then concatenated these strings together then return them as a single string let's try this with a different name SpongeBob SquarePants SpongeBob now has a full name the first and last names are now cap ized using the return statement you can return some data back to the place in which you call a function well everybody that's a function it's a section of reusable code to call a function you type the function's name add a set of parentheses you can send a function some data which are known as arguments but you'll need a matching set of parameters you also do have the option of returning some data back to the place in which you invoke a function we'll be using functions a lot in the future but we will get more practice with them and those are functions in Python hey everybody today I'm going to explain default arguments default arguments are a default value for certain parameters the default is used when that argument is omitted when you invoke a function in the last topic we discussed positional arguments today we will be examining default arguments then in future topics we'll examine keyword and arbitrary arguments let's begin in let's define a function to calculate net price there will be three parameters an original list price a discount if there is one and sales tax we will return a net price and here's the formula list price times 1 minus our discount percentage times 1 plus our sales tax maybe I'm buying a PlayStation 5 for $500 I will pass in 500 for the list price well I can't actually execute this function without also passing in an argument for Discount and tax perhaps the discount is zero and the sales tax is 5% 0.05 well this would work and I should probably put this within a print statement so you can see it there we are my total is $525 the list price of 500 no discount and 5% sales tax now suppose that maybe 90% of the time when we're executing this function most of the time discount is zero and our sales tax is almost always the same what we could do to make this function a little more flexible is to set these two parameters to have a default value in place of sending in three arguments we can pass in one then s our discount and our tax to have a default value so I will set discount to be zero and tax to be 0.05 meaning 5% so this function would work our total is 525 and that's assuming that our discount is zero and our tax is 5% the nice thing about using default arguments is that let's say that somebody has a discount well this function would also accept up to two additional arguments so let's print our net price 500 and our customer has a coupon for 10% off I'll add a second argument of 0.1 if we're passing in an argument for our discount we'll use whatever is passed in rather than the default our total now is $472 or maybe this time they are not paying sales tax I will set the sales tax to be zero now the customer total is $450 so that's kind of the nice thing about default arguments it makes your functions more flexible and it can reduce the number of arguments especially if the arguments that you're passing in tend to be consistent most of the time people don't have a discount and almost everybody is paying 5% sales tax why pass an arguments if we don't have to Let's cover an exercise we'll create a count up timer we will import the time module we will Define this function define count there will be two arguments start and end for X in range start comma and within the range function the second argument is exclusive so I'm going to add one to the end of our time then I will print X to make this thread that's running the program sleep you can access the time modules Sleep Method pass in one for one second then outside of the for Loop let's print the word done to invoke this function I need to pass in two arguments a start time and an end time I'll set the start time to be zero the end time to be 10 10 seconds so we start at zero then we will increment by one every second I'll speed up the video I think you get the idea but we'll stop at 10 let's assume that most of the time a user would like to begin at zero well we don't necessarily need to pass that in as an argument let's set our start parameter to have a default value of zero we only need to pass in one argument but we do have a problem non-default arguments should follow default arguments so if you use any default arguments you'll want to be sure that they're after any positional arguments so let's reverse these and that should work so now when I run this program it's assuming we'd like to start at zero but we'll need to pass in an ending amount of seconds when do we want to stop that works the same but now we do have the option of starting at a different number this time let's end at 30 but we will begin at 15 we're beginning at 15 then we will count to 30 I'll speed up the video there we are all right everybody so in conclusion default arguments they are default values for certain parameters the default value is used when an argument is omitted they can make your functions more flexible and reduce the number of arguments you have to pass in especially if those arguments are consistent most of the time so those are default arguments and in the next topic we will discuss keyword arguments and well yeah those are default arguments in Python hey friends it's me again today I'm going to explain keyword arguments a keyword argument is an argument preceded by an identifier it has a few benefits it helps with readability and the Order of the arguments doesn't matter if they're keywords keyword arguments are one of four basic styles of arguments we discuss positional default then next we'll discuss arbitrary but today we'll be focusing on keyword suppose I have a function to display a message like a greeting I will name this function the hello function we will need a greeting a title Mr Mrs doctor a first name then a last name all I'm going to do within this function is print an F string I will print my greeting the user's title first name last name then to invoke the hello function I will need to pass in four arguments a greeting a title a first name and a last name so for my greeting let's say hello the title will be Mr the first name will be SpongeBob last name SquarePants so you know this does work we're currently using positional arguments the position of these arguments does matter so what if I were to switch these around we have hello SpongeBob SquarePants followed by Mister hello SpongeBob SquarePants Mis an optional feature when sending arguments to a function is that we could turn these into into keyword arguments prefix any arguments with the name of the parameter followed by equals title equals Mister first equals SpongeBob last equals SquarePants then with these keyword arguments the order really doesn't matter maybe we move the first name to the end and the still would print out is the same thing we have title first name last name if you're mixing and matching positional arguments and key word arguments you want to be sure that the positional arguments are first so if I was to move the string or greeting to the end well this technically wouldn't work we have a syntax error positional arguments follow keyword arguments so make sure any positional arguments are first before using any keyword arguments two helpful benefits of using keyword arguments is that it helps with readability and the Order of the arguments doesn't matter we know what this argument is as well as is these two title last name first name let's say we have a first name and a last name John James these two names kind of sound like first names is our first name John or is it James we could use keyword arguments to clarify which is which you thought John was the first name but it's actually the last name and the first name is James then our title is still the same hello Mr James John Let's cover another example I'm going to print the numbers 1 through 10 using a for Loop for X in range 1 comma 11 because the second argument is exclusive then I will print X after each print statement we print a new line do you remember in previous topics how we would follow our print statement with comma and than a new character such as a space while end is a keyword argument found within the built-in print statement in place of ending each print statement with a new line we are using this keyword argument of end and sending it to be a space another one is separate that's found within the print statement maybe we have some numbers they're all separate strings the numbers 1 through 5 I can use the separate keyword argument then separate each of these strings with a given character or characters I will separate each of these strings with a dash a lot of built-in functions such as the print function they have some keyword arguments you can use let's go over an exercise now we're going to create a function to generate a phone number but we'll need to pass in a country code area code the first three digits in the last four digits let's define this function as Define get phone to get a phone number we have a country code area code first meaning first few digits then last meaning last few digits we will return an F string we will place our country code first Dash then our area code Dash the first few digits Dash the last few digits my phone number phone num equals I will invoke the get phone number function we just created but we'll need a country code an area code first few digits then last few digits and remember the order doesn't necessarily matter usually I try and be consistent with the order of the parameters make up a phone number I'm in the United States my country code is one area code 1 2 3 the next few digits will be 456 the last few will be 7890 then let's print this phone number print phone num and here is my phone number although you can change it up based on how you do phone numbers in your country this is typically how you would see a phone number in the United States all right everybody so those are keyword arguments they are just arguments preceded by an identifier that matches the name of a function's parameters it does help with readability and the Order of the arguments doesn't matter when invoking a function it could be helpful to identify some of these arguments and well everybody those are keyword arguments in Python Hello friends it's me again today I need to explain arbitrary arguments arbitrary meaning a varying amount of arguments we don't know how many arguments the user is going to pass in when they invoke a function to accept a varying amount of arguments developers tend to use these parameters of args and quars args means arguments quars means keyword arguments you would want to prefix each of these parameters with the unpacking operator which is an asterisk when you invoke a function that has args or quars as parameters you will pack all of those arguments into a tupple if it's args or a dictionary if the parameters quars let's go over an example I will create a function to add two numbers together Define add function there will be two parameters a comma B all I'm going to do is return a + b i will invoke this function pass in two arguments because we have two parameter set up one comma 2 then I'm going to print the result big surprise there my function return three all right well what if I would like to pass in three parameters this time well I can no longer use this function the add function takes two positional arguments but three were given I could modify this function so that it could accept a varying amount of arguments any amount I'm going to replace the parameters with asterisk than the word args meaning arguments so when we use the unpacking operator what's going to happen now is that with the arguments that we pass into this function we will pack them all into a tupple and if you don't believe me let's test it I'm going to print the type of args then I'm going to remove this print statement for now my parameter args is a tupple that I could work with we can use the built-in methods of this tupple or we could iterate over it I'm going to iterate over this Tuple for every ARG in args for every argument in arguments what we'll do is create a variable named total to keep track of the total total plus equals the current Arc that we're iterating over then at the end I will return the total let's print the result print add these three numbers together there we are my total is six then we can pass in any amount of arguments for this time maybe five or even one with my parameter args you can change this name to something else like nums meaning numbers for every num in nums total plus equals num this would work too the name of the parameter isn't as important as as the unpacking Operator just by typical naming conventions people tend to stick with args but the parameter name can vary let's try a different example let's create a function to display somebody's name display name we will accept a varying amount of arguments use the unpacking operator then follow the unpacking operator with the unique parameter name for every ARG in args let's print each argument then replace the ending character of my print statement with a space now sometimes people can have a varying number of names in their full name there can be a first name middle name last name maen name a title Etc so I'm going to pass in just a first name and a last name SpongeBob SquarePants if if I need to add a middle name I can do that SpongeBob Herold SquarePants or a title Dr SpongeBob Herold SquarePants the third yeah as I was saying with the unpacking operator followed by a unique parameter name you can pack all of these arguments into a tuple which you can use within this function now let's discuss quars you use two unpacking operators then typically people follow this with the word quars meaning keyword arguments it allows you to pass multiple keyword arguments which we discussed in the last topic I think this would be great for an address Define print address function use double asterisks then we can add a parameter name but people usually stick with with quars meaning keyword arguments just as a placeholder I'm going to type pass pass doesn't do anything I want this program to be able to run we'll get back to this function momentarily I'm going to invoke this function print address then pass in multiple keyword arguments with an address you would typically have a street a city state depending on what country you live in you may have more or less of these keyword arguments I live in the United States we have a state then a zip code okay my street will be I'm just making something up here one two three fake Street City will be Detroit State Michigan ZIP code 5 43 2 1 just to make this look better I'm going to place each of these keyword arguments on a new line for me that's just more readable but you do you when I pass in these keyword arguments we will pack them into a dictionary just to prove it let's print the type of quars look at that class dictionary within this function you can treat quars as if it's a dictionary there's a lot of built-in methods or we could iterate over the keys the values or both to to iterate over the values let's say for every value in our dictionary quars Dov values method print every value here's all the values for the keys let's change this for Loop to be for every key in quars do Keys method print every key here are the keys for both you could say for every key comma value in quars do items method print every key actually let me turn this into an F string print every key colon value the items method will return key value pairs we can pass in a varying amount of keyword arguments I'm going to add an apartment number apartment equals 100 our keyword argument of apartment was packed into a dictionary along with all these other keyword arguments so that's kind of nice we can pass in a varying amount of keyword arguments let's cover an exercise we're going to use both args and quarks together we will print a shipping label Define shipping label function the parameters will be both ARS comma quars then just for now I'm going to write past just so that this program will work for now we'll fill in the shipping label function momentarily when we invoke the shipping label function we will first pass in any positional arguments followed by keyword arguments and it won't work the other way around I'll prove that in a little bit so let's say we have doctor SpongeBob SquarePants the thir then I'll add my keyword arguments I'm going to put this on a new line Street equals 123 Fake Street Apartment equals 100 City equals Detroit State equals Michigan zip equal 54321 when we invoke this function we have a mix of arbitrary positional arguments and arbitrary keyword arguments this shipping label function is designed to accept both you do need args first followed by quars this program will run but if we have have it the other way around quars followed by args it's not going to function properly you can see that we have a syntax error with your parameters make sure that your keyword arguments follow your positional arguments let's iterate over the positional arguments first for every ARG in ARS let's print each ARG then I will change the ending character of my print statement to be a space Here's the name of the user who we're shipping something to with the shipping label function I will print a new line then we will iterate over all the keyword arguments for every value in my dictionary quars do values method I will print each value then I will change the ending character of my print statement to be a space all right it's not looking too bad so far if you were to remove some keyword arguments or some positional arguments this should work still which it does I'm going to change the format of this address slightly let's add our street on one line then the city state and zip code on the next line let's get rid of this four Loop to print the street I'm going to print use an FST string add a placeholder quars doget method I'm going to get the street key with this get method you'll probably need to place them within single quotes because if you use double quotes python gets confused as to where this FST string ends we will use single quotes Let's test it all right we have a street on the next line we will print the city state and zip print fing placeholder quars doget within single quotes the city I'll add another placeholder quars doget State then quars doget zip let's see what we have all right not too bad what if the user has an apartment keyword apartment equals number 100 well we should probably add that too within this top print statement I will add another placeholder invoke the get method of the dictionary the key we are looking for is apartment Dr SpongeBob SquarePants 123 Fake Street apartment number 100 Detroit Michigan 5432 1 what if our print statement is set up to display a street and an apartment but the user doesn't have an apartment this would display none and we don't want that I'm thinking what we'll do is we'll place this print statement within an if statement what we'll check is if apartment in quars if there's an apartment key in quars our dictionary then print this line else we will print just the street the person doesn't have an apartment we won't print the apartment then but if they do have an apartment apartment equals number 100 then we will 1 2 3 fake Street apartment number 100 here's a challenge round what if a user has a PO Box let's change apartment to P box the string will be P box number 1,1 I suppose I'll add an else if statement else if PO Box in our dictionary quars let's print the the street I'll copy this line paste it followed by a second print statement quars doget PO Box there we are Dr SpongeBob SquarePants 123 Fake Street p. box 1001 Detroit Michigan 54321 all right everybody those are arbitrary arguments when you invoke a function you can pass in a a varying amount of arguments set up your parameter to be args for a varying amount of non-keyword arguments or quars for a varying amount of keyword arguments you can set up both in your parameters which we did for this exercise and well everybody those are arbitrary arguments in Python hey everybody so today I got to talk about iterables in Python and iterable it's a category any object or collection that can return its elements one at a time is considered an iterable if an object or a collection is considered an iterable then it can be iterated over in a loop for example let's create a list of numbers numbers equals a list I'll add the numbers 1 through 5 to keep it simple lists are considered iterable we can use them within a for Loop in the context of a for loop we're going to be given each element one at a time each element that we're working with we can give a temporary nickname let's say number for every number in my iterable of numbers let's just print each number this will give us 1 through 5 the name of the current element in our iterable should be descriptive of what we're iterating over for example I don't want to rename the current number that we're working with as something like blah blah blah you know this would work but other people looking over your code might not understand what a blah blah blah is and I don't blame them each element that we're given from our iterable the name should be descriptive of what we're given or you might see item for every item in numbers print each item that's also a good choice now you could even iterate backwards by enclosing our iterable within the Reversed function so take our iterable of numbers and reverse it then we get the numbers 5 4 3 2 1 if you would rather not print each element on a new line we can replace the new line character at the end of print statements with something else print is a function we can pass in a keyword argument of end rather than end each line with a new line character let's end with the space this will space out each of the elements or we could replace it with something else or what about a dash after each element append a dash character we could even add multiple characters such as a space a dash and a space if we so choose it's up to you tuples are also iterable let's convert our list to a tupple by enclosing our numbers within a set of parentheses and I no longer want this reversed for every number in my itable of numbers print each number then again we get the numbers 1 through 5 let's cover sets I will create a set of fruit which I will name fruits for a set enclose any values within a set of curly braces let's add a string of Apple a string of orange a string of banana and a string of coconut so with our for Loop let's say for every fruit in my iterable of fruits I will print each fruit that would give me apple banana orange coconut now sets they're actually not reversible I will attempt to enclose our iterable of fruits within the Reversed function here's what happens we have a type error set object is not reversible sets you can't rever verse let's cover strings I will create a string of name type in your full name I'll use my YouTube channel name for every character in my iterable of name I would like to print each character maybe I would rather not have each character end with a new line I will set the keyword argument of end to be a space last we have dictionaries which are the most complicated let's name this dictionary my dictionary dictionaries you enclose with a set of krly braces kind of like a set but each element is a key value pair I will add a key of A with an Associated value of one a key of B which has a value of two a key of C which has a value of three if you iterate over a dictionary the dictionary is going to return all the keys but not the values we'll test that for every key in my iterable of my dictionary let's print each key this would give me the keys of a b and c but none of the values 1 2 or three if you need the values we're going to follow this iterable of my dictionary use the built-in values method this will return all the values of your dictionary as an iterable but let's rename a key as value because now we're working with the values then we're given all the values 1 2 and three if you need both the keys and the values you're going to use the items method we'll be given both a key and a value make sure that the value and the key is separated with the comma let's print each key followed by the value we get the key of A with its value of 1 b 2 c 3 we can reformat the output however we want let's use an F string I will add two placeholders let's print each key equals then the value a equals = 1 b = 2 c = 3 okay everybody so those are iterables an object or collection that can return its elements one at a time is considered an iterable meaning that object or collection can be iterated over using a loop and well everybody those are iterables in Python hello again so today I got to talk about membership operators in Python they are the operators in and not in they're used to test whether a value or a variable is found within a sequence which include but are not limited to Strings lists topples sets or dictionaries here's an example I'm going to create a word a secret word let's say apple I'm going to turn this into a game I will have a user guess a letter I will accept some user input guess a letter in the secret word what I would like to do is check to see if my letter is found in my word I can write the following statement if our letter in our word in is going to return a Boolean value of true if that letter is found or false if it's not so if our letter is found I'm going to print the following statement I'll use an F string there is a add a placeholder insert our letter else let's print I'll use an F string our letter was not found Let's test this guess a letter in the secret word I will guess a capital A so all these letters are uppercase do take note of that is there an a there is an a let's guess a letter that's not within this word such as z z was not found the in membership operator will test to see if a value or a variable is found within a sequence if it is it returns true if not it returns false or for the inverse you could say not in if letter is not in word we would have to flip these statements around if this value or variable is not found in this sequence it returns true otherwise false so it does the opposite of in guess a letter in the secret word is there an e there is an e is there a q q was not found depending on the statement you're trying to write you can use either in or not in whichever makes more sense in that context let's go over another example we were searching for a value or a variable found within a string let's try a set list tles and sets are going to behave similarly I will create a set of students for a set you need a set of curly braces let's add a few student names such as SpongeBob Patrick and Sandy I will have a user type in a student to search for we will accept some user input enter the name of a student we're going to check if our student is in our sequence of students if in returns true let's print the following I'll use an F string insert our student is a student else we will print I'll use an F string insert that student was not found enter the name of a student let's search for SpongeBob SpongeBob is a student enter the name of a student let's attempt Squidward Squidward was not found and much like the first example we can do the opposite see if a value or a variable is not in a sequence we would have to switch these statements around enter the name of a student is Sandy a student Sandy is a student enter the name of a student is Laria student Laria was not found now now we'll cover dictionaries I will create a dictionary of grades student grades like a grade book let's say that the student of Sandy she will be a key has a value of a Squidward the key of Squidward has a value of B SpongeBob he is also a key SpongeBob has a grade of C then Patrick Patrick has a grade of D here is my dictionary of grades then we'll search for a student student equals input enter the name of a student we'll check if Let Me Close the this if our student is found within grades then I will print the following we're looking for keys is there a matching key if we find that student I'll make this an F string let's display the associated value of that key student students grade is I'll add a placeholder once we find a student we have to get that value at the given key to do that we'll take our dictionary of grades at index of student this will retrieve the value at a given key if we don't find a student we'll output the following again I'll use an FST string student was not found so now if I search for a student such as SpongeBob we're given a grade we're given the value at that key that we're searching for Let's test Sandy Sand's great as a Squidward Squidward's great as B and Patrick Patrick's great is D but Larry is not a student if I search for him well Larry was not found let's go over one last example we're going to create a variable of email it's going to be a string type in whatever your email is Bro Code gmail.com I would like to see if this email is valid does it contain at and a period I will write if our value of at that character is in our email and a period is in email we have two conditions check if at is an email and check if a period is an email if so it's a valid email then we'll print valid email else we will print invalid email is my email valid that email is valid I'll get rid of the app invalid email I'll get rid of the period following Gmail that email is also invalid in this example we're checking two conditions if this value is found within this sequence and this value is found within this sequence all right everybody so those are membership operators in and not in they will return a Boolean based on whether a value or a variable is found within a sequence which include but are not limited to Strings lists tles sets or dictionaries and well everybody those are membership operators in Python hey what's going on everybody so in today's video I got to explain list comprehensions in Python a list comprehension is a concise way to create lists in Python they're Compact and easier to read than traditional Loops basically you have to follow the this formula for every value in something that's iterable meaning you can Loop through it check some condition then do this expression so let me give you an example with using a traditional Loop then you'll be able to see why a list comprehension is useful we're going to create a list and double the numbers 1 through 10 doubles equals an empty list using a traditional for Loop we will say for every value let's say X in range 1 through 11 remember that in the range function the second number is exclusive this will give you the numbers 1 through 10 for the first iteration X is going to be 1 then 2 3 all the way up until 10 so we'll iterate 10 times during each iteration I'm going to take my list of doubles use the built-in append method we will append X during each iteration that's going to be the value time 2 so if I were to print my list of doubles here's the result we have the numbers 1 through 10 all doubled 2 4 6 8 10 12 14 16 18 20 so this is a lot to write we can use a list comprehension to make this code more Compact and easier to read here's how we need a name for this list let's say doubles equals an empty list within our list list will follow this formula we have an expression for Value in iterable and optionally we can check a condition we'll do this in exercises later on in this topic we'll begin with for every value let's say X in our iterable our iterable is going to be a range 1 through 10 again for the first iteration X will be 1 then the second iteration X will be 2 all the way up until 10 during each iteration what would we like to do with X our value let's take X multiply it by two and return it then if I was to print my list of doubles we have the numbers 2 4 6 8 10 12 14 16 18 20 for every value in this iterable do this multiply it by two this is a list comprehension it's a concise way to create list in Python we'll go over a few exercises so this time we will triple each number we'll create a list of triples equals let's say this time for every Y in range 1 through 10 so we have to write 11 take Y and multiply it by 3 then we will print our list of triples 3 6 9 12 15 18 so on and so forth let's Square each number we'll create a list of squares for every Z in range 1- 10 to square a number we take that number multiply it by itself so the numbers 1 through 10^ squar is 1 4 9 16 15 36 49 64 81 100 so 10 * 10 is 100 now we're going to work with strings we'll create a list of fruits equals think of some fruit these are all going to be strings Apple orange banana coconut I'm going to take each string in this list and make it uppercase we could assign this to a new list such as uppercase fruits or we can simply just reassign it just to keep it simple I'll reassign it so again we're following this formula I like to begin with the four value in iterable portion for every fruit in our iterable of fruits what do we want to do well let's take each fruit take each fruit use the built-in upper method to make it uppercase then I'm going to print my list of fruits each string in this list is now all uppercase you could even cut down on one of the steps with our iterable of fruits I will place this list and this does work too although I do find this a little more difficult to read but you can take either option how about instead of making each string uppercase we'll take the first letter of each string then put it within a new list so let's take each fruit at index of zero that will give us the first letter we'll place it within a new list of fruit chars meaning characters here's the result a o b c for every fruit in our list of fruits return the first character of each string a o b c now we'll work with conditions we'll create a list of numbers both negative and positive numbers equals let's say one -2 3 -4 5 -6 we'll create a list comprehension to create a new list where all of the numbers are positive our new list will be positive nums equals we'll write a list comprehension for every let's say num in Num numbers we'll write a condition return this number if our num is greater than or equal to zero we do need an expression if we're not modifying each value we can just return the value of num during this exercise we're more focused on the if condition rather than the expression if our value of num meets this condition simply return it and place it within this new list let's print our list of positive numbers and we have 135 let's do this with negative numbers I'll just copy what we have and change a few things around this list will be negative numbers negative nums for every num in numbers check this condition check to see if num is less than zero if so return that number let's print our list of negative numbers -2 -4 -6 let's check to see if there's any even numbers even nums equals for every num in numbers check to see if our num is divisible by two and we can do that with the modulus operator followed by two the modulus operator will give you the remainder of any Division if our number is even number modulus 2 will equal Zer if it's even this is going to equal zero if it's odd it's going to be one we're not modifying our value we're just going to return our number our list of even numbers should be -2 -4 -6 let me add one more value let's add positive 8 -24 -6 positive 8 maybe we'll add one more -7 okay let's find any odd numbers let's copy this line of code replace even numbers with odd numbers if num modulus 2 is equal to one that means that number doesn't divide by two evenly then we'll print our odd numbers 1 3 57 all these numbers are odd here's the last exercise we'll create a list of grades we'll create a new list of any grades that are considered passing meaning they scored 60 or above so let's say one student has a grade of 85 another with of 42 79 90 56 61 let's say say 30 I will create a new list of passing grades equals again follow this formula for every grade in grades check our condition if our grade is greater than or equal to 60 we will return the current grade then let's print our list of passing grades that will give us 85 79 90 and 61 all of these grades are greater than or equal to 60 all right everybody so that is a list comprehension it's a concise way to create lists in Python they're Compact and easier to read than traditional Loops remember for every value in your iterable optionally you can check a condition you can write an expression to modify that value if you choose and return something all right everybody so those are list comprehensions in Python hey everybody so today I'm going to explain match case statements in Python if you're familiar with other programming languages this is also known as a switch match case statements are alternatives to using many LF statements we execute some code if a value matches a case the benefits of using a match case statement is that they're cleaner and the syntax is more readable in this sample program I have a function there is one parameter a day day will be a number ideally a number 1 through 7 depending on this number we'll return a string corresponding to the day of the week if day equals 1 then it is Sunday two it is Monday all the way up to 7 where it will be Saturday I do have a else Clause if we pass in something that's not valid like pizza pizza is not a day but it really should be not a valid day a cleaner and more readable alternative is to use a match case statement instead of many elif statements here's how I'm going to take my if and many elif statements and enclose them within a match case match case the case is going to be the value we're examining the case will be day colon we're going to examine our value of day against matching cases we're going to replace if day equals with the following just simply case so let's do that with each of these statements if you have an else Clause you're instead going to have a case of underscore an underscore and match case statement is a wild card we will perform this case if there are no matching cases this case would function as the else statement here's what we're working with now if I pass in one and return the day of the week we would get Sunday two would be Monday 3 Tuesday 7 is Saturday and then let's try that day of pizza that is not a valid day a match case statement is an alternative to using many l statements I find this much easier to read than the many l statements both would technically function let's go over a second example we will create a function of is weekend we have to pass in a day this time our day is going to be a string such as Monday the value for each case instead of a number is going to be a string if our day matches a case of Sunday let's return how about a Boolean of true we're checking to see if it's the weekend if our day is equal to a case of Monday then we will return false let's do this with the other days I'm going to fast forward the video we will call the function of is weekend then pass in a day of the week such as Monday so is Sunday the weekend that is true Monday that is false Saturday that is true and we do have a wild card case if there are no matches is pizza a day of the weekend that is false there is a way we can modify this match case too we tend to be repeating ourselves a lot the days Monday through Friday all return false we're going to use the or logical operator which is represented with a vertical bar if the case of Saturday or Sunday return true if the case is Monday or Tuesday you can get rid of that or Wednesday or Thursday or Friday then we will return false we can keep our Wild Card case so is Saturday part of the weekend that is true is Monday false Sunday true Friday false and pizza we have our Wild Card case that gives us false all right everybody so those are match case statements they're similar to switches in other programming languages they're an alternative to using many LF statements we execute some code if a value matches a case the benefits is that the code is cleaner and the syntax is more readable and well everybody those are match case statements in Python on Hello friends it's me again today I'm going to explain modules a module is just a python file containing code you want to include in your program you use the import keyword to include a module you can use built-in modules or create your own sometimes it's useful to break up a large program into reusable separate files for a list of all the modules found within the standard python Library you can use the help function pass in the word modules and then we would need to print this here are many of the different modules available to you a few you may recognize would be math string time one of my favorite names of a module is the pickle module unfortunately it doesn't have anything to do with Pickles it's used for serialization to list all of the different variables and functions found within the module you can place that name of the module within the help function for example with the math module here are a few different variables we would have access to and a few different functions to include a module we would type import the name of the module for example math I now have access to everything found within the math module including those variables and functions to access those variables and functions I would normally type the name of the module dot the name of the variable or function such as Pi then let's print this PI from the math module is 3.14 and some change another way to import is to type import the name of the module as you can give your module a nickname an alias whatever you think of such as m m short for math we would no longer refer to this module as math we would refer to it as our Alias M using an alias would reduce some of the typing you have to use if you have a very long module name another way to import import is to use from the name of the module import something specific Pi for instance you would no longer need the module name from math import Pi Pi would be included within our namespace however I tend to not use from import as much just because it's possible there could be name conflicts here's an example let's say from math import e e is an exponential constant e is 2.71 what if I was to create a program where we have four variables named A B C D A = 1 b = 2 c = 3 D = 4 then I'm going to print E from the math module to the power of a that would give me 2.71 then let's do this with b c and d e to the power of b e to the power of C e to the power of D here are the results let's say we have a different variable e e will be five then I will print e to the power of E we have imported E from the math module when we have declared all of these variables technically what we've done is we have created another version of e we will end up using the second version rather than the version that we have imported from the math module all my my results are now different and it's possible you may not realize it I like to be more explicit I'm going to import math if I'm using a variable or function from a module I much prefer to prefix that variable name or function with the name of the module in which it's from math. e to the power of a to the power of B to the power of C to the power of d math. e to the power of our variable e and these results are to be expected Now to create a module what we're going to do is right click on our project folder go to new python file think of a module name maybe example then click python file we now have two tabs Main and example declare whatever you would like within this module let's create our own variable Pi Pi equals 3.14159 then a few functions let's create a function to square an argument that's passed then Define Square we will accept an argument which we will name X then return X to the^ of two let's define a cube function we will accept one argument then return X to the^ of 3 maybe a circumference function Define circumference we will accept a radius then return 2 * Pi * radius then an area function to calculate the area of a circle we will accept a radius as an argument then return Pi * radius to the power of 2 all right here is our example module within our main Python program let's import the name of our module which we named example we now have access to everything within this module I'm going to declare a variable result and set it to the name of my module do PI then I will print the result which is 3.14159 let's utilize the square function result equals example do Square let's Square three which is n let's use the cube function that would be 27 circumference that would give me 18.8 then area that would be 28.2 that's how to create your own module it can be useful at times to separate your program into individual files all right everybody in conclusion a module is just a file containing code you want to include in your program you use import to include a module you can use built-in modules or create your own if you do need a list of the modules available to you again you can use the help function then pass in the word modules and well everybody that's how to get started with modules in Python hey friends it's me again today I'm going to explain both variable scope and scope resolution variable scope is where a variable is both visible and accessible with scope resolution when we're using a variable there is a certain order known as the lb rule in which we locate that variable local enclosed Global built-in we'll get to this momentarily let's begin with variable scope I have two functions Function One function two within function 1 a equal 1 then we print a within function 2 b equal 2 then we print B if I were to invoke these functions let's invoke function one then function two we would print one then two variables declared within a function have a local scope variable a is local to function one variable B is local to function 2 within function one if I were to print B and function two if I were to print a we would run into a name error name B is not defined and the same thing would apply with a functions can't see inside of other functions imagine that we're function one this is our house we can see everything that's going on inside of our house but function two is our neighbor's house we can't see what's going on inside of our neighbor's house we have no idea what B is with function 2 function 2 has no idea what a is that's where variable scope comes in it's where a variable is visible and accessible functions can't see inside of other functions but they can see inside of their own function that's why we sometimes pass arguments to functions so that our functions are aware of them using this concept we could create different versions of the same variable let's rename a to be X and B to be X as well then I will print X we have two different versions of x a local version of X found within function one and a local version of X found within function 2 whenever we utilize a variable we will first look to see if there's any local instance of that variable if there isn't we would move to the enclosed scope with an enclosed scope one example is when you have a function declared within another function I'm going to place function two within function one this is allowed in Python this is a more advanced concept we'll cover this more in the future so I'm going to eliminate this print statement let's get rid of function two at the end of function one we will invoke function two like I said it's pretty complex we won't be using this until much later within function two if I was to print X we would use the local version or x equals 2 if I was to eliminate this variable declaration we would use the enclosed version instead where x equals 1 there's an order of operations use any local variables first then enclosed variables we're printing X within function 2 since X wasn't found within the local scope we would use x within the enclosed scope but like I said that's a more advanced topic you should at least be aware of it let's move on to the global scope Global meaning outside of any function I will eliminate these variable declarations within function one we're printing X and within function two we're also printing X I will declare a global version of X where x equal 3 x is outside of any functions when I run this program we're printing three twice once for function one and once for function 2 there's no longer a local version of X for both of these functions if there were we would end end up using these local versions instead Function One prints one function two prints two if there's no local version as well as no enclosed version we would move on to the global version where x equal 3 last in our order is built in I think what we'll do though is from math import e e is an exponential constant I'm going to print what e is e is 2.71 e is built in I will create a function to print e Define function one all I'm doing is printing e then we should invoke it invoke function one if I was to set e to be a different value like three what we're doing technically is creating two different versions of e variables can share the same name as long as they're within a different scope we have a buil-in version of e and a global version of e if I was to print e now it would print my Global version because using the lb order we would first look for any local version of e then enclosed version then Global which we do have one of then lastly built-in all right everybody so in conclusion variable scope is just where a variable is both visible and accessible python has a scope resolution order lb if we're using a variable we will first look in the local scope for that variable if we don't find that variable in the local scope we will move over to an enclosed scope then Global then built-in we will have more practice with this in the future and well everybody that is both variable scope and scope resolution in Python hey everybody so today I got to talk about this if statement if Dunder name is equal to a string of Dunder main when you see this if statement it's usually followed by a call to a function named main or something similar a majority of the driving code behind behind a program is usually found within some sort of main method when you see this if statement basically speaking it means that this script can be imported or it can run Standalone functions and classes in this module can be reused in other programs without the main block of code running sometimes you would like the functionality of a program without executing the main body of code a good example could be a library in a python Library we would like to import some of the useful functions such as the math module but if we were to run that Library directly instead of importing it we could instead display a help page but if we're importing that Library we don't necessarily want to display that help page only if we're running it directly in many Python scripts you'll see the statement of if Thunder name is equal to main if we're not running this program directly don't do it in this example we're going to delete our main python script be sure to recreate it at the end of this topic in case I forget to mention that we will create two scripts go to file new python file script one file new python file script 2 we have to add new run configurations for script one and script 2 so if you go to the top go to run edit configurations we will add a new run configuration select python select a new script path to script one okay apply again we have to do this with script 2 add python select a script path of script 2 okay apply then okay using the dropdown menu we can select which run configuration we would like would we like to run our main python file but we have deleted it do we want to run script one or script two for the time being we'll select script one within script one if I was to print then call the dur function dur meaning directory python has all of these built-in attributes if you're not familiar with object-oriented programming for now think of an attribute as a variable Dunder name is a special type of variable Dunder meaning double underscore if I was to print what's contained within Dunder name we would receive a string of Dunder main that's why in a script you may see the statement if Dunder name is equal to a string of Dunder main if so then you usually call a function named main to start your program I'm going to undo that so let's import script 2 from script 2 import everything asterisk means everything within script script 2 I will print Dunder name and we'll see what's within it again I'm running script one within script two Dunder name is equal to a string of script two the name of the Python script however within script one Dunder name is equal to a string of Dunder main this means I am running script one directly let's delete this import then go to script 2 import script one from script One Import asterisk meaning all we're now going to change our run configuration from script one to script 2 we are running script 2 directly now Dunder name within script one is the name of the Python script script one Dunder name within script 2 is now Dunder main so by adding this if statement of Dunder name is equal to Dunder main we can check to see which file is being run directly if Dunder name equals Dunder main we will call a function of main to contain the main body of our program but we need to Define this function define main our main function will contain the majority of our python code anything that's not already within a function so let's print this is script one then we'll Define another function of favorite food we will have one parameter of food let's print the following message I'll use an F string your favorite food is add a placeholder add our parameter of food within our main function let's call the favorite food function pass in your favorite food as a string I'll type in pizza then let's print the word goodbye we're going to run script one run it here's the result from the top down all of our code is within functions we skip over it because we're not calling it quite yet the first thing we do in this program is check this if statement if Dunder name is equal to Dunder are we running this program directly which we are we're running script one if so call the main method to start the program we print this is script one your favorite food is pizza goodbye now I'm going to go to script two delete our print statement change the Run configuration to script 2 and run it nothing should happen that's good now if we were missing this if statement of if under name is equal to Main then we delete our main function here's what would happen we're importing script one but we're running script two this is script one your favorite food is pizza goodbye I don't want this code to execute we're not running it directly that's why we have that if statement if under name is equal to main I only want to run this code if we're running it directly so what we'll do within script 2 now is Define a function of favorite drink there's one parameter of drink I will print use an F string your favorite drink is I'll add a placeholder we'll add our parameter of drink let's print the message this is script 2 we will call from script one the favorite food function pass in your favorite food this time I'll say Sushi let's call our favorite drink function favorite drink I'll pass in coffee then we will print goodbye okay we are running script 2 this is script 2 your favorite food is Sushi your favorite drink is coffee goodbye we're running script to but we're importing the functionality of the favorite food function from script one sometimes from another python script you want to borrow something but you don't want to run the main body of code directly I just want to borrow this function from script one and that's it script 2 can be run as a standalone program but I can't import it without this body of code running I can add that if statement if Thunder name is equal to a string of Thunder main if we're running this program directly execute this code so let's call a function of main Define main then Place main body of code within it if I run script 2 we have the same message so by adding this if statement of if name is equal to main this script can be run as a standalone program or it can be imported a more practical example of this could be a python Library you can import the library for functionality but if you run the library directly you could instead display a help page it is good practice to include if Dunder name equals Dunder main it makes your code more modular helps with readability leaves no Global variables and avoid unintended execution and well everybody that is the purpose of if Dunder name equals Dunder Main in Python hey what's going on everybody so in this video we're going to create a very Simple banking program using python this is meant to be more of an exercise to get us used to working with functions when creating a project I like to divide that project into smaller sections then handle them one at a time so we'll do that by declaring all the functions we'll need first with the banking program we'll need to show a user their balance we'll Define a function to show balance for the time being I'll write pass just as a placeholder we'll need to make a deposit Define deposit make withdrawal Define withdraw near the end of this project we will be creating a main function and placing the main body of our code within it we'll handle that near the end just to contain everything we have our three functions with our banking program we'll need to show a balance make a deposit or make a withdrawal what are some variables we'll need well we'll need a balance which I will set to be zero initially I will also create a Boolean of is running this will be true if at any time we said is running to be false we'll exit the program so with the majority of our code we'll place it within a while loop while is running you can check to see if this is equal to true but since this is a Boolean that's not necessary we will just say while is running if is running becomes false false we'll exit the while loop within our while loop we'll print some sort of Welcome message let's print banking program then list some options let's print one show balance two deposit three will be withdraw four will be exit afterwards we will set a choice variable to equal some user input input enter your choice 1- 4 We're encouraging a user to to type in a number 1 through 4 to select an option do they want to show their balance make a deposit make a withdrawal or exit we'll add a few if and else if statements let's check to see if the user's choice is equal to one that is a string of one our user input is a string data type unless we were to typ cast it to something else if our choice is equal to one we will call the function to show balance else if our choice is equal to two we will make a deposit by calling the deposit function else if choice is equal to three we will call the withdraw function else if choice is equal to 4 that means we would like to exit so we need to exit this while loop we can do that by setting our variable of is running is this program running equal to be false to exit if somebody types in some input that's not valid we can handle that with an else statement else let's print that is not a valid Choice okay let's see what we're working with currently to test everything we haven't written anything within these functions yet show balance deposit or withdraw so we can type 1 2 3 and for to exit processed finished with exit Code Zero so we can't exit the program we just have to select option four with this else statement this will execute if we type in something besides the numbers 1 through 4 because there's no other options left so to test that enter your choice 1 through four uh I'm just going to type the word poo that is not a valid choice so we know that the L statement is working once we exit the while loop let's print a message that says thank you have a nice day if I was to type for to exit we should exit the program thank you have a nice day let's make that h capital now we'll work on our functions beginning with show balance currently these two variables are Global we don't need to pass them as a parameter to these functions quite yet we will be enclosing all of this code within a main function we'll handle that later though so with show balance all we're going to do is print I'll use an F string your balance is add a dollar sign or other unit of currency of your choosing add a placeholder our balance variable and let's see what we have I will type one to show balance your balance is 0 I'll display our balance with two decimal places after I will add a format specifier after balance colon. 2f will add two decimal places we covered format specifiers in a previous topic so if I were to run this again type one we show $0 and 0 cents we're displaying two floating Point decimal places now we need to make a deposit that'll be the next function we will Define a local variable of amount equals accept some user input enter an amount to be deposited again when we accept user input it's a string we'll typ cast it to a number a floating Point number because we have to include dollars and cents we'll add some checks though after accepting some user input if our amount is greater than zero we don't want anybody to make a negative deposit let's print that's not a valid amount else we are going to return our amount so this function is going to return something so within our else if statement we will take our balance plus equals the deposit we're being returned with this will add our deposit to our balance balance plus equals deposit let's try it let's show our balance our balance is $0 we'll make a deposit of $100 exactly again we'll show our balance after making the deposit your balance is $100 let's attempt to deposit negative money we'll select two to make a deposit we'll deposit 42069 that's not a valid amount so we have a problem we have a type error unsupported operand for float and nonone type so within this statement within if within our deposit function we're not returning anything let's just return zero we have to return something and within this if statement we didn't return anything previously will either return zero or return a valid amount let's try this again let's make a deposit I will attempt to deposit -420 69 that's not a valid amount our program's not crashing that's good now we'll attempt to make a valid deposit $50 And1 then show my balance your balance is $50 And1 Cent okay that is the deposit function we'll work on the withdraw function next we will create a local variable of amount accept some user input enter amount to be withdrawn our user input is going to be a string we will typ cast it to be a floating Point number we need to check to see if our amount we're trying to withdraw is greater than our balance users shouldn't be able to withdraw more money than what they have in their bank account if the amount is greater than our balance that we have we will print insufficient funds else if the amount somebody's trying to withdraw is less than zero we will print a different message amount must be greater than zero else we will return our valid amount so with our if and else if statements we do need to return something if we take one of these routes we will return zero we're not making any changes within our else if statement where we select choice three we're going to take our balance minus equals the withdraw amount Let's test this banking program let's show our balance our balance is zero we'll make a deposit of $100 show my balance again your balance is $100 let's press three to withdraw money enter amount to be withdrawn one1 kajillion dollar insufficient funds yeah no kidding Let's attempt to withdraw money again we shouldn't be able to select a negative amount negative $420 69 amount must be greater than zero let's enter in a valid number this time I would like to withdraw $49.99 that has appeared to work we'll show our balance again your balance is now $501 then we can exit by pressing for to exit thank you and have a nice day the last few changes I'm going to make is that I'm going to enclose all of this code our main portion of code within a main function just to encapsulate all of our variables and help with readability we will Define a function of main take all of our code within the main body of our program and place it within the function I'm just going to select all of it and indent it at the end of our program we need to call a main function to run it if you're familiar with the statement of if Dunder name is equal to a string of Dunder main that means this program can be imported or run stand alone it is good practice to include this if statement we discussed this in the previous video if we're running this program directly execute the main function however our variables of balance and is running they're now enclosed within this local scope these other functions have no idea what these variables are of balance so we need to pass in our balance to those functions of withdraw and show balance when we show our balance we have to pass in our variable of balance same thing with withdraw then set up those parameters within show balance we will have one parameter of balance the same thing with withdraw the last thing I'm going to do is add a little bit of text decoration around my program just to make it look nice so I will print a bunch of asterisks it's not necessary but I think it'll look nice let's add some text decoration before and after the title of banking program also before our choice basically whenever we print anything we'll add some text decoration let's do that with show balance our deposit and within withdrawal okay let's run this one last time banking program let's show our balance your balance is $0 we'll make it deposit $100 And1 show our balance again your balance is $100 And1 we will withdraw money enter an amount to be withdrawn $11,000 insufficient funds let's try that again let's withdraw $50 show our balance again $501 then press for to exit thank you and have a nice day all right everybody that is a simple banking program you can write using python hey everybody in today's video we're going to create a beginners slot machine program using python this Project's meant for beginners so let's get started when creating a project I like to break up that project into different sections then tackle them one at a time so with the slot machine what are some of the different functions we'll need well we'll need to spin a row we'll Define a function to spin row as a placeholder I'll write pass we'll return to this function later we need to display or print the row print row if somebody gets matching symbols on the slot machine we need to give them a payout we'll create a function to get payout in this function we'll calculate what that payout is going to be but again we'll get to that later we'll write the majority of our code within a main function at the end of this program I will add the if statement of if Dunder name is equal to a string of Dunder main then we will call the main function which drives our code this program can be imported or stand alone it is good practice to add this if statement a majority of the code we're going to write is going to be within our main function So within our main function let's declare the variables we'll need throughout this program we will need a starting balance which I will just name balance we will start with 100 00 as in $100 we'll need to display some sort of Welcome message let's print something we will print welcome to Let's name our game python slots just for some flavor I'm going to add some text decoration just a bunch of as risks I think it'll look cool but you don't have to Let's display our symbols we're going to use symbols I'll add some emojis we'll use emojis in this program in place of images if you're on Windows you can hold down the window key plus semicolon let's add a cherry you typically see a lot of fruit in slot machines a watermelon a lemon there's also a lot of bells for some reason but we'll add those and a star let me just align everything let's do a test run welcome to python slots let me make one adjustment okay I'm happy with that so after our welcome message we'll continue playing this game while our balance is greater than zero while we still have money we can continue playing we will print I'll use an FST string current balance colon space I'll add a placeholder pick a unit of currency I'll pick American dollars then we will display the user's balance we will prompt the user to enter in their bet which we will assign to a variable of BET so input place your bet amount let's do a test run welcome to python slots current balance $100 place your bet amount we won't deduce the BET amount from the balance quite yet I just want to be sure that we can enter in something $1 good $10 $100 what if somebody body types in a word like pizza we need to prevent that input and correct it we'll check if take our bet use the is digit method is our bet a digit if somebody types in a word like pizza we need to tell them that's not valid so this will return true if our bet is a digit but we're going to use the not logical operator if our our bet is not a digit then do this we will print please enter a valid number followed by the continue keyword the continue keyword will skip the current iteration of this Loop and start from the beginning Let's test it place your bet amount Pizza please enter a valid number we have our current balance again place your bet amount I'll type in one okay we did not get that message of please enter a valid number this bet of $1 is valid so if our bet is a digit we'll convert it to be an integer using typ casting because when you accept user input it's a string it has the string data type let's reassign our bet type cast our bet as an integer then we will check to see if our bet is greater than our balance people can't bet money that they don't have if the bet is greater than the current balance if bet is greater than balance we will print this message instead insufficient funds then continue if somebody tries to bet negative money or no money we'll add this statement if bet is less than or equal to zero we will print bet must be greater than zero and continue if all these checks pass if our bet is not a digit if our bet is greater than our balance or if our bet is greater than zero we will take our original balance minus equals our bet to subtract it let's do a test run place your bet amount pizza please enter a valid number I will bet1 kajillion dollar insufficient funds yeah no kidding 0 bet must be greater than zero what about $1 our bet should be subtracted from our balance let's try 10 we are now down to 89 let's bet $90 insufficient funds 89 and that has appeared to work once we subtract our bet from our balance we will call the function to spin row this function is going to return a list which we will assign to be row row will be a list using the spin row function we have to generate three random symbols then return them within a list we'll work on the spin row function next within our spin row function we will declare a list of symbols add your symbols but these need to be strings make sure they're all comma separated there we go this is where list comprehensions can come in if you don't know what a list comprehension is here's an alternative we will declare an empty list of results this is an empty list we need a for Loop to generate three random symbols we could say for symbol in range three this for Loop will iterate three times during each iteration let's take our empty list of results use the append method we will append a random. choice among our symbols so we need to import the random module we'll do so at the top import random we're telling the random module to pick a random Choice from this list of symbols then we will append them to our empty list of results after we escape the for Loop we will return our results it's a list now a much better option is to use a list comprehension here's how it's going to be a lot more concise we will return a list within the list we will write a list comprehension for every let's say symbol in range three there is no condition what do we want to return during each iteration access the random module use the choice method then pass in our symbols symbol isn't used in this example what you may see people do is use an underscore as a placeholder basically what we're saying is for every iteration in range three return a random symbol that's all we need for the spin row function going back we have our list of row afterwards I am going to print it to test it print row and we should have three random symbols after making a bet all right it looks like it's working we'll make a few changes though instead of printing our row I'm going to print the word spinning I will add a new line character just to give us some space like after this word of spinning then we will call the print row function we'll pass in one argument R row that's returned to us after we spin the row so going to our print row function we need to set up one parameter our row that we receive it's going to be a list one easy way to print the elements of a list is that we can print pick some sort of separator for each item in the list for example I'll just print a space with strings there are bu methods we will use the join method then pass in our list or other iterable basically what we're saying using the join method we're going to take our iterable in this case our list join each element by a space a space character here's the result we have three symbols you could join them by a different character I'll add a vertical bar and to your bet amount $1 now we have a vertical bar between each of these symbols we could include more than one character I'll add a space before and after this vertical bar just to space things out I think that looks a lot better and you don't have to but I'm going to add some text decoration before and after I'll add a bunch of asterisks let's see what we're working with not bad so every time we make a bet we get a new set of symbols now what if all three symbols match we need to calculate a payout and give it to the user because well they won so after we print our row we will call the get payout function but we will pass in our row it's a list and our bet how much did we bet we will be returned with a pay out which we will add to our balance let's go to the get payout function we're sending two arguments to our get payout function a row and a bet we have to check to see if each element in our row is all the same is it all the same character we can do that with an if statement if our row at index of zero that's going to be the first symbol is equal to row at index one that's the second symbol is equal to row at the second index and that's the third symbol if all three symbols match we have to return the BET multiplied within our if statement we will add another if statement I will check to see if our row at index0 is equal to our first symbol of cherry be sure to place it within quotes because it's a string now the reason I'm only checking if row at index zero is a Cherry Emoji all these symbols are going to be the same if we're within this if statement all of these symbols are going to match we only need to check one of them it could be zero one or two but I'll just add zero they're all going to be the same regardless if somebody has all cherries we will return their bet * 3 or some other amount you can make the payouts higher or lower else if row at index zero is equal to a watermelon then we will return their bet Time 4 so watermelons are worth more than cherries else if row at index zero is equal to a lemon we will return their bet Time 5 else if row at index zero is equal to a bell let's give them times 10 return bet time 10 else if row at index zero is is equal to a star that's worth the most we will return their bet time 20 make sure we're not within our if statement anymore if all three symbols don't match within our list we don't want to give the user anything they lost that spin we will return zero that's all we need for the get payout function scrolling back down after receiving a payout it's returned to us from this function we'll check to see if our payout is greater than zero that means they want to spin I will print I'll use an F string U1 I'll add a placeholder preced this with a unit of currency I'll use dollars will display the payout else if they did not receive a payout that means they lost that spin we will print s sorry you lost this round then take our balance this is our original balance plus equals our payout in most cases the payout is going to be zero but if the user wins something we will add that to the balance okay let's do a test run I will bet $1 sorry you lost this round and my current balance is 99 let's bet again I'll just keep on doing this until I win we're going to lose more times than what we win okay see I got all Bells it says you won $10 once somebody runs out of money we want to stop them from playing or if they would like to exit we'll create a variable of play again we will accept some user input do you want to spin again we'll add y for yes sln for no if our variable of play again does not equal a character of capital Y then we will break to break out of this Loop let's do a test run and to your bet amount I'll just bet a dollar do you want to spin again if I type in anything besides a capital Y we will exit I will type in no then we exit and to your bet amount I'll bet a dollar if somebody were to type in a lowercase y that doesn't register we'll make it uppercase by following our input with the upper method to make it uppercase place your bet a dollar hey I won I won $3 do you want to play again I'll type in a lowercase y yes I would like to play again but I did not hold shift in order to make this a capital Y that will still register and our current balance is $12 we're ahead currently place your bet amount I'll bet $10 we lost this round I will press n because I don't want to play again then we exit so at the end of our program I will print I'll use an F string game over your final balance is I'll add a placeholder pick a unit of currency I'll pick dollars display our balance then I'll just add some text decoration before and after to make it all look nice okay let's play this one last time enter your bet amount I'll bet a dollar sorry you lost this round do you want to spin again yes I do I will bet $5 you lost spin again yes I will bet 10 20 again I'll bet 20 I keep losing I'm running out of money guys hey I won $10 though do you want to spin again no game over your final balance is $1 that's why you shouldn't gamble you tend to lose more money than what you gain all right everybody so that is a slot machine program you can write using python hello everybody today I'm going to show you how we can write a substitution Cipher encryption program basically speaking what we're going to do is that we have a message to hide the message we can encrypt it by replacing every instance of one character with another chosen at random using the same key we can then decrypt to the message when I was at my University I took an intro to cyber security course I turned this program in as a final assignment and I did get an A on it I don't know maybe it'll help you at the very least it's a good exercise all right let's get started everybody we will Begin by importing the random module as well as the string module let's create a string of characters named chariz whatever characters you would like to use for your encryption program list them here as a string however this can be a lot to write I think a better solution would be to import some constants from the string module I'm going to include some punctuation I will import the punctuation constant of the string module how the heck do you spell punctuation okay that's right plus I will add some digits string. digits constant plus string Dot asky letters let's take a look at our character so far we have one long string of characters what if I would like to include a space a white space well there is a constant for that but that includes things like carriage return that's going to warp our results let me show you just for a demonstration string Dot Whit space plus all the other stuff we have a carriage return and some other characters I would like to avoid that so in place of importing the Whit space constant from the string module I'm going to add a space character that's good enough here are all the characters I will be using this program feel free to add more or less this is all one long string I'm going to turn the string into a list where each character is an individual element to do that I'm going to take our string of chars reassign it then typ cast my string of characters as a list then let's print it again print chars instead of one long string we have a list a list of all the characters we'll need I am then going to create a key which we will Shuffle eventually key then to create a copy of a list you can type the original list. copy method then I will print my key I'm going to place these lists within an F string chars then key let's see what we have we have two identical lists one for the original characters and the other for the key we're going to shuffle this key random. shuffle pass in our list of key look at that all of the characters are now shuffled in a random order what we'll be doing when somebody types in some text to be encrypted we will replace every instance of one character within that string let's say an O then replace it with another one every time we run this program this key will be reshuffled let's ask for some user input this part of our program we will do some encryption plain text is the original message plain text equals we will accept some user input enter a message to encrypt cyppher text is the name of the encrypted message that will be an empty string okay let's say a user types in a message enter a message to encrypt I like pizza it's a very important message every instance of a character within my plain text I will refer to the key and replace that letter with a different one for example any z's I have two Z's in this program will be replaced with let's see capital B every time we run this program though it's going to shuffle the key so it's not going to be consistent what we're going to be doing is iterating over every letter in our plain text for every letter in plain text strings are iterable find the index of every letter from our plain text within our list of characters let's assign a variable index index equals take our list of chars use the index method we are looking for that letter whatever letter we're currently on then return an index then refer to our key get whatever letter is at that same index so we will append that to our Cipher text it's currently an empty string Cypher text plus equals our key at the given index our Cipher text should be the encrypted message now let's print it out print I'll use an FST string original message let's print our plain text then our encrypted message print our cyppher text string let's take a look so far enter a message to encrypt I like pizza then here's the new encrypted message every instance of a character within my plain text was replaced with another so for example any z's were replaced with E I have two e within this encrypted message if I were to run this program again it would likely be different I like pizza and here's my new encrypted message my Z's were replaced with semicolons this time for every ladder in our plane text get the index of each letter then refer to the key add the new character to our encrypted message it's probably best for us not to display the characters and the key so let's hide those we will be reusing this key for decryption now to decrypt the message let's copy this section of code paste it we are now decrypting we will ask for some Cipher text then reset our plain text for every letter in our Cipher text refer to our key append a character to our plain text within our list chars at a given index we will display our encrypted message followed by the original message let's try it one last time enter a message to encrypt I like tacos here's my original message then the encrypted message if I were to decrypt the encrypted message it should give me my original message I will type in these characters exactly hit enter and here is my message decrypted I like talking goes all right everybody so that is a substitution Cipher encryption program for beginners when I was at University I did turn this program in for a final assignment for a cyber security class and I did get an A on it so maybe it'll help you and well yeah that's an encryption program for beginners in Python what's up everybody so in today's video we're going to create a game of hangman using python I thought that this would be a good mini project for us while learning to code it is important to create small projects as you go along here's one that we can make together when creating a project I like to declare the various variables and data structures I'll need first followed by the functions I'll need for this game we will need a set of words one of these words is going to be chosen at random so let's create a few words I'll add some fruit apple orange banana coconut and one more pineapple using the random module let's import that import random using the random module we will pick one of these words at random we won't be able to see what it is but we can guess what the word is one letter at a time once we reach six incorrect guesses we lose the game before each guess we will display some asky art which trial name as hangman art this will be a dictionary a dictionary where each key value pair contains a tuple so this is a dictionary of we'll have a key which will be a number and a tupple the key is going to represent the incorrect number of guesses so we'll start at zero we will display a tupple which will contain some aski art then let me just copy this for one incorrect guess we'll display some different s art I'll just put each on a new line for readability so we're going to go all the way up to six once we hit six incorrect guesses we lose the game each key corresponds to the number of incorrect guesses once we reach six we lose the game each Tuple that corresponds to the incorrect number of guesses we will display a certain image if you would like feel free to look in the description of this video if you would like to copy this to save you some time each topple will consist of three rows three strings for no incorrect guesses where incorrect guesses a zero we will display nothing we can't see our hangman person for one incorrect guess we will display their head for two incorrect guesses we will display their head and the main torso of their body which will represent with a vertical bar let me copy this one for three incorrect guesses we will display their left arm represented with the forward slash with four incorrect guesses we will display their right arm however if you use a backs slash that's an escape sequence within a string you have to use double backs slashes to literally print a backslash so with five incorrect guesses we will display their left leg of the person then once we reach six incorrect guesses we display the full person that's when we lose the game when we see the entire person that's some asky Arch that we can use so let's test it just to be sure that everything is working fine I will print my hangman art at the Key of zero to represent no incorrect guesses okay so when we display this person we're going to have to use some sort of loop for every let's say line in hangman art at index of zero for zero incorrect guesses I will print each line line with no incorrect guesses we don't display anything that's correct we can't see the person and that's okay so with one incorrect guess display the dictionary where the key is one that displays the person's head two two would be the main torso of their body three they're left arm four their right arm five their left leg and six their right leg once we see the entire person we lose the game so we can delete these two lines of code we no longer need them we know that our dictionary is working I'm going to zoom out a little bit following our dictionary we'll declare the various functions we'll need throughout this program we will Define a function to display man our hangman there will be one parameter wrong guesses and then for the time being I'll write pass we'll fill in this function later when we display our man we need to know the number of incorrect guesses to display the Right image we have a display man function and a display hint function we will have a string of hint then I'll write pass for now our hint is going to be a list a list of underscore characters for each letter that we guess right will flip one of those underscores to be a letter if that letter is correct I'll create a function of display answer within this function we will display the correct answer either when we lose the game or win the game and I will write pass we will create a function of main to contain the main body of code of our program again I'll write pass for now I'll add the following if statement if Dunder name is equal to a string of Dunder main if we are running this file directly I would like to call the main function to start the program all right let me zoom out this will be the main skeletal structure of our program import the random module we have our set of words we'll be importing more from a separate file near the end of this video we have a dictionary where the key is a number to represent the number of incorrect guesses and a tuple to display some asky art we have four functions display our man display the hint display the answer and the main function to contain the main body of code all right let's work within our main function within our main function we will create a variable of answer what is the correct answer that we have to guess I will access the random module call the method of choice then pass in our set of words one of these words will be chosen at random Let's test that I will print our answer just temporarily we should get a random word Apple Apple pineapple Apple I guess it really likes apple for some reason there we go we have orange we are choosing a word at random we no longer need this print statement looks like everything is working fine now we'll display our hint our hint is going to be a list of underscore characters I need the number of underscore characters to equal the number of characters in one of these words that is chosen at random so I could multiply my list by the length using the length function of my answer so let's print our hint to see what we're working with with my selected word we have how many underscores 1 2 3 4 5 6 7 okay we have a different word 1 2 3 4 5 that is probably Apple it has five characters all right so that's our hint it's a list of underscore characters when we guess a letter if it's correct we'll fill in one of the underscores with that correct character we need to keep track of the number of wrong guesses we'll create a variable of wrong guesses set that equal to be zero when we start the game we're going to keep track of all of the incorrect guesses that we've made we will create a set of guest letters for an empty set we'll call the set function normally in Python you can't create an empty set with just a set of parentheses we have to use the set function then I will create a Boolean variable of is running set that to be true while our game is running continue playing once we lose or win the game we will switch this to be false to exit the game we will keep this as true when we initially run this program after we declare the variables we'll need within the main function we'll create a loop a while loop while is running we don't need to say while is running is equal to true we don't necessarily need to create that comparison we can just say while is running while this is true continue doing some code so what would we like to do let's call the function of display man but we have to pass in the wrong number of guesses call our function of display man pass in our variable of wrong guesses when we begin the game we would like to display one of these images then we will display our hint then we'll call the function to display our hint pass in our hint that was the list of underscore characters to represent the answer we have to guess we will create a variable of guess and accept some user input will'll prompt the user to enter a letter just in case a user types in a character that's uppercase let's add the lower method to make it lowercase so let's fill in our display man function there's not a lot to write here when we call this function we need to display one of these images based on the wrong number of guesses one of these Keys within the display man function we'll create a for Loop for every line in my hangman art this dictionary at the Key of wrong guesses this will be a number 0 through six depending on what this number is I will print each line print each line of that Tuple let's see what we're working with we'll do a test run so we are displaying no person we can't see them for testing purposes I am going to change wrong guesses to be one we're displaying their head two displays their body three displays their left arm four is their right arm five their left leg leg and six is their full body that's when we lose now you don't necessarily need to do this but I'll add some text decoration before and after I'll add just a bunch of asterisks before and after I think that looks better but you do you let's be sure to set wrong gesses back to zero after we display our hangman we have to display the hint what's the clue we're trying to solve so we will call our display hint function and pass in our list of hint So within the display hint function let me zoom out I will print the following between each character within our hint each underscore we will display a space character strings have a built in join method we'll call that then pass in our hint for each character within our hint join it by an empty space so now when we do a test run we are displaying an underscore to represent each character each is separated with the space while we're here we'll fill in the display answer function we just have to copy this line of code from display hint replace hint with answer and that's all we need for the display answer function so let me test that real quick after playing our hint temporarily I will display our answer just to be sure that it's working yep there's our hint and there's our answer that we have to guess okay let's delete this line of code we don't want to display the answer I was just testing it so the user is going to be able to type in a letter to guess such as a for example once we guess a letter if that letter is found within the hint if it's one of these characters we need to switch that underscore to be one of those characters so we'll write the following if statement if our guess is in our answer in is a membership operator if this letter is found within our string of answer we're going to create a loop we will create a loop that will iterate once for each character within the answer but we don't know the length of the answer because python we'll choose it at random so let's say for every index we can shorten this to I for I in range the length of my answer let's say the word is Apple the length of the word Apple has five characters this would return five for I in range five then we will iterate five times we'll iterate this Loop once for the number of characters within my answer we'll check during each iteration if our answer at index of I during the first iteration that will be zero then the second iteration it will be one then two so on and so forth strings are iterable if our answer at index of I is equal to our guess if there's a match if we guess the correct letter then we're going to take our hint at that given index of I and set that equal to be our guess looks like this if statement is outside of the while loop I'm just going to invent it by one somewhere within it okay let's do a test run I'm going to guess the letter A yes we have one a let's do something that's probably not in here Q okay okay so there were no matches we don't end up doing anything so what is this word probably this should be the word orange so let's guess o r n e g all right we know that it works what if somebody types in some input that's not valid before checking if that guess is correct we'll do some input validation what if the user types in a whole word like pizza we want the user to only guess a single character not many characters We'll add the following line if the length of Our Guest that we type in does not equal one then I will print the following message let's say invalid input then we will use the keyword of continue to skip this Loop continue okay enter a letter I will type the word Pizza we get this message of invalid input we skip that Loop's current iteration I will guess a there are two A's I will type banana and again we get invalid input we have to guess one letter at a time what if somebody types in a number like one we would like to prevent that so within this if statement I would like to execute this code if our guess is not an alphabetical character I can add the following or not take our guess dot use the is Alpha method if our guess is an alphabetical character this returns true if it's not an alphabetical character it's false so we are checking if this is not an alphabetical character we execute this code let's try this again I will type in one invalid input 42069 invalid input let's say we guess the letter A what if we type in a letter we have already guessed I will guess a again if they already guessed a letter I don't want that to count we'll skip the current Loop iteration I'll add another if statement if our guess is in our set of guest letters then I will print the following I'll use an F string our guess is already guessed oh one thing I'm forgetting once we check that our guest is not within our guest characters we'll take our guest letters this is a set add the guess we're keeping track of the letters we have already guessed so I will type let's guess a we have one a if I were to guess a again we get that message of a is already guessed and then be sure to add continue to skip the current Loop iteration all right now going down to this if statement if guess is in our answer if we guess a character that's incorrect we will take our variable of wrong guesses incremented by one wrong guesses plus equals 1 let's do a test run I will guess a there is an a what about Q There is no Q we display our dictionary where the key is one we display that asky art R is there an R yes there is an R this is probably orange I would like to be sure we display the entire person I will guess some wrong characters we know that that works now we need a win condition if we guess all of the correct characters and display the entire word we'll work on that next if there are no underscore characters not in our hint this will be true if there are no underscore characters in our hint if underscores not in hint we'll call our function of display man pass in the wrong number of guesses call the function of display answer pass in our answer we will print the text of you win then set our Boolean variable of is running equal to be false let's win this time I already know that this word is probably pineapple let's guess something incorrect there we go we have two wrong guesses but we have correctly guessed the word pineapple you win and we exit the program what if we lose I'll add the following if statement else if our variable of wrong guesses is greater than or equal so the length of our hangman art is a total of seven there's seven total keys but once we hit six we lose the game with this LF statement if the length of our hangman art the length of our hangman art is going to be seven so we are going to subtract one for six for a total of six once our wrong guesses is greater than or equal to 6 that means we lose the game we will call the display man function pass in the wrong number of guesses display what the correct answer should have been display answer pass in our answer we will print you lose then take our Boolean variable of is running set that to be false I'll guess incorrect letters there the word was coconut we have six incorrect guesses we display the entire hangman the correct answer was coconut you lose if you would like to import a larger variety of words we could create a separate python file for that so within our project folder we will create a new python file I will name this python file words list this will be a python file let's take our set of words cut it I'll add a note that these are words for Hangman game Words will be a set I recommend looking online for a very large set of words that we can use then just copy and paste them within here while while browsing online I found an extensive list of animals that I can use so here are all the possible words for my game so from my main python file I have to import this module of words list from the module of words list import words and now I have a greater variety of words I can use let's run this one last time this word has four letters I'll guess the vowels there's an a no E I O there is an O is it Goat nope t r bore all right the word was bore you win all right everybody so that is a game of hangman that we can create using python hey everybody so so we have finally made it to Python objectoriented Programming this is a very important topic in Python an object is a bundle of related attributes and methods attributes are similar to variables to describe what the object has so look around you right now you are surrounded by different Real World objects next to me I have a phone a cup and a book each of these objects can have different attributes to represent it for example an attribute of the phone next to me could be version number I could set that to be 13 is on could be another attribute is the phone powered on or not that could be true or false or even a price I have a cup next to me what liquid is within the cup in this case coffee what's the temperature of the cup is the cup empty is empty or even a book What's the title of the book that could be a string how many pages does the book have Pages could be another attribute now objects also have the capability to do things they have methods which are functions that belong to an object people mix up functions and methods all the time they're technically different even when teaching I tend to make that mistake calling a method a function and a function of method usually people know what you're referring to though a method is a function that belongs within an object what are some actions these objects can perform with a phone you can make a call or receive a call call turn the phone on or turn the phone off those could all be functions with a cup you could fill the cup drink from the cup or empty the cup with a book you can open the book read the book and close the book an object is a bundle of related attributes and methods they can represent real world items to create many objects we'll need to utilize a Class A Class is a type of blueprint used to design design the structure and layout of an object we need to design what our objects have their attributes and what they can do their methods we will create a class of car we will create some car objects class car to construct a car object we need a special type of method called a Constructor it works similarly to a function we will Define a function of double underscore init meaning initialize double underscore again and then follow this with a set of parentheses this is our Constructor method we need this method in order to construct objects it's a Dunder method Dunder meaning double underscore that's a future topic I don't want you to be overloaded with information right now all you need to know is that we need this method in order to create objects this method behaves similar to a function we need to set up the parameters self is already provided to us self means this object we're creating right now this car so what are some attributes that a car should have a model that could be a string like a BMW a year that could be a number a color let's add a Boolean of four sale is the car for sale or not that's true or false to assign these attributes we're going to access self self do the name of the attribute self. model equals the model we receive these are parameters when we receive the name of a model we will assign it to this object let's do this with year self. year equals year self. color equals color self. for for sale equals for sale this is an example of a few attributes that a car might have a model year color and if it's for sale or not represented by a Boolean now to construct a car object we need a unique name for this car let's just say car one car 1 equals take the name of the class add a set of parentheses to invoke The Constructor we're going to do this almost exact L like a function we have parameter set up we need to send a matching number of arguments self is provided to us behind the scenes automatically we need a model year color and if it's for sale or not so pick a car if you're choosing I'll pick my favorite car the model will be a Mustang for the year I'll go with the recent year of 2024 a color I'll pick red is the car for sale I like this car so no I will set that to be false make sure false is capitalized let's see what happens if I attempt to print our car object of car one what we're given is the memory address of this car object where it's located but I would like one of the attributes located at this memory address instead of printing the object itself we're going to access one of the attributes found within this car we will follow the name of the car with a DOT this dot it's known as the attribute access operator I would like the model of car one that would give me Mustang let's access the year take the name of the car car one dot the year 2024 followed by the color car1 docolor red car one is it for sale we'll print that that is false now let's create a second car we're going to reuse this class to create a second car we will create Car 2 equals car we'll pass in some different arguments a Corvette the year will be 2025 the color will be blue is this car for sale let's say that is true instead of accessing car 1's attributes let's access car 2's attributes that would give us a Corvette the year is 2025 the color is blue for sale is set to true or even a third car car 3 equals a new car we will pass in a string of charger the year 2026 the color will be yellow is this car for sale let's say that is true as well then I will print car 3's attributes the model is charger the year is 2026 the color is yellow for sale is set to True with classes they can take up a lot of space for better organization you can place them within a new python file so let's cut our class and we will create a new python file within our project folder file new python file the name of this python file is going to be all lowercase car then we will paste the class that we cut originally class car which has a capital c so from our main python file we're going to import our car file our car module from the name of the module car import the name of the class car then when I run this program nothing should change we should still have access to all of our car objects you could either keep your classes within your main python file or import them if you would like to organize things let's talk about methods methods are actions that our objects can perform within our class we will Define a method of Drive self is going to be provided to us when we invoke the drive function let's print you drive the car what other things can cars do let's stop we will print you stop the car let's take car1 access the drive method you drive the car car 2 also has a drive method you drive the car same thing with car 3 you drive the car let's access the stop method car one. stop car 2. stop and car 3. stop these methods are identical for each car object instead of printing the word car let's insert the model of the car I will convert these print statements to F strings instead of the word car let's add a placeholder let's add self. model self is referring to the object we're currently working with use the attribute axis operator followed by the name of the attribute let's also do this with the stop method self do model let's take car one use the drive method you drive the Mustang car one. stop you drive the Mustang you stop the Mustang let's do this with Car 2 you drive the Corvette you stop the Corvette car three you drive the charger you stop the charger now now within our F strings let's also insert let's insert the color I'll add a placeholder self. color do this with stop as well self. color you drive the yellow charger you stop the yellow charger car one you drive the red Mustang you stop the red Mustang card to you drive the blue Corvette you stop the blue Corvette let's add one last method let's create a method to describe our car we'll print the details of the car let's print I'll use an F string add three placeholders let's print self.y year followed by self. color then self. model we'll take car 1 use the describe method that we created describe car 1 car 1 is a 2024 red Mustang describe Car 2 Car 2 is a 2025 blue Corvette car 3 is a 2026 yellow charger all right everybody so those are objects in Python an object is a bundle of related attributes attributes are variables that an object has and methods methods are functions that belong to an object they Define what this object can do and well everybody that is a summary of object-oriented programming using python hey everybody today I got to talk about class variables in Python class variables are shared among all instances meaning objects created from a class instance variables are defined in inside of the Constructor class variables are defined outside of the Constructor with class variables they allow you to share data among all objects created from the class with instance variables each object has their own version with a class variable all those objects share one variable here's an example we will create a class of student we also need a Constructor when we create a student object this construct structor is automatically going to be called but we need to pass in some arguments we are provided with self self refers to the object we're currently working with we will set up a name parameter and an age parameter we will assign self the object we're currently working with set the name attribute to equal the data for the name that we receive from this parameter and self. AG equals age let's let's construct two student objects we will have student one equals then call the Constructor for student so type the name of the class followed by a set of parentheses to invoke it this will automatically call The Constructor but we have to pass in data for the name and the age for the name let's pass in SpongeBob because basically everybody in the world knows who SpongeBob is I don't know how old SpongeBob is we'll say he's 30 we'll create another student object which we will refer to as student 2 we will call the Constructor of our student class pass and data for the name and age student two will be Patrick Patrick will be 35 okay let's make sure this works let's print student 1's name followed by student 1's age and we should get SpongeBob and his age is 30 let's print student 2's name and student 2's age Patrick Patrick is 35 now we'll create a class variable class variables are defined outside the Constructor and they are shared among all objects created from that class each object has their own name and age property these are instance variables but class variables are defined outside the Constructor each object will share this one variable so if we're working with students let's say there is a class variable of class year what is the graduating year of this class 2024 now let's print student 1's graduating year print student one. class year okay so SpongeBob has a class year of 2024 that's when he's graduating let's check student two Patrick is ages 35 his graduating class year is 2024 now with class variables you can access them through any one object such as student one or student 2 it's good practice to access a class variable by the name of the class rather than any object created from the class since we're accessing class year we'll access this class variable by the name of the class of student make sure the S is capital this helps with Clarity and readability if I was looking at this print statement I can tell that class year is a class variable because we're accessing it directly from the class and not any instance from this class without looking at this class I can't tell if class year is an instance variable or a class variable but if I access it via the class name it's more explicit so it's good practice to access a class variable by the class name itself and not any one instance of this class let's create another class variable we'll create a class variable to keep track of how many students we have created this class variable will be num students meaning number of students equals z So within our Constructor we can write any code that we want this code will always be executed when we instantiate an object I would like to take our number of students and increment it by one each time we construct a new student object so instead of using self self refers to the object we're currently working with if we're constructing student one just imagine we're replacing self with student one or student two if we were constructing student two if we're going to be modifying a class variable in place of self we'll use the name of the class student access our class of student get the class variable of number of students then I will increment it by one plus equals 1 we are constructing two student objects I will print access our class of student get the number of students and print it we're constructing two student objects if I print the number of students that we have it should be two then just to be sure that this is working let's construct a third student object student 3 equals student this student will have a name of Squidward Squidward's age will be 55 now we have three students and for good measure let's construct one more student 4 equals we will create a new student with a name of Sandy sy's age will be 27 the number of students is now four just as an exercise using an FST string let's print the student classes class year as well as the number of students I will print use an fing my graduating class of let's add a placeholder access the class of student then access the class Year my graduating class of 2024 has then we need the number of students We'll add a placeholder access the class of student access the number of students has blank students let's see if this works my graduating class of 2024 has four students now if I were to change 2024 to 2025 my graduating class of 2025 has four students let's print the name of each student these are instance variables student one. name then we need Student two three and four my graduating class of 2025 has four students SpongeBob Patrick Squidward Sandy all right everybody so those are class variables class variables are shared among all instances of a class they are defined outside of the Constructor the benefit is that they allow you to share data among all objects created from that class and while everybody those are class variables in Python what is going on everybody so today I got to talk about inheritance in Python inheritance allows a class to inherit the attributes and methods from another class much like how a child in real life can inherit traits from A parent by having a class inherit attributes and methods from another class this helps with code reusability and extensibility in this example we're going to create an animal class the dog cat and mouse class will inherit attributes and methods from the animal class we will create a class of animal then I will Define The Constructor when we construct an animal object let's pass in a name it's not required but it might be good for this example we will assign the attribute of name equal to the name we receive let's also add an attribute of is alive whenever we create an animal we will set there is alive attribute to be true and that is a capital T all animals can eat Define eat we will print using an F string add a placeholder self. name the name of this animal is eating all animals should be able to sleep Define sleep print I'll use an FST string insert self. name is sleeping and that is all we need for the animal class let's define class dog for a child class to inherit the attributes and methods from another class after the class name that's going to inherit we need to add an inheritance list with the set of parentheses then list the name of the class we're inheriting from the parent the the dog class is going to inherit all of the attributes and methods of its parent animal for the time being as a placeholder I'll add pass just to demonstrate this class cat is also going to inherit from animal and class Mouse will also inherit from animal okay I will collapse this for now we'll create a dog object dog equals dog then pass it a name for this dog because we have one parameter set up of name this dog will be named Scooby as in Scooby-Doo cat equals call the cat Constructor this cat will be named Garfield and mouse mouse equals Mouse our Mouse will have a name of Mickey even though there's nothing within this dog cat or Mouse class we should still have these attributes and these methods if you inherit the animal class you should have a name attribute and is alive attribute set to true you can eat and you can sleep let's print our dog's name dog. name Scooby print dog. is alive our dog is alive that is true let's have our dog object use the eat method Scooby is eating and sleep dog. sleep Scooby is sleeping let's replace dog with cat the name of the cat is Garfield Garfield is alive Garfield is eating Garfield is sleeping and mouse replace any instance of cat with mouse our mouse's name is Mickey Mickey is alive Mickey is eating Mickey is sleeping even though these children classes are empty we're still inheriting these attributes and methods from its parent of animal this is convenient because you don't need to copy and paste these attributes and methods for every single class for example if I were to copy these attributes and methods and paste them well we have a lot more codee to write and as a consequence if I need to make a change to one of these methods I would have to do that to every single instance of this method for example let's replace is sleeping with is asleep well now I need to find every single Sleep Method and change it manually it's not too bad if you only have a few classes but imagine if you have hundreds of classes that's going to take a lot of work it's a lot easier to write the code once and then reuse it and I only need to make that change in one place rather than make that change many times so let's change is sleeping to is asleep and see if that works again Mickey is asleep let's replace Mouse with dog Scooby is asleep not only that but with children classes they can have their own attributes and methods that are different from one another so dogs have all these attributes and methods and they can speak let's create a speak method and I will print a unique message for dogs woof cats will also have a speak method but it's going to be different cats will meow then for our Mouse class they will squeak let's have our dog speak woof let's have our cat speak meow and our Mouse squeak all right everybody so that's an introduction to inheritance inheritance allows a class to inherit attributes and methods from another class much like in real life a child can inherit traits from A parent these are also known as sub and super classes which is a topic for another day inheritance helps with code reusability and extensibility if all of these children classes inherit these attributes and methods from another class we only need to write that code once and not copy it for every single class that needs it we can write and change the code in one place for better reusability and extensibility and well everybody that is an introduction to inheritance in Python hey everybody so today we got to talk about both multiple and multi-level inheritance we'll begin with multiple inheritance that's when a child class inherits from more than one parent class for example a class of C can inherit the traits from both class A and B in Python you can have more than one parent multi-level inheritance we'll talk about near the end of this topic so in this example we're going to create two parent classes prey I'll write pass for now and Predator we'll create a class of rabbit a class of Hawk then class fish rabbit Hawk and fish are going to be children classes prey and Predator will be parents if one of these classes rabbit hawk or fish inherit from prey they get the ability to flee we will Define a method of flee all we'll do in this example is print the following text this animal is fleeing if you're a predator you get the method to hunt Define hunt we will print this animal is is hunting rabbits they will inherit from the prey class they're typically not Predators except that one rabbit and Monty Python and the Holy Grail that's the exception rabbit will inherit the prey class then it gets access to a flea method Hawks are predators they will inherit the Predator class now fish they will hunt smaller fish and flee from bigger fish you could consider fish both prey and predators so they will inherit both classes we will use multiple inheritance they will inherit everything from the prey class and the Predator class now let's see if this does in fact work now we'll create a rabbit object rabbit equals rabbit there are no parameter setup we don't need to send any arguments to the Constructor Hawk equals Hawk and fish equals fish so let's take our rabbit object and they should have a flea method rabbit. flea method this animal is fleeing but they do not have a hunt method because they're not Predators rabbit object has no attribute hunt Hawks can hunt they're Predators they inherited that method this animal is hunting but they can't flee they're not prey Hawk object has no attribute flea fish can do both they inherit from the prey class and the Predator class fish. flee this animal is fleeing fish. hunt this animal is hunting children classes can inherit from more than one parent which is what we did for fish they are both prey and predators whereas in rabbits are just prey Hawks are just Predators if you need to inherit from more than one parent you just add that additional class to The Inheritance list with multi-level inheritance a parent can inherit from another parent we will create a class of animal and for now I'll write pass prey and Predator are going to inherit from the animal class so we need to add animal to each inheritance list let's say if you're an animal you get a method to eat all animals will eat print this animal is eating and you can sleep Define sleep print this animal is sleeping so think of rabbit Hawk and fish as children classes prey and Predator are those class's parents and animal is the grandparent prey and Predator will inherit everything that the animal class has rabbit Hawk and fish will inherit everything the prey and Predator classes have so now our rabbit Hawk and fish classes should have the ability to eat and sleep and we'll test that rabbit. eat this animal is eating rabbit. sleep this animal is sleeping let's check out fish fish. eat this animal is eating fish. sleep this animal is sleeping okay we're going to expand upon our example a little bit let me zoom out each of our objects is going to have a name our rabbit will have a first name of bugs Hawk will be Tony as in Tony Hawk our fish will be Nemo within our classes we don't have any Constructor set up in which class should we assign the name attribute let's do so within our animal class so we will Define a Constructor to assign these attributes we will receive a name we'll assign self. name equals name now with these other classes if you're not assigning any attributes or if you don't need any other initialization logic you don't need a Constructor we'll implicitly use the Constructor we inherit from the parent let's convert each of these print statements to an F string replace animal with self. name now let's have our rabbit use the E method oh we should get rid of this there we go bugs is eating rabbit. sleep bugs is sleeping rabbit. flee bugs is fleeing let's check out our Hawk Hawks don't have a flea method because they're Predators not prey let's eat Tony is eating let's sleep Tony is sleeping let's hunt Tony is hunting let's check our fish next our fish can eat Nemo is eating our fish can sleep Nemo is sleeping they can flee Nemo is fleeing and Hunt Nemo is hunting okay everybody that is both multiple and multi-level inheritance with multiple inheritance a child can inherit from more than one parent class you just add each additional class to The Inheritance list with multi-level inheritance a child can inherit from a parent which inherits from another parent Class C can inherit from B where Class B inherits from a think of C as the child b as the parent and a as the grandparent c will have all the attributes and methods even available within the grandparent class of a and well everybody that is both multiple and multi-level inheritance in Python hey everybody so today I got to talk about the super function in Python super is a function it's used within a child class to call methods from a parent class the child class is the subass the parent class is the super class hence why this function is named the super function using the super function it allows you to extend the functionality of the inherited methods here's an example we'll create a few shape object objects we'll need to set up the classes though we'll have class Circle for the time being I'll just write pass we'll fill it in later class square and class triangle for each of these classes in order to instantiate objects we'll need a Constructor we will Define our Constructor our init method when creating circles what sorts of attributes should a circle have let's say a color what's the color of the circle is it filled or not fil will be another attribute and a radius then let's assign these self. color equals the color that we receive self. filled equals filled self. rius equals radius let's do this with the square and Triangle really I'll just copy our Constructor and paste it squares don't have a radius with a square the width and the height are the same let's replace radius with width we'll also keep the color and filled attributes self. width equals width now with triangles again let's copy our Constructor we'll need a width and a height self. height equals height so with programming we try not to repeat ourselves if we don't have to what do all of these classes have in common they all share the attributes of color and filled the ways in which they are different is that Circle has a radius attribute square has a width triangle has a width and a height if we have to make any changes to one of these attributes we would have to do so manually for example let's replace filled with is filed now I need to look throughout my code for any instance of filled and replace it with is filled it's a lot of work and I might make a mistake such as here and here it's better to write your code once and try and reuse it so that's where inheritance and the super function can come in handy we're going to take the attributes of color and is filled and place it within a parent class these children classes will inherit those attributes so class what do they all have in common they're all shapes class shape and for now I'll write pass circle is going to inherit from its parent of shape that also applies with square and triangle we'll set up a Constructor for shape Define init we will pass in the color and is filled then we will assign these attributes self. color equals color self. is filled equals is filled we don't need to manually assign these attributes within each of these Constructors for the children instead what we have to do is within the Constructor for each of these children classes we have to call the Constructor for the parent also known as the super class of shape so we will eliminate these two lines of code use the super function dot call The Constructor of the parent that is the dunder init method but we need to pass in the color that we receive and is filled this will be a Boolean and let's do this with the square class and the triangle class we still need radius for the circle width for the square width and height for the triangle we're going to call the super function to take care of whatever attributes all these types of shapes have in common such as color and is filled now let's see if this works let's construct a few objects we will create a circle named Circle call The Constructor for Circle we have to pass in a color a Boolean if it's filled or not and a radius so for the color of the circle let's say red is filled let's say that is true and a radius of five you could even use keyword arguments for better readability although not necessary but for clarity let's say color equals red is filled equals true radius equals 5 let's see if this works I will print our Circle color it is red print our colors is filled attribute the circle is filled that is true and the radius print Circle do radius the radius of the circle is five we could even convert this to an F string I'll add a placeholder then add centim 5 cm let's construct a square object square equals Square we'll need a color is filled and a width I'll just copy what we have and make a few changes replace radius with width the color will be blue is filled will be false the width will be six we don't need a height because squares have an even width and height if we ever need the height we can assume it's the same as the width in this case six let's check out our Square square. color Square dot is filled Square do width our square is blue it's not filled in the width is 6 cm let's create a triangle object triangle equals triangle pass in our arguments the color will be yellow is filled will be true the width will be seven and the height will be eight let's print our triangle's color is it filled it's width and its height our triangle is yellow it's filled in the width is 7 cm the height is 8 cm so that's how you can use the super super function to reuse the Constructor of a parent class we don't need to manually assign each of these attributes within each of the children classes we can do that in just one place when we refer to Super imagine that we're replacing this with the parent class name such as shape that might be a good way to think of it use the Constructor of the parent class of shape and pass these arguments in what you could do as well is is extend the functionality of a method So within our shape class let's create a method of describe we will describe the attributes of this shape we will print use an FST string when we want to describe our shape let's say it is at a placeholder self. color what is the color of this shape and is it filled or not and add a placeholder we'll use a turn AR operator print filled if self. is filled is true else we will print not filled each of these types of shapes circle square and triangle will have access to a describe method let's attempt to use it take our Circle use the describe method that's inherited it is red and filled Square it is blue and not filled triangle it is yellow and filled so then we also have method overwriting what if we create a similar method of describe within circle square and triangle let's do that Define a describe method within our Circle let's C calculate the area what's the area of the circle I'll use an F string it is a circle with an area of then we'll calculate the area given the radius to calculate the area of a circle we can take Pi I'll just say 3.14 just to keep it simple times the radius squared self. radius times self. rius if I were to call the describe method will we use the parents version of describe or the child so let's take our Circle use the describe method the result it is a circle with an area of 78.5 I should really add cenim squar after that ctim squared this is called method overwriting if a child shares a similar method with a parent you'll use the child's version and not the parents this is Method overwriting if you would like to extend the functionality of a method from a parent you can use the super function not only do I want to use the describe method of the child I would also like to use the describe method of the parent So within this function we will use the super function access the describe method of the parent what we're doing is extending the functionality of the descrip method it is a circle with an area of 78.5 CM squ the circle is red and it's filled or you could change up the order let's use the parent classes describe method and extend the functionality with our own print statement it is red and filled it is a circle with an area of 78.5 CM squ let's finish this with the square and triangle classes I'll copy what we have for the described method within the circle class but we'll make a different calculation describe the square it is a square with an area of take self. width times self. width the height and the width are going to be the same if it's a square then describe our triangle it is a triangle with an area of width time height we have a height in this case divided two we've already described our Circle let's describe our Square it is a square with an area of 36 CM squ it is blue and not filled let's describe our triangle it is a triangle with an area of 28.0 CM squ it is yellow and filled all all right everybody that is the super function it's used in a child class to call the methods from a parent class also known as the super class it allows you to extend the functionality of the inherited methods within a child class you could use it within a Constructor to assign any attributes that all of its siblings have in common such as color or if that shape is filled when used within any other method you can extend the functionality of that method not only are we printing this message from the parent we're tacking on another print statement before that and well everybody that is the super function in Python what is going on everybody so today I got to talk about polymorphism in Python polymorphism is a programming concept it's a Greek word that means to have many forms or faces poly means many morph means form in programming an object can take one of many forms there's two ways to achieve polymorphism one is through inheritance an object could be treated of the same type as a parent class there's also duck typing which we'll talk about in the next Topic in this video we're more focused on inheritance what we'll do in this video is create a class of shape we'll write pass as a placeholder we will create a class of circle which will inherit from shape again writing pass class Square inherits from from shape class triangle which inherits from shape if I was to create a circle object Circle equals Circle our Circle identifies as a circle and since our Circle class inherits from the shape class our circle is also considered a shape it has two forms it's a circle and it's a shape but our Circle isn't a square or a triangle that could also apply to our Square class our square is a square our square is also considered a shape but our square is not a circle or a triangle those are two possible forms for our Square it's a square and a shape so let's say we would like to create a list of shapes what do they all have in common well they're all shapes a descriptive name for this list would be shapes equals an empty list I will instantiate a circle object object a square object and a triangle object our circle is a circle and a shape our square is a square and a shape our triangle is a triangle and a shape each of these objects has two forms or two faces let's fill in some of these classes let's say that with our shape class we will define an area method Define area I'm going to turn this into an abstract method meod I'll just write pass to work with abstract classes we need to import that from ABC import Capital ABC as well as abstract method preceding the area method I will add a decorator of abstract method our circle square and triangle classes they're all considered shapes they inherit from this class we need to Define an area method for each since they're all considered a shape every shape has an area with our class of circle let's define a Constructor Define in nit we will pass in one argument a radius what is the radius of the circle assign an attribute of radius equals the radius we receive let's do this with square Define innit one parameter the length of a side self. side equal side then triangle Define init we have two parameters base and height self. base equals base self. height equals height all right now let's finish defining these area methods for each class we will return 3.14 time self. radius to the^ of two so given a radius that's how to calculate the area of a circle then with our Square Define area we will return self do side to the power of two then with our triangle Define area return self. Bas time self. height time 0.5 now we have to pass in some arguments for our Circle we need a radius I'll pick four for the square the length of a side will be five then our triangle the base will be six the height will be seven we're going to write a loop to iterate through our shapes for every shape in shapes then we're going to print for every shape called the area method and that would give me these numbers if you would like you can format the output I'll just use an F string I'll add cm squared much better what if we were to create a class that's completely unrelated to shapes I will create a class of pizza I will Define a Constructor to construct a pizza object we need a topping and a radius what is the radius of the pizza self. topping equals topping self. rius equals radius within my list of shapes I'll add a pizza object but I have to pass in a topping such as pepperoni and what is the radius of the pizza let's say 15 cm so our pizza our pizza class doesn't have an area method here's what happens when I run this we get an attribute error Pizza object has no attribute area our pizza object is considered a pizza but it is not considered a shape it does not inherit from the shape class at the top here you know what a pizza is circular it could be considered a circle so how about this let's take the pizza class it will inherit from the circle class and within our Circle class we're already assigning the radius to the radius attribute so instead of doing that here within the Constructor for our pizza class let's call the super Constructor super which refers to the parent use its Constructor then pass in the radius we receive let's see if this works now that does here is the area of our pizza our pizza is considered a pizza it inherits from the circle class so it's also considered a circle and our Circle class inherits from the shape class our pizza has three forms our pizza is considered a pizza it's also considered a circle and it's also considered a shape it would make sense for it to fit into this list of shapes because our pizza also identifies as a shape so that's polymorphism everybody it's a Greek word meaning to have many forms or faces poly meaning many morph meaning form in Python there's two ways to achieve polymorphism one through inheritance an object could be treated of the same type as a parent and there's also duck typing which we'll discuss more in the next topic stay tuned for that and well everybody that's polymorphism in Python hey everybody so today I got to talk about duck typing in Python duck typing is another way to achieve polymorphism besides using inheritance objects can be treated as if they're a different type as long as they meet the minimum necessary at attributes and methods required of them it follows this adage if it looks like a duck and quacks like a duck it must be a duck as long as an object resembles another it could also be treated of that type so in this example let's create a class of animal we will have a class attribute of aive if you're an animal you will have an attribute of aive you're a living creature let's create a class of dog the dog class will inherit from the animal class they will inherit the alive attribute let's also Define a speak method if you're a dog you gain the ability to speak we will print woof then we'll create a cat class class cat inherits from animal for the speak method we will print meow let's create a list of animals what do these two classes have in common they both could be considered animals let's create a list of animals we will construct a dog object and a cat object if I was to write a for Loop for every animal in my list of animals have each animal use its speak method which will result in the dog going woof the cat going meow they're both speaking what if we add a class that has nothing to do with animals like class car cars will have a horn method that's how they speak when you honk the horn you will print honk within my list of animals let's create a car object it really doesn't belong in here but let's see what happens we have an attribute error car object has no attribute speak our car object doesn't have the minimum necessary attributes and methods when iterating through this list of animals we're calling each animal speak method which our car object doesn't have but it does have a horn method so what if we rename our horn method as speak maybe it's an AI car or something well this woodwork the dog goes woof the cat goes meow the car goes honk so our car object it quacks like a duck we could consider it a duck it has the minimum necessary methods to be considered an animal animals inherit this alive attribute let's utilize that after the animal speaks let's print their alive attribute print my animals Al live attribute my car object doesn't have that attribute we get an attribute error car object has no attribute alive but if I was to add that attribute alive equals false we have true for the dog it's living true for the cat it's living but false for the car it's not living it's not a living creature my car meets the minimum necessary requirements to be considered an animal if I were to set this to be alive well then it would be a living car kind of like the movie Cars so with python duck typing is another way to achieve polymorphism besides using inheritance as long as an object has the minimum necessary attributes and methods you could treat it as a different type of object if it looks like a duck and quacks like a duck it must be a duck and well everybody that is duck typing in Python hey what's going on everybody today I'm going to talk about static methods in Python a static method is a method that belongs to a class rather than any object from that class any instance instance methods we're already familiar with them they are methods that belong to individual objects created from that class they're best for operations on instances of that class any objects whereas static methods they're best for utility functions within a class that do not need access to class data I'll demonstrate the differences between an instance method and a static method we'll Begin by creating a class of employee we'll need a Constructor let's define that to create an employee object we'll need a name and a job position we will assign self. name equals name self.pos equals position we will create an instance method of get info we will return employee info we will return an FST string where we will display self. name equals self.pos get info is an instance method each object that we create from this class will have their own get info method to return the information on that object the object's name and the object's position now we'll create a static method to create a static method we need a decorator of static method static methods are best for General utility functions within a class we'll Define a method to check to see if a job a position is valid which we will name is valid position so static methods they don't have self as the first argument we're not working with any objects created from this class to check to see if a position is valid we will pass in a job position which I will name as position I will create a list of valid positions let's assume that our is the Crusty Crab what are some valid positions a manager is a valid position a cashier a cook then let's say a janitor then we will return we'll use a membership operator check if position that we receive is in our list of valid positions what we have done is that we have created a static method we don't need to rely on any objects to use this method for example to use a static method we will use the name of the class rather than any object that we create from this class such as this we don't need to do that we type the class name followed by the static method is valid position then I did set this up to accept one argument let's check to see if a cook is a valid position then I do need to print this what is the output a cook is a valid position what about a rocket scientist that would probably be s's job that is false a rocket scientist is not a valid position at the crusty crab this is a static method it belongs to the class not any object created from that class now let's create a few employee objects let's say employee 1 equals a new employee we have to pass in a name and a job Eugene will be the first name that's Mr Krabs he will be a manager employee 2 equals employee Squidward will be a cashier employee 3 equals employee employee 3 will be SpongeBob SpongeBob will be a cook to call an instance method we have to access one of the instances of the class in order to use it if I want to check the info on employee 1 I will access that object that instance use the get info method then I need to print it take employee one get the info Eugene is the manager let's do this with employee 2 and employee 3 Eugene Mr Krabs is the manager Squidward is the cashier SpongeBob is the cook for an instance method you access a object then call the instance method with the static method you only need to access that class you don't even need to create any objects from that class it's a general utility method all right everybody those are static methods they're a method that belongs to a class rather than any objects created from that class they're usually used for General utility functions that do not need access to class data and well everybody those are static methods in Python hey what's going on people so today I got to talk about class methods in Python a class method allows operations related to the class itself they take CLS as the first parameter whereas instance methods will take self self refers to any object created from that class CLS meaning class refers to the class not any objects here's an example we will create a class of student we'll need a Constructor to construct some student objects all students will have a name and a GPA self. name equals name self. GPA equals GPA we will also create a class variable for this demonstration of count we will count how many students we create whenever we construct a student object we will access the class of student take our count variable increment it by one whenever we create a student object increase count by one I will create an instance method of get info instance methods have self as the first parameter we're referring to the object we're currently working with I will return an F string where we will display the students name and their GPA self. name self. GPA I'll add a comment that this is an instance method Now to create a class method to work with class data we will declare a class method with a class method decorator class method what we're going to do is Define a method to get the count the class variable of count this method will be called get count rather than self as the first parameter we'll be working with a class CLS meaning class I will return an F string total number of students at a placeholder CLS count let's test this to call a class method you take the name of the class followed by the class method get count and then we do need to print this what is the count of my current students total number of students is zero let's create a few student objects we will create student one equals called the student Constructor we have to pass in a name and a GPA let's say that the name is SpongeBob SpongeBob has a GPA of 3.2 we'll create two more students student two student three student two will be Patrick Patrick has a 2.0 then Sandy Sandy Smart in fact she's a genius she has a perfect 4.0 now let's count the number of students total number of students is three when we call this class method we can access or modify class data this class variable of count rather than using self we use CLS for the class let's create one more class method this time I'll calculate the total GPA of all my students we'll need a class variable to hold that data let's say total GPA equals 0 whenever we construct a student object we will access our class of student get the total GPA then add plus equals this student's GPA that we have just created basically speaking the total GPA this variable is going to accumulate all of the GPA of every student and store it as a sum to find the average we're going to divide it by the count the number of students we'll do that within a class method to create a class method again we need to use the class method decorator I will Define a method of get average GPA the first parameter is CLS for class I will check if CLS count the count variable of my class is equal to zero that means if we have no students if that's the case if there's no students we're going to return zero because otherwise we're going to divide by zero and we'll get an erir else we're going to return an F string follow this formula we're going to take the total GPA of my class class. total GPA divided by class. count the number of students we have that's how to calculate the average GPA after getting the count of the number of students to access a class method we take the name of the class student call the class method get average GPA then I will print it total number of students is three the average GPA is 3.06 repeating after calculating the average I'm going to add a format specifier of 2f just around to two decimal places and I'll add average GPA coin space then we'll calculate the average all right everybody those are class methods instance methods are best for operations on instances of the class any objects static methods are best for General utility functions which do not need access to class data class methods are best used when we're working with class level data or we require access to the class itself such as when we're working with class variables rather than using self as the first parameter we're going to use CLS meaning class and well everybody those are class methods in Python yo what's going on people so today I'm going to explain magic methods in Python magic methods are also known as Dunder methods meaning double underscore you typically find these within classes we're already familiar with one of them our Dunder init method we have double underscores on the left and double underscores on the right but there are others I'll cover a few of the more beginner friendly ones so what these methods do is that they're automatically called by using some of pythons built-in operations such as printing an object seeing if two objects are equal greater than or less than when we use many of Python's built-in operations with objects we can Define and customize the behavior of those objects so in this demonstration I'm going to create a class of book we will construct some book objects we will Define a magic method a Dunder method of init to initialize these objects for a book we need a title an author and the number of pages we'll say num Pages self. tile equals title self. author equals author self. number of pages equals number of pages when we call the class of book we Are automatically calling Dunder init so let's create a book object book one equals book we need a title an author and number of pages so since we're dealing with this topic of magic methods I'll pick some fantasy related books for my first book book I'll pick the Hobbit that's the title the author is JRR token the number of pages is 310 so for my next book book two I will pick Harry Potter and the philosopher stone the author is J K rolling the number of pages is 223 then we have book three for my third book I will pick The Lion the Witch and the Wardrobe the author is CS Lewis the number of pages is 172 okay here are my three free book objects when we call the class of book and pass an arguments we will call the dunder init method it's a magic method it's automatically called behind the scenes within this magic method we can Define and customize the behavior of objects and in this example we're just assigning the attributes of title author and number of pages that is one built-in operation of python what would happen if I was to print book one directly to the console here's what happens well we're given a memory address here's book two and book three well we can customize this Behavior we will use the dunder string method double underscore St Str meaning string double underscore again we have one parameter of self instead of returning a memory address we can customize this Behavior let's instead return an F string I'll add two placeholders we will display self. tile the title of the book by self. author and I'll place the title within single quotes now let's print book one we have The Hobbit by JRR token let's print book two Harry Potter and the philosopher stone by JK Rowling and book three the line the witch in The Wardrobe by CS Lewis so that is thunder string we can return a string representation of the object when we print it directly to the console here's another Dunder method we can check to see if two objects are equal I will print is book one equal to book two that gives me false if they were to have the same title the same author and the same number of pages then python would say they're not equal still so let's customize this Behavior we will Define a method of Dunder equals which is just EQ for parameters we have self the first book we're examining in this case book one and other other means the other book we're examining two objects for equality to do that we'll see if the title of two books and the author is the same we'll disregard the number of pages you can have two different versions of the same book they might have different font sizes or the dimensions of the physical Pages might be different so we will return a Boolean value we will examine if self that's the first book is the title attribute equal to our other books title and is the author of the first book self. author equal to our other books author if I were to run this we get false book one does not equal book two but if they have the same title I'm going to replace these and the same author then they would be equal and we'll disregard the number of pages let's say that with this version of The Hobbit they're using a smaller font size so there's less Pages we're using Dunder equals to compare if two objects are equal what if I was to print book two is less than book three like what does that even mean and I'm just going to get rid of these two lines type error less than is not supported between instances of book and book so we can't use less than on two objects but we can customize that behavior by using Dunder less than which is just LT we're examining one book and the other book self and other let's compare the number of pages we'll compare if the pages of book two is less than book three we will return a Boolean value is self. number of pages less than other number of pages so now this should not give us an error book two does not have less Pages than book three another would be greater than I'll just copy what we have Dunder GT for greater than for our first book of self is it greater than the number of pages of the other book well that's true the number of pages of book two is greater than book three let's use Thunder add to add the pages of two books together what would happen if I were to add two books together book two plus book 3 well we get a type error unsupported operand for book and book well to customize the behavior of addition we will Define Dunder add we have self and other for the other object let's add the pages together of two books maybe we need a summer reading list and we would like to see what the total number of pages is I will return self. number of pages attribute plus our other books number of pages that would give me 395 that's 223 + 172 heck I'll even put this within an F string cuz why not then I will add the word Pages 395 Pages within an object we can search for a keyword within one of the attributes so let's find the word the lion within book three to do that I would write a statement like this Lion in book three type error argument of type book is not iterable we will Define Dunder contains besides self we will pass in a keyword a keyword that we're searching for I will return then we'll use the in membership operator is our keyword in self. tile I'm looking for the word lion that's going to return true if lion is in the title of this book or is our keyword in self. author maybe we're searching for an author let's try that again that returns true lion is in book three however lion is not within book one that's false is rolling in book two that's the author that is true is rolling in book three that is false that is dund contains we are searching for a keyword in an object now we could search for a key given an object for book one we'll use the index operator and look up an attribute let's get the title of book one the default behavior is that we get a type error book object is not subscriptable so to customize this Behavior we will use dund get item besides self we have one parameter of key we're accessing book attributes by indexing with this object return the value at this key what's that attribute we will check if our key that we receive is equal to title which it is in this case we will return self. tile What's the title of the book so that would give me The Hobbit here's book two and book three what if the key is author none we didn't set that up yet if key is equal to author then return self. author the author of book three is CS Lewis two is JK Rowling book one is JRR tolken what about number of pages num Pages well we're not set up for that yet I'm going to turn this into an El if statement else if key is equal to num Pages then we will return self. num Pages the number of pages in book one is 310 book two is 223 book three is 172 what if there is no key otherwise if there is no matching key I'll add an L statement let let's return an F string key placeholder our key that we pass in as an argument was not found what do books not have well they don't have audio I guess unless it's an audio book is there a key of audio in book three there is not key audio was not found and I'll place that within single quotes much better all right everybody so those are magic methods also known as Thunder methods meaning double underscore they are automatically called by many of Python's built-in operations they allow developers to define or customize the behavior of objects when we use those built-in operations and well everybody those are magic methods in Python hey everybody so in today's video I got to talk about the property decorator in Python the property decorator allows us to Define a method as a property we can access it like it's an attribute one of the benefits is that when Reading Writing or deleting attributes we can add additional Logic the property decorator gives us a getter method to read a Setter method to write and a deleter method to delete when working with attributes in this example we'll create a class of rectangle we need a Constructor let's define that when constructing a rectangle object we will need a width and a height we will assign the attribute of width equal to the width that we receive when constructing this object self. height equals height let's construct a rectangle object rectangle equals rectangle we need to pass in a width and a height then I will print my rectangles width rectangle. width and the height rectangle. height with my rectangle the width is three the height is four using the property decorator when reading these attributes of width or height I can write some additional logic let's say that when accessing the width or the height I would like to display one digit after the decimal then add centimeters here's one way in which I can do that for each of these attributes I'm going to create a method we will Define a method of width no parameters besid self for now I'll write pass and Define height preceding each of these methods I will use the property decorator so at property now when accessing the width or the height will be returned with whatever is Within These methods of width and height but there's one change we're going to make to these attributes we'll set these attributes to be private prefix each of these attributes with an underscore this tells you and other developers that these attributes they're meant to be protected they're internal we shouldn't access the width or the height directly outside of this class technically we could I will access the internal version of width and height we get three and four but we do have a warning access to a protected member width of a class that applies to height as well our width and our height are only meant to be used inside of this class if we need to get the width and the height we will do so through these getter methods provided by the property decorator so when accessing the width let's return an F string I will access self. private width add a format specifier to display one digit after the decimal. 1f followed by centim we'll do this with the height as well we will return self. private height so now when we access the width or the height we will do so using these getter methods if I access these private width and height attributes instead again they will be three and four it's kind of like their raw these attributes are meant to be used internally inside of the class so that that's the point of a getter method we can add additional logic when reading one of these attributes when we try to get them we can also add Setter methods if we would like to set or write these attributes here's how let's take our width we will create a decorator of at width. Setter when attempting to set the width we will do so using this method we will Define our method name of width we will have one parameter a new width we don't want the parameter name to be the same as the method name that's why we're naming it something different when setting the width let's check to see if the new width is greater than zero if so we will take self. private width equals our new width else let's print something let's print width must be greater than zero and let's do this with the height height. Setter Define height pass in a new height if our new height is greater than zero assign self. private height equals the new height else print height must be greater than zero before printing the width and the height let's take our rectangle width set it to be zero then see what happens well we get that message width must be greater than zero if I were to set width to be five well that does work our width is now five let's change the height rectangle. height I will set this to be Nega 1 height must be greater than zero and the height hasn't changed what about six six does work when using these Setter methods we can add additional logic when writing or changing one of these attributes these are Setter methods now if you need to delete an attribute here's how there is a delete keyword we will delete our rectangle's width and delete our rectangle's height in this series we really won't be using the delete keyword but you should still know that it exists so we will create a deleter method at take one of the attributes in this example with we will create a deleter method the method name will be width the name of the attribute there will be no parameters besid self we will delete self. private width then let's print something just to confirm that this was deleted width has been deleted same thing applies to height take the attribute of height Define height delete private height height has been deleted when deleting our width or our height we get that confirmation message width has been deleted and height has been deleted all right everybody so that is the property decorator we can define a method as a property meaning it can be accessed as if it was an attribute one of the benefits is that we can add additional logic when we read write or delete attributes the property decorator gives us a getter Setter and deleter method getter methods to read Setter methods to write and delete methods to delete and well everybody that is the property decorator in Python what is going on everybody so today I got to talk about decorators in Python a decorator is a function that extends the behavior of another function without modifying That Base function we pass the base function as an argument to The Decorator function for example let's say we have a base function of get ice cream and you can pass in a flavor of ice cream well some people might want sprinkles on their ice cream and others may not they might just want plain vanilla well we could add sprinkles by using a decorator we're extending the behavior of a function where we get ice cream where we're adding sprinkles but we may not want to change the base function because some people don't like sprinkles think of decorators that way we're adding something to a base function without changing it here's how to create a decorator let's start with the base function we will create a function to get ice cream there will be no parameters for now all we're going to do is print the following message here is your ice cream and for fun I'll add an emoji because I like emojis I'll add an ice cream Emoji to call this function all I got to do is call the get ice cream function here is your ice cream here's how to create a decorator a decorator is a function we'll need to define it Define add sprinkles our decorator function is going to have one parameter a function but we'll just rename it to Funk for short we're going to pass a function to our decorator function within our decorator function we will define an inner function of wrapper currently there's no parameters we'll set that up later within this wrapper function we will call the function that we receive this parameter then we will return our wrapper function up until this point we've been returning values but now we're going to return an entire function here's the basic formula to create a decorator to apply a decorator to a base function preceding that function you're going to add at the name of The Decorator so add sprinkles is a decorator the base function is get ice cream within our decorator how do we want to add sprinkles exactly currently our decorator doesn't do anything here's what happens we just print here is your ice cream let's say that before we're given our ice cream we'll print a statement that we add sprinkles within our decorator imagine that we're replacing calling function with this print statement let's create another print statement where we add sprinkles before it I will print the following message you add sprinkles and I'll add an emoji how about confetti that could resemble sprinkles okay let's see what happens you add sprinkles here is your ice cream we're decorating our base function of get ice cream with a decorator of AD sprinkles where're not modifying the base function we're extending it now we have a nested function of wrapper within our decorator it is necessary to have this here's why so I'm not going to call the get ice cream function quite yet so nothing should happen if I was to remove this wrapper well we'll end up calling this function as soon as we apply The Decorator we're not even calling following the get ice cream function at all we only want to execute this code when we want ice cream not whenever we apply The Decorator that's why we need that wrapper function we'll get ice cream and add sprinkles only when we call that function then at any point in my program if I call the get ice cream function then we get ice cream with sprinkles let's apply more than one decorator we'll create a decorator to add fudge Define add fudge we have one parameter a function which we will rename as Funk we need an inner rapper function this is so that we don't call this function when we apply a decorator I will print you add fudge close enough we'll add a bar of chocolate then call the base function that we receive then we need to return the wrapper function all right given our base function we can apply more than one decorator let's say that after adding sprinkles we will apply The Decorator where we add fudge so now we have the following output you add sprinkles you add fudge here is your ice cream so with decorators you can apply more than one decorator to a base function what if your base function accepts Arguments for example when we get our ice cream we need to pass in a flavor like vanilla I will set up one parameter of flavor I will convert our print statement to be an F string here is your add a placeholder flavor of ice cream let's run this and see what happens all right we have a type air our wrapper function isn't set up to accept arguments what you'll see within wrapper functions is that they'll have parameters of args and quars to accept any number of arguments and keyword arguments then when you call your base function in this case get ice cream we we will also set this up to accept any number of arguments and keyword arguments let's do that within our ad fudge decorator too our wrapper function will accept any number of arguments and keyword arguments same thing goes with the base function and now this should work you add sprinkles you add fudge here is your vanilla ice cream or any other flavor of your choosing like chocolate you add sprinkles you add fudge here is your chocolate ice cream all right everybody so those are decorators they're a function that extends the behavior of a base function in this case get ice cream decorators extend a function without modifying it if you would like to apply a decorator to a function you precede that function when you define it with at the name of The Decorator and you can apply more than one and well everybody that is an introduction to decorators in Python hey everybody so today I got to talk about exception handling in Python an exception is an event that interrupts the normal flow of a program there are many different types of exceptions which include but are not limited to zero division error exceptions when you attempt to divide a number by zero for example 1 divided 0 that would interrupt our program we have a zero division error another is a type error that's if we attempt to perform an operation of a value that's of the wrong data type for example 1 plus a string of one that would give us a type error unsupported operand for INT and string value errors tend to happen when you attempt to typ cast a value of the wrong data type so let's say we attempt to type cast the word Pizza as an integer well Pizza isn't a number we have a value error invalid literal for INT base with 10 pizza so exceptions will interrupt our program if they're not handled gracefully and here's how we can do that there's three steps we can write a try accept and finally block any code that's dangerous where it could cause an error you'll place within a tri block for example anytime we accept user input that is considered dangerous code because a user can type in anything so let's say we have a number number equals we will accept some user input we will tell a user to enter a number then we're going to typ cast it as an integer then I'm going to print 1 divided by whatever the user types in if I were to type in zero we get a zero division error if I type in the word Pizza we get a value error we would like to prevent our program from stopping this code is considered dangerous a user can really type in anything so we're going to surround this code within a tri block we'll type try colon and then indent any code underneath it we're going to try this code if an exception happens we will move on to step two subsequently following the tri block we will add an accept block if we run into one of these exceptions we can execute some alternative code for example a zero division error if somebody attempts to divide a number by zero we can take a different course of action instead of our program crashing and coming to a halt let's print you can't divide by zero idiot let's attempt to divide by zero enter a number zero you can't divide by zero idiot we have gracefully handled this exception so now let's say somebody types in the word Pizza when we're asking for a number well we have a value error well we can chain accept blocks if we encounter a value error let's add an accept block for that accept value error we're going to print enter only numbers please enter a number I'll type in the word Pizza enter only numbers please that's good we're not interrupting our program now what you may see some people do is they will just catch all exceptions accept exception now this is actually considered bad practice exception will catch all exceptions however it's too broad of a clause it's good practice to tell the user what went wrong exactly if we resort to just catching all exceptions you may see an error message such such as something went wrong I'm looking at you Microsoft we want to tell the user what went wrong exactly I would only catch all exceptions as a last resort first let's try and tell the user what went wrong exactly so I'm going to undo all this code if there's an exception that occurs it's not a zero division error and it's not a value error then we can add that catch all where we catch any unseen except itions now lastly we have the finally block the finally block always executes regardless if there's an exception or not it's usually used for any sort of cleanup that you need to do such as if you're handling files you may try and open a file and then you'll want to be sure to close that file when you're done with it that would be handled within the finally block but we'll get to file handling pretty soon in the next topic so just for the time being I'm going to print do some cleanup here all right let's test this enter a number I'm going to divide by zero you can't divide by zero and we still execute the finally block enter a number I'll enter in one 1 / 1 is 1 and we still execute that finally block the finally block will be more useful in future videos all you need to know is that it always executes regardless if there's an exception or not all right everybody so that's exception handling an exception is an event that interrupts the normal flow of a program there are many different types of exceptions you can always look under the official python documentation for an extensive list and well everybody that's exception handling in Python hey what's going on everybody today I'm going to show you how we can handle a basic file detection using python this topic is the first of many involving a minseries on file handling using python first we'll need to cover file detection before we read and write files to work with files using python we will import the OS module OS means operating system this module provides a way for python programs to interact with the operating system be sure to import the OS module at the top for my demonstration within my project folder I'm going to create a new file new file I will name this file test and this will be a plain text file it will have the file extension of txt this file really doesn't need to say anything I'm just going to type I like pizza because I do the context doesn't matter we're not going to be reading files in this video for convenience I'm going to assign a variable of file path this will be a string for file detection we can either use a relative file path or an absolute file path we'll cover relative file paths first these two files are right next to each other my main python file and my test file if we're using a relative file path I only need the file name including the extension test.txt we'll be passing in the string of file path as an argument to check to see if this file exists I will use an if statement if access the OS module access the path there is a built-in method of exists we'll pass in our file path as the argument this method returns a Boolean value of true or false if this file exists so if this file does exist test.txt let's print the following I'll use an F string the location I'll add a placeholder exists I will place my file path within that place holder and I'll surround it with single quotes to make it look nice if this method returns true do this else we'll do something else I will print that location doesn't exist all right let's see what happens the location test.txt exists now what if I get the extension wrong let's say that I'm looking for a PDF but it's really a txt file well that location doesn't exist you do have to be sure to get the file extension correct what if this file was in a folder within my python project I will create a new directory I will name this directory stuff then I will place my test file within the stuff folder pycharm wants me to refactor my code because the location changed I'm not going to do that I'm going to be sure that this box is unchecked and press refactor we're using a relative file path that test file is no longer next to my main python file here's what happens that location doesn't exist with our relative file path we'll have to navigate to our stuff folder then find the test file so preing this file name I will access the stuff folder stuff slash the name of the file test.txt and now we can locate that file the location stuff SL test exists when working with relative file paths you may need to open up a folder then find your file you also could work with absolute file paths so for this demonstration on my desktop I'm going to create a new file new text document text test if I were to look at the properties this is a txt file a text document I'm going to copy the location within my file path I will paste it then list the name of the file test.txt this is an absolute file path one problem we're running into when working with strings a backs slash does serve as an escape sequence on python thinks we're trying to print a tab character we can solve this with double backs slashes or we could use a forward slash either one works all right let's see if that file exists that does the location of that absolute file path does exist if I were to get the extension wrong let's say this is a PDF well that location doesn't exist there is a built-in method of is file to check to see if that file is in fact a file and not a directory let's add the following after we detect this file we'll write a Nesta if statement if os. path. is file then passing our file path as an argument if this file is in fact a file and not a directory I will print that is a file the location of that absolute file path does exist that is a file what if it was a directory a folder I'm going to delete this go to new folder I will name this folder test to check to see if a location is a directory let's add an LF statement else if os. paath do iser meaning is directory this is a method we'll pass in our file path if this is a directory a folder I will print that is a directory let's run this again that location doesn't exist oh we have to get rid of the file extension it is not a plain text file the location of that absolute file path exists that is a directory a folder all right everybody that's basic file detection in the next few videos we're going to be reading and writing files and well everybody that is basic file detection using python hey what's going on everybody in today's video I'm going to show you how we can write and output files using python we'll cover plain text Json and CSV v files but we'll start with plain text because it's the easiest suppose we have some data that we would like to Output I'll create a variable of text Data think of a food you like I will output I like pizza for convenience we'll create a variable a file path this can be a relative file path or an absolute file path within this file path we'll need a name for this file I will name this output then include the file extension this will be a txt file a plain text file this is a relative file path when I generate this file it will be within the same project folder as my main python file to create a file we'll write the following with open function pass in our file path and a character of w to write as file and for now I'll write pass there's a few things going on here with is a statement it's used to wrap a block of code to execute if we open a file the width statement will also close that file when we're done with it so we don't need to manually close files when you open a file it is good practice to close it because if you don't you may run into unexpected Behavior the width statement takes care of that for you the open function will return a file object the first parameter is the file path the second parameter is the mode w Is Write X will also write if this file doesn't exist if it already does exist we'll receive an error A is for append to append a file and R is to read but we'll take care of reading in the next video so we will stick with W to write a file the open function returns a file object the first argument is the file the second argument is the mode you can set these to be key word arguments if it's easier for you to read when the open function returns a file object for us we're using the as keyword to give it a name as file it's kind of like we're instantiating a file object file equals file file is the name of the file object to write to this file we're going to take our file object use the built-in write method then pass in our text Data then when this is done I'm going to print a confirmation message I'll use an F string let's say text file I'll add our file path place it within single quotes was created let's see what happens text file output.txt was created and here's that file I like pizza we also have the capability ability of setting an absolute file path let's say I would like to Output this file to my desktop I would just need that location let me just get the location from one of these folders by going to properties I will copy this location this is the location to my desktop but for you it's probably going to be different then I will paste the absolute file path a backs slash is an escape sequence within a string we either could use double backs slashes or a forward slash now let's see if this outputs to my desktop text file here's the file path was created and here's that file it's a plain text file and it says I like pizza so when working with the file path it could be a relative file path or an absolute file path all right now for our text Data there are different modes as well W is for write if we use x we'll write a file if that file doesn't already exist in this case it does on my desktop we already have a file named output and it's a plain text file so when I run this with the mod of X we get a file exists error that file already exists we could catch this exception so that our program isn't interrupted I will copy the name of this error I will place my code within a triy block we will try this code and catch any exceptions except file exists error if this file already exists let's take a different course of action let's print that file already exists so now when I run this again our program isn't interrupted we receed this message that file already exists if I were to delete that file bye-bye then run this again well we create a new file text file that absolute file path was created and here it is again now for the mode there's also a a to append any new data will be append to that file we get I like pizza I like pizza when a pending data if you would like that data on a new line we can add a new line character W will overwrite a file so we're back to the original when a pending either before or after we write our Text data we could add a new line character let's say let's do that before new line plus our text Data here's the output again we're appending not writing I like pizza I like pizza our second sentence is on a new line let's run this a couple times we should have several lines now let's work with a collection let's say we have a list of employees we'll pick some employees at the CR crab so we have Eugene I guess he is technically the manager I don't know if that counts as an employee Squidward SpongeBob and Patrick Patrick worked at the K Crusty Crab in one episode he counts then we'll to be sure we're writing our employees this is what's going to happen we have a type error write argument must be a string not a list in order for us to write each item within a list we'll need to iterate over it using some sort of loop we can't write a list or any other collection directly here's what we'll change for every employee in our collection of employees we're iterating over something that is iterable we will access our file object use the write method then write each employee here's the result we get one long string of each item in this list if you prefer after writing each employee we could add a new line character after and here's the output we get each item in our list on a new line or rather than a new line character we could use a space this would output all the employees but space them out now we'll be outputting a Json file in summary a Json file is made of key value pairs for our data let's say we have a dictionary of employee a dictionary is made of key value pairs we'll have a name of SpongeBob SpongeBob's age will be 30 his job his position is that he is a cook so this is the data I would like to Output I'll keep the file path the same we'll change the file extension tojson we will need the help of the Json module let's be sure to import that import Json within our width block we'll make the following change we're going to access our Json module use the dump method the dump method will convert our dictionary to a Json string to Output it so we have to pass in our Json data of employee our file as the second argument then for a confirmation message let's print Json file was created here's the result Json file at this location was created and here's my Json file I'll go to properties we'll confirm it is a Json file it is and I'll open it here's the result now you could add indentation after each key value pair here's how after our second argument our file we can pass in a keyword argument of indent for each key value Pair by how many spaces do we want to indent each let's say four and let's take a look I think that's more readable we're indenting each key value Pair by four spaces so that is a Json file it's a collection of key value pairs a dictionary or anything that uses key value pairs is a great candidate to be output to a Json file all right now we're going to work with CSV files CSV means comma separated values C CSV files are pretty common with a spreadsheet of data like an Excel spreadsheet we will create a 2d data structure of employees this will be a list of lists let's add four we'll need the help of the CSV module import CSV think of our 2D data structure as a table of rows and columns so for the first row I will add name comma age comma job the second row will have a name of SpongeBob age 30 job cook for the next row we'll have Patrick Patrick will be 37 what is Patrick's job I don't know he's unemployed then we'll have Sandy Sandy will be 27 Sandy is a scientist okay now with our file path the file extension is going to be a CSV file comma separated values within the context of our width block we're going to create a writer object to write to a file writer equals access the CSV module use the writer method of that module then pass in our file writer is an object it provides methods for writing data to a CSV file and then we'll print a confirmation message of CSV file was created here's the output currently we have a CSV file I'll go to properties to confirm it well we have no output we have to iterate over all the rows in our 2D collection we'll write the following for every Row in our data of employees we'll take our writer object use the right row method and pass in that row that we're iterating over now let's take a look that's better however the writer method gives us a new line after each row so if we would like to prevent that when we open this file I will set the keyword argument of new line equal to no characters an empty string let's take a look again yeah that's much better so this is a CSV file it's made of Comm separated values all right everybody so that is an introduction to writing files using python what's going on everybody today I'm going to show you how we can read files using python we'll cover plain text Json and CSV files in the previous topic we have created some sample files to work with here is my plain text file my Json file and my CSV file they're all named input they each have a different file extension for convenience I will create a variable of file path we can list a relative file path or an absolute file path I'll use an absolute file path I'm going to right click on the file I would like to read go to properties copy the location then paste it then add the file name including the extension input and this is a txt file within the context of a string backs slashes are Escape sequences for special characters we would either need to use double back slashes or a forward slash here is the absolute file path to the file I would like to read to read this file I will add a wi block with is a statement it's going to wrap a block of code within a context manager and it'll close a file if we open it it is good practice to to close a file if you do open it if you don't it can lead to unexpected Behavior we will use the open function the open function has two arguments our file path and a mode to read a file we'll set the mode to be R for read the open function is going to return a file object which we will give a nickname of file as file when we read our file object it's going to return one long string which we will assign to a variable named content content equals file use the read method and assign it to this variable then I'm going to print the content print our content the content of the file here's the result that is the content of my file I like pizza it's really good let's say we can't find this file perhaps I forget the file extension we'll run into a file not found error this will interrupt our program we can catch exceptions when they happen any dangerous code that may cause an exception we can wrap within a tri block if there's an exception we will catch them by stating accept the name of the exception in this case File not found error instead of our program being interrupted let's take a different course of action we will print that file was not found let's try this again that file was not found at least our program isn't being interrupted let's add the file extension back what if we don't have permission to read this file to demonstrate that I'm going to rightclick on that file go to properties go to security edit the permissions I will deny any sort of control I will attempt to read this file and we get a permission error permission denied we could handle this exception as well if we encounter a permission error I will print the following you do not have permission to read that file let's run this again you do not have permission to read that file those are a few exceptions we can handle in case they appear file not found errors and permission errors let's say we would like to read a Json file we will need the help of the Json module I will import the Json module at the top of my program I need to get the file path of this Json file it's pretty much the same as before in this case the file extension is a Json file there's only one change we're going to make we will assign our variable of content equal to access the Json module use the load method and load our file and that should read the contents of my file here's my Json file name SpongeBob age3 job cook with the data of your Json file you could access a value given a key I will access our content by its key of name that will return the value of SpongeBob age 30 job cook now here's how to read a CSV file we will import the CSV module the file extension is going to be CSV again this is on my desktop in the same location as the previous files my content will equal access the CSV module access the reader method and pass in our file here's the content currently we're given a memory address with the CSV file what we need to do is read the CSV file line by line all of the data is within a collection which we need to iterate over so to do that we're going to create a for Loop for every line in my content I will print each line that's much better the format resembles a spreadsheet like an Excel spreadsheet there's rows and columns to get a specified column we can access an index in my example R line at index of zero would give me the First Column name SpongeBob Patrick Sandy the next index would be all the ages of each person 30 35 27 and index two would be the job positions cook unemployed and scientist if you need a specific column of data from a CSV file you can use an index as one possibility all right everybody so those are a few ways in which we can read files using python hey what's going on everybody so in today's video I'm going to show you how we can work with dates and times using python we will import the date time module this allows us to work with dates and times using our system clock our computer's clock this video serves as more of an introduction to create a date object we will assign an object of date let me zoom in a little bit we will access the date time module called the date method within the date method we will pass in the following arguments a year of our choosing so for me I'll say 2025 a month one corresponds to January these are numeric months and a day a day of the month I will say the second if I was to print the state object here's what it outputs the year is 2025 January 2nd to get the date right now let's say today this will return a date object that represents today access the date time module access the class of date then call the today method to return the date of today let's print today currently I'm recording this video July 14th 2024 for me that is the result of my today object when I print it now we'll work with time I will create a Time object access the date time module call the time method we have to pass in hours minutes and then seconds so for the hour let's say 12 30 and 0 seconds I will print the current time it is 12:30 now to get the time right now on our system clock I will create a datetime object of now equals access the datetime module now within the datetime module there is a date time class we have to access we will access that I know it looks kind of silly date time. dat time do the now method so we're accessing the datetime module there's a built-in datetime class we have to access then within that class there's a now method what is the time right now according to my system clock this returns a date and a Time July 14th 2024 it is just after 9:00 a.m. we can format the appearance of the string here's how I'm going to reassign our datetime object of now our datetime object has a string format time method stf time we're going to pass in a string and include some format specifiers let's say I would like to display the hour first I'm going to add a percent these format specifiers you can find according to the datetime documentation online so I will display the hours that would be percent H percent M for minutes percent s for seconds let's see what we're working with we have the hours the minutes and the seconds I will separate each of these with the colon that's better now I'll add the date I'll start with the month I will add a format specifier of lowercase M then the day a format specifier of D then the year format specifier capital Y here's the result we have the month the day and the year I'll add a dash to separate these that's better or if you prefer the day first rather than the month we can switch this around it depends on how you read dates in your country now we're going to cover an exercise we're going to see if the current date and time has passed a Target date and time so we are going to create a Target date date time equals access the date time module we will create a new date time so now we have to pass in a date and a time for my date time let's say it's something far into the future like the year 2030 January 2nd for the hour it will be 12 30 and 1 second I'm going to get the time right now which I will name current date time equals access the date time module access the date time class call the now method to return the current date and time right now using an if statement I will see if our Target date time is less than the current date time have we already passed this date if our Target date is less than the current date that means this date and time has already passed I will print the following if that's the case Target date has passed else I will print Target date has not passed here's the result Target date has not passed what if I set the target date to the year 2020 well then the target date has passed so that's how we can check to see if a date and time has already passed has it elapsed all right everybody so that is an introduction to working with dates and times using python all right everybody so in today's video we're going to create a working alarm clock using python for this project we will need the following Imports we will import time we'll be updating our clock every second the time module is going to help us with that as well as import date time the date time module allows us to work with string representations of a time in my opinion the easiest way to work with sound effects is to actually use pame so we will import pame game now you may need to download the pame package here I'm getting a message that there's no module named pame there might be a link to install it even too one way in which you can download the pame package is to open up a terminal then use pip pip is Python's package manager pip install py game all right we have our three Imports let's create a function to set a alarm we have one parameter and alarm time and for now all right pass our alarm time parameter is going to be a string representation of a time in military time I would like to start this program if I running my main python file directly I can add the following if statement if Dunder name is equal to a string of Dunder Main if we are running this main python file directly then we will set the alarm but first we have to prompt the user what they would like to set the alarm too so we will Define a variable of alarm time equals ask for some user input using the input function we will prompt the user to enter the alarm time and give a format hours minutes and seconds again this is going to be in military time once we have our alarm time we will call the set alarm function and pass in our alarm time all right we are now within the set alarm function when we call this function let's print the following I'll use an F string alarm set 4 then include the alarm time you will need an MP3 file to work with if you don't have available here's one recommendation you could use YouTube's audio library and then search for sound effects or some music these audio files are only allowed for non-commercial use outside of YouTube so you can search for a song or some sound effects find one that you like and download it once you find a song that you like move it to your project folder now I will create a variable of sound file equals this will be a relative or absolute file path my MP3 file is right next to my main python file I only need to list the file name I named mine my music and this is an MP3 file I'm going to perform a test run we're not going to play our sound quite yet we do have this output that displays that says hello from the pame community let's say I set my alarm to 9:00 a.m. then enter alarm set for 9:00 a.m. if you would like to suppress this output for pame we can navigate to our virtual environment go to library pame underneath this file named Dunder init let's scroll all the way to the bottom and we should have this if statement we display the version of P game we're using and a print statement of hello from the pame community we could comment this out or even just delete it that is the most simple solution so we shouldn't get that message anymore we're going to create a Boolean variable of is running is our alarm clock running I will set that to be true while is running while this is true we will continue the alarm clock we need to get the current time current time equals we will access the date time module access the class of date time call the now method to get the time and date right now we could method chain the string format method stf time I would like the hours minutes and seconds but not the date so we will type percent H colon let me zoom out a little little percent M for minutes and percent s for seconds we're getting the hours minutes and seconds of the date and time right now and storing it within this variable of current time then I'm going to print the current time we'll perform a test run however currently we're within an infinite loop at the end of the while loop all set is running to be false okay Enter the alarm time let's say 10:00 a.m. alarm set for 10:00 a.m. and the time for me right now is 9:42 and 16 seconds we'll get rid of this line where we set is running to be false instead I'm going to access the time module and call the Sleep Method we will pass in a number of seconds to sleep so 1 second I'll set set the alarm to be 10: a.m. now the time should update every second which it is however when the current time is equal to the alarm time we have to trigger the alarm so after printing the current time we will write an if statement to check if the current time is equal to the alarm time if this is true that let's print the following wake up and I'll add an emoji cuz it's silly once our alarm triggers we will set is running to be false within the if statement let's do a test run we're not going to play the sound quite yet I will set the alarm to 9:45 and then I'll come back a little bit later all right once the current time matches the alarm time we print wake up and set is running to be false to exit the while loop and then subsequently exiting the program now we need to play an MP3 file we will access our package of pame access the module of mixer so mix is a module for loading and playing sounds but we have to initialize it but we're going to initialize it with init to initialize the initialize method is another way to call the Constructor we can pass in some keyword arguments for the frequency size channels buffer all that but that might be a little too complicated for us at this level we'll use the default settings by not passing in anything the next step is to load our sound file access the package of pame access the module of mixer access the module of music then call the load method we will load our sound file our sound file contains the file path to our MP3 file once we load our music we have to play it py game. mixer. music called the play Method our MP3 file is only going to play for a brief second I'll demonstrate that I will set the alarm to 949 and just give it a few seconds our sound file stops playing when the program terminates what we need to do next is continue playing our sound file while that sound file is BU busy we will add a while loop while access pygame do mixer. music call the get busy method this returns a Boolean if our song is busy if it's still playing then we will call the time modules Sleep Method and sleep for 1 second once the song finishes or we terminate the program prematurely the sound file will no longer be busy so this should be the finished product let's test it I will set the alarm for 952 and we just have to give it some time [Music] so uh yeah I'm going to talk about multi-threading in Python today multi-threading is used to perform multiple tasks concurrently think of it like we're multitasking we're performing a few different actions at once for example I could study and listen to music and eat something at the same time multi-threading is good for Io bound tasks IO meaning input output such as reading files or fetching data from an API things that may take some time to do and we don't know when it's going to end exactly to use multi-threading we'll import the threading module import threading we access the threading module then call the thread Constructor and pass in a Target function what we'll do for this demonstration let's say we have a bunch of chores to do we have to walk the dog get the mail and take out the trash let's define some functions to handle that we have a function to walk the dog then I will print the following message you finish walking the dog let's create a function to take out trash then we will print you take out the trash then another function of get mail as in get the mail from the mailbox then I will print you get the mail just to simulate these functions taking an indeterminate amount of time I'm going to import the time module to help us let's say walking the dog t takes 8 seconds I will access the time module call the Sleep Method and pass in 8 for 8 seconds when we call the walk dog function we'll wait around for 8 seconds then finish walking the dog this chore will take quite a bit of time to complete taking out the trash it's fairly quick taking out the trash will take 2 seconds getting the mill will take 4 seconds let's call these functions and see what happens we will Begin by walking the dog I will call the walk dog function followed by take out trash function and the get mail function here's the result we're going to wait around for 8 seconds until the walk dog function is complete right about now you finish walking the dog you take out the trash and you get the mail these functions are running on the same thread the main thread our main Python program we have to complete these chores in order one by one because they're all running on the same thread instead of walking the dog and then when we're done taking out the trash and then when that's done we get the mail we could accomplish all three tasks at the same time let's say we have a thread object we could say thread one or to be more descriptive let's say we have chore one let me zoom in a little bit chore one is going to contain a thread we will access the threading module call The Constructor for a thread we have to pass in a keyword argument of Target what is the first chore that we have to do let's walk the dog to start this thread we will take our thread object of chore one and call the start method to start it okay let's do this with chore 2 access the threading module call the thread Constructor pass in a Target then the name of a function take out trash chore two do start and then we have chore three I'll just copy what we have because I'm feeling lazy chore three will be get mail here's the result now we finish taking out the trash first then we get the mail then we finish walking the dog so we're executing these functions concurrently we're multitasking were taking out the trash and getting the mail and walking the dog all at the same time one thing that I did want to point out notice how we finished taking out the trash first followed by getting the mail then walking the dog these tasks finished in a different order compared to when we weren't multi-threading that's because taking out the trash finished first it took 2 seconds getting the male took 4 seconds and walking the dog took the longest it took 8 Seconds previously we finished walking the dog first then took out the trash then got the mail when all the chores are complete I would like to print a message I will print the following all chores are complete here's what happens currently we get this message that all chores are complete but we haven't finished any yet we're still completing them there may be at times you want your program to wait for all threads to finish before we print that confirmation message that all chores are complete we're going to use the join method take each thread use the join method we'll do this with chore 2 and chore 3 as well with the join method we will wait for these threads to finish before continuing with the rest of the program here's the result now you take out the trash you get the mail and you finish walking the dog all chores are complete when constructing a thread object and we have a keyword argument of Target if some of these functions take parameters for example with the function of walk dog let's say we have a first name I will convert this print statement to an FST string we will display first for the first name you finish walking whatever your dog's name is so when we're creating a thread and the target is that function and that function accepts arguments we need one more keyword argument and that is args we will send this function a tuple we need a set of parentheses within this tupple we will list our arguments let's say that our dog's first name is Scooby now since this is a topple if we only have one argument we have to end that tupple with a comma to let python know that this is a tupple here's the result you take out the trash you get the mail you finish walking Scooby all chores are complete if we were missing this comma this is what would happen we're no longer passing in a tuple what if what if we have multiple parameters we have first for first name and last for last name you finish walking first and last we have first name of Scooby last name of do you take out the trash you get the mail you finish walking Scooby-Doo all chores are complete all right everybody so that is multi-threading it's used to perform multiple tasks concurrently as if we're multitasking we're executing multiple functions at the same time multi-threading is good for Io bound tasks such as reading files or fetching data from apis and well everybody that is an introduction to multi-threading in Python hey everybody in this video I'm going to show you how we can connect to an API using python in this demonstration we're going to connect to the poke API to get some information on a Pokémon of our choosing I'm assuming that most of us are familiar with Pokémon I thought it'd be a fun example so according to this API we can look up a Pokémon such as Pikachu then we can get the stats for Pikachu such as Pikachu's name height ID number and all sorts of moves and abilities that a Pikachu may have we will need this URL but we'll handle that later our first step is that we're going to import the requests library to make an API request however when I run this I have a module not found error no module named requests requests is one package we'll have to install it's not normally included with the standard python download if I was to go to my project folder go to my virtual environment library site packages there is no package for request ests we'll have to download that with py charm and vs code there is a built-in terminal that we can use to download the request package we can use pip pip is a package manager for python it's normally included when you install python we'll type pip install requests it'll take just a second and now we have that package of requests within our project folder if I run this again that error goes away process finished with exit Code Zero that means there were no errors going back to our Pokemon API we will need this URL let me zoom in so you can see it I'm going to store that as a base URL so it's easier to work with for convenience I'm going to create a function name get Pokemon info to get some info on a Pokemon we'll have to pass in the name of a Pokemon for now I'll write pass outside of this function let's say we have a variable of Pokemon name pick a Pokemon I will pick Pikachu for now then I will call the get Pokemon info function then pass in my Pokémon name remember that your parameters can be named different than your arguments when you send data to a function you can rename it to something else temporarily now that we have the name of the Pokémon we would like to look up we can complete the URL this will be an F string so with our Pokemon API we have the base URL followed by the word Pokemon then the name of a Pokémon so we have the base URL I'll add a placeholder and insert itward slash the word Pokémon slash the name of that Pokémon in this example it's going to be Pikachu we now have the full URL we'll access the request module use the get method and pass in that URL this method is going to return a response object which I will assign to response response is a response object and I'm just going to print our response just to see what we're working with here's our response object it has a status code this is an HTTP status code of 200 200 means the response was okay here's a few examples of response codes you're probably familiar with 404 not found so we are looking for 200 the response is okay after we to get our response I'll add an if statement if our response our response object does have an attribute of status code to read what the status code is if this status code is equal to 200 that means the response is okay but for now I'll write pass else I'm going to print the following else I'm going to print failed to retrieve data and I will print the status code of the response object so temporarily I will print data retrieved if it was successful I can't spell okay we have our data data was retrieved if our status code of our response object is equal to 200 I will take our response object and use the Json method our response is a Json format using this method we'll convert it to a python dictionary it will consist of key value pairs much like a Json file but I'm going to assign that to a variable of Pokemon data so it's easier to work with then I will print our Pokemon data so here's the data on Pikachu it's really difficult to read all this you can see some keywords we have abilities base experience this is an extremely large dictionary once we have our dictionary I will return that dictionary of Pokemon data back to the place where we call this function and I will store that as a variable Pokemon info equals get Pokemon info pass in a Pokémon's name and now we should have a dictionary that we can work with let me zoom out if our dictionary exists we can use the if keyword if Pokemon info if that's true if it exists this will be true I will print the following I'll use an F string to access the value of addiction iary we can access it by a key we'll take our dictionary of Pokémon info access the key of name let's see what happens exactly we get Pikachu let's get Pikachu's ID number we will access the key of ID the given value is 25 Pikachu is the 25th Pokémon in the franchise let's get at Pikachu's height Pikachu's height is four I don't know what unit of measurement they use in that franchise 4 feet or 4 in I don't know let's get Pikachu's weight Pikachu's weight is 60 60 lb 60 kg I don't know just to make this look nice I'm going to add Name ID height and weight that looks much better let's pick a different Pokemon I will pick my favorite Pokemon of tyion failed to retrieve data does that have to be a lowercase T yes it does okay so name tyan I'll follow the name with the capitalize method to make it capital there we go so my favorite Pokemon is tyan ID is 157 Ty loan's height is 17 and weight is 795 all right everybody that is one way in which we can connect to an API using python also tell me what your favorite Pokémon is in the comment section down below all right everybody in today's video we're going to get started working with with the pi qd5 graphical user interface also known as a guy GUI in this topic we'll be creating a basic window so let's get started all right the first step is that using pip we're going to install the pi qt5 package open up a terminal both pycharm and vs code have a built-in terminal that you can use we're going to use pip that is Python's package manager pip install Pi qt5 enter and this might just take a second once your download has finished you should have a package within your site packages folder named Pi qt5 we can work with it as long as we import it first we are going to import the module of CIS CIS meaning system this module provides access to variables used and maintained by the python interpreter then from the package of Pi qt5 do pay attention to the capitalization it's easy to mess that up use dot to access the module of QT widgets widgets are the building blocks of a pi qt5 application they begin with Q that helps distinguish them from widgets from other libraries they typically begin with Q from this module import the following widgets Q application and Q main window here's some boiler plate code that we have to write in order to get this application up and running first we will create a class of main window which will inherit from the class of qain window by inheriting from the parent of Cain window we can customize our own Windows to display to the user we will need a Constructor let's define that Define Dunder init there will be no arguments currently besides self and in case we have to pass any arguments to the parent of Cain window we will access the super class that's the parent and call the parents Constructor but currently we don't have any arguments to pass in we will return to this class momentarily let's define a function of main When We Begin this program we will call the function of main to begin the application for now I'll WR pass if we are running this file directly let's add the following if statement if Dunder name is equal to a string of Dunder main if we are running this file directly call the main function in order for us to begin if that's true we will call the function of main within the main function we will create an app object app equals we will call the Constructor for Q application that class but there one argument that we have to pass in we will access our module of CIS do argv meaning arguments so by passing in this argument this allows Pi QT to process any command line arguments intended for it that's if we use command prompt or terminal we won't be doing that in this series but you may someday in the future it would be a good idea for us to Future proof our code otherwise you may see people pass in an empty list so we now have an app object next we will create a window object window equals call The Constructor for our class of main window currently we don't have any arguments to pass in we have an app object and a window object by calling their respective Constructors now if I run this program currently our window is not going to show the default behavior for a window is to hide it in order to show our window we will access our window call the show method to show it it's only going to appear for a brief second when I run the script I don't know if you saw it but it pops up for a brief second we need to ensure that the window stays until we interact with it or close it after we show our window we will access our module of CIS call the exit method the exit method ensures a clean exit of our program within our exit method we will pass in as an argument our app object our app object has a built-in method of EX ecore and this is a method so we can call it this is the execute method there isn't underscore character after exec for execute that distinguishes it from the execute method there is a separate version of this execute function that ends with an underscore our apps execute method it waits around for user input and handles events such as if we click buttons press keys or close the window now that we're calling this method when we run our program this window should stay in place we can maximize it minimize it or close it that's all the boiler plate code that we need for a basic window let's customize it within our Constructor for our main window what would we like to add let's set the title for our window self. set window title method we will pass in a string think of a title for your program my cool first GUI gooey and now we have a new title my cool first gooey graphical user interface when this window appears we can set the geometry of where the window appears and the size of the window access self do set geometry method there's four arguments X and Y for the X and Y coordinates a width of the window and a height of the window if I were to set X and Y to be both zero this window will appear in the top left corner of my screen I'll also need a width and a height let's say I don't know 5 00 for each so now my window is now a square the width and the height are both the same they're both 500 the width is 500 pixels the height is 500 pixels with the first two arguments we set the initial placement of our window to be where X is z and y is zero that corresponds to the top left corner if I set the first argument to be 100 well then the window is going to move to the right by 100 pixels there are ways to Center your window in the very center of your screen but that's a little too advanced for us right now for the time being I'll pick something roughly near the middle of my screen 700 pixels on the x axis and 300 on the Y AIS it should appear roughly in the middle but feel free to adjust these values based on the size of your screen we'll discuss layouts in the future now if you would like a window icon we can change that you will need a image to work with So within my project folder I have a profile picture for my YouTube channel I'll set that to be the icon find an image that you like then add it to your project folder in order to work with icons we'll need to make the following import from PI qt5 that's the package access the module of QT GUI import the following Q icon now we can work with icons after we set the geometry for our window access this object of self this main window call the method of set window icon within this method we will call the Constructor of Q icon we'll pass in either a relative file path or an absolute file path my main python file is right next to my profile picture that image I only need the file name within a string so the name of my image it's going to be different for you depending on what the name of your image is my image is named profile uncore pick and this image is a JPEG jpg then when I run this program I'm using my image as an icon for this window all right everybody that is how to create a window using pi qt5 and in the next topic we will be creating some labels what's up everybody in today's topic we're going to create some labels using pi qt5 we will import the widget of Q label this label class is used to create label widgets that can display text or images within the Constructor of our main window this is where we'll create a label we will declare a label object lab equals call The Constructor for Q label for the text of the label we'll pass in a string that's the first argument let's say the word hello for the second argument we will pass in self self refers to this window object that we're calling and instantiating all right let's do a test run here is my label although you can barely see it the font is really small but it does say hello let's set the font we'll need another import from PI qt5 do QT GUI import Q font by importing the Q font class we can begin working with fonts we're going to take our label call the set font method within this method we will call the Constructor of Q font pick a font that you would like I will pick aial but feel free to choose really any font then the second argument is a font size I'll pick 30 let's do another test run that's much better let's increase this to 40 for the font size now I'm going to set the geometry of this label such as the positioning and the width and the height let's take our label use the set geometry method we will pass in X and Y coordinates 0 0 corresponds to the top left corner for the width let's set the width to be 500 and the height to be 100 that's better I'll cover more advanced alignments momentarily let's add a style sheet sheet pqt does have styles that are very similar to CSS if you would like to learn more about CSS I do have a full course on that topic we will add some CSS like Properties by accessing our label object call the method of set style sheet within this method we will pass in some CSS like properties such as a color for the color let's say blue these CSS like properties should end with a semicolon and now the font color is blue you could also use RGB values or heximal values you could always look up a Color Picker and pick a very specific color let's pick something green we can either use RGB values or heximal values so I will copy this value so I will paste that heximal value and now we have a very specific shade of green but I think I'll go with something dark such as that so this color is going to be a dark gray color we could set a background color this will be a new string background Das color and I will pick a new color I will pick something blue that's a decent color we have a blue background with dark gray text we can set the font to be bold font weight will be bold so the font is now bold the font style can be italic font style italic so our font is italic and we can underline text decoration underline the text on our label is now underlined let's work on positioning next currently my text is left Justified and to the center vertically to work with alignments we need this import from PI qt5 QT core import QT the class of QT is used for alignments to Center the text of our label at the top vertically we will take our label use the set alignment method then pass in a flag access the class of qot access the flag of a line top this will align our text vertically to the top so then our text is aligned vertically to the top rather than the center for the bottom we will use the flag of a line bottom we will align vertically on the bottom the text is now on the bottom to align vertically in the center align V Center this will be vertically Center which it was originally now for horizontal alignment we can add the following okay to align right we will pass in a flag of align right horizontally align right the text is now all the way to the right for the center a line H H for horizontal Center the text is now horizontally aligned in the center center for the left Aline left the text will be aligned to the left we could combine both horizontal and vertical positioning here's how take our label call the set alignment method we will align horizontally in the center follow this with the or bitwise operator which is a vertical bar this allows us to combine Flags we will align horizontally in the center then vertically let's align to the top so our text should be aligned horizontally we're aligned in the center and vertically we're aligned to the top align bottom vertically horizontally we are in the center vertically we're aligned on the bottom then for the very center of our label a line horizontal Center and a line vertical Center our text will now be in the very middle of our label both horizontally and vertically now there is a shortcut for the very center we don't need both of these flags the shortcut is the following set alignment align Center that will align the text both horizontally and vertically so that is Center and Center all right everybody so that is an introduction to labels in pi qt5 what is going on everybody in today's video I'm going to show you how we can add images to Pi qt5 you will need an image to work with me I'll be using my profile picture for my YouTube channel feel free to take a moment to find a picture of your own maybe a profile picture of yourself we will need the following Imports Q label the most common and straightforward approach to displaying an image is to add an image to a label in order to display it then we will need this other import from PI qt5 that's the package then the module of QT GUI import the class of qix map the class of qix map it's used for handling images and provides functionality for loading manipulating and displaying images we will load our image to a q piix map object then add this Q pix map object to a label in order to display it within our Constructor of our main window we will create a label label equals call the Q label Constructor then pass in self self refers to the window object our window will be the parent widget our label widget is one of its children once we have our label we'll set the geometry of the label label. set geometry method we have to pass in X and Y coordinates and as well as a width and height of the label for the coordinates let's say zero for each the label will appear in the top left corner for the width 250 is good and the height 250 as well here's my window the label is going to appear in the top left corner however there's nothing added to the label that's where the widget of Q pix map comes in we will create a PIX map object equals call the Constructor of Q pix map we have to pass in a string that represents a relative file path or an absolute file path to our image my image is right next to my main python file I just need the file name the name of my image is profile uncore pick and this is a JPEG when I run this we don't see our image we have to add the Pix map object to the label we have to set it here's how take take our label use the set pixmap method and pass in our pixmap object and now we can see the image however the image doesn't scale according to the size of the label to enable that we have to call the following method take our label call the set scaled contents method then pass in true our image will now scale to the size of the label if we were to change the size of the label let's say it's 100 pixels it will scale down even further or I could even increase it to 500 so now the image takes up the entire width and height of the window let's set that back to 250 there's a few tricks that we can do with positioning of the image we've set our label with an image we can move the label within the confines of the window currently it's set in the top left corner but here's a few tricks that we can do with positioning with our label we will set the geometry again so the top left corner is 0 0 for the coordinates we could pass in 250 and 250 again for the width and the height but if we were to change that here when we initially create this label we would have to manually change that here as well I think it would be better if we were to get the current width and height of the label take our label call the width method to get the width same thing applies with the height label. height method that should work fine let's say we would like to take our image and move it to the right side of our window here's how with the x coordinate we're going to access self that means our window called the width method here's what we have currently we can't see the label it was placed outside of the confines of the window let's subtract our labels with label. width I'll put each of these arguments on a new line just to help with readability so now our image is Right Justified within our window for the bottom right corner we will take the second argument access self. height that's the height of the window that we're instantiating minus our label's height and now our image is in the bottom right corner for the bottom left corner we will set X to be zero now here's the tricky part to have our image placed in the center center of our window we will take the width of the window minus the width of the label / by two for integer division we'll be using double forward slashes we need our pixels to be whole integers so we're going to be using integer Division and not standard division we will round to the nearest whole pixel then we will do this with the height as well and now our image should be in the middle of our window all right everybody and that is how to add an image to your Pi qt5 application well hello again friends today I got to explain layouts in pqt 5 we'll discuss vertical horizontal and grid layouts but we'll need the following Imports we will be importing Q label Q widget I'm going to put these Imports on a new line just because we have a lot QV for vertical box layout and I'm just going to copy this qh for horizontal box layout and Q grid layout let's be sure that we have all these Imports these classes deal with layout managers they aren't widgets we'll be writing a majority of the code within our main window class however it can get disorganized really quick what will help keep things organized is if we declare a separate function within the main window class this is a common practice that you'll see within Pi qt5 there will be a function for innit for initialize UI for user interface no other arguments besides self and for now I'll write pass when we construct a window object we will call Self do init UI to initialize the user interface so anything that deals with the user interface we're going to be writing within this function to help keep our code clean and organized normally we can't add a layout manager to a main window object main window widgets have a specific design and layout structure that's normally incompatible with layout managers what we would need to do is create a generic widget add a layout manager to that widget then add that widget to the main window in order to display the layout within our method to initialize our user interface we are going to create what is called a central widget called The Constructor for Q widget this is a generic widget then we will take self self is our window call the set Central widget method then pass in our Central widget when working with layout managers we will add that layout manager to the central Widget the central widget is then added to the main window so currently this is what we're working with we will need some widgets to organize because right now it's empty let's create a few labels let's say label one equals Q label I'll pass in some text number one okay let's create four additional labels 1 through five I'll just do some copying and pasting all of our labels are overlapping let's add some colors let's take label one use the set stylesheet method then pass in a background color as a CSS property background-color will be red let copy this line of code paste it four additional times for labels 1 through 5 we'll have a label that is yellow another that is green blue then purple here are the labels they're all overlapping one another that's why we can only see five this is where a layout manager comes in we'll start with the vertical layout we will create a vertical layout manager which we will name vbx vbox equals call The Constructor for QV box layout we are calling the Constructor we will take our layout manager call the add widget method then pass in a widget such as label one near the top here we'll do this with the other labels we'll do some copying and pasting add label two 3 four and five there's one last step we will take our Central widget which we have declared at the top of this function call the set layout method we are setting the layout of our Central widget with the layout manager a vbx vertical box here's the new layout all of our labels all of our widgets are arranged vertically for horizontal we will use qh box layout for horizontal replace any instance of vbx with hbox for the set layout method pass in hbox this allows for a horizontal layout then we have grid Q grid layout replace hbox with grid so what we have to do with grids after adding a widget we have to specify a row and column with separate arguments the row and column both begin with zero so Row one column 1 would be row0 column 0 for label two let's say row 0 column 1 Label 3 will be Row 1 column 0 four will be Row one column 1 then five row one column 2 so here's the current layout we have labels 1 and two both within row zero labels 3 four and 5 are both within the second row let's say label five is Row 2 column 2 that would result with something like this we have label five which is purple in row two column 2 so it depends on how you want to arrange your widgets all right everybody so that is an introduction to layout managers in pi qt5 today I'm going to show you how we can create push button widgets in pi qt5 to begin we will need the following Imports Q push button as well as Q label for this demonstration during the previous topic on layout managers within our Constructor for our main window we defined a method of initialize UI for user interface let's be sure that we're calling that method within our Constructor within this method is where we'll be handling managing the user interface to create a button we will call the push button Constructor normally when creating widgets we would want to prefix that widget with self then follow the name of the widget for example button however I'm going to demonstrate what happens when we don't do that because without self we're declaring a local variable we'll get back to that in just a moment let's create a local button object by calling the Q push button Constructor we can pass in some text such as click me we will add this to our window self self refers to our window object let's set the geometry of the button button. set geometry we could use a layout manager but I do want to keep this lesson as simple as possible so let's pick some coordinates I've picked the following for the X and Y coordinates 150 and 200 for the width 200 and the height 100 here is our button currently the font is a little small so I'm going to set the stylesheet set style sheet I'll just increase the font size we could could use Q font but that might be overkill for this demonstration let's just say the font size will be 30 pixels now we can read it so we have our button we're going to be connecting our button to a function but we need to Define that function we'll do so within our main window class so we will Define a function of on click there are no parameters besid self when we click on the button but what would we like to do let's print a test message let's say button clicked and that's it when we click this button nothing happens we have to set up a signal and slot for the button here's how we will take our button dot list a signal a signal is emitted when a widget is interacted with we have to list the type of signal so the signal we're looking for is clicked when we click this button we will perform a slot an action we will take the signal of clicked connect it to a slot connect is a method the slot will be self dot the name of the method on click when we press this button we perform this slot this method of onclick each time I press the button we perform that action not only should we print a message for this demonstration let's set the text of the button so we have button. set text let's change the text to clicked so this actually isn't going to work because we're not prefixing self let me demonstrate what happens we print button clicked but then we have a problem we have an exit code our program was interrupted button is considered local to our initializer method our onclick function doesn't recognize what our button is that's why we're going to prefix our button with self so it belongs to the class of main window and not this method any instance of button we're going to prefix with self and now this should work the text on my button is going to change when I click it clicked you don't have to do this but with my personal coding style whenever I create a variable or an object within a class I like to do so within the Constructor even py charm is giving me a warning when we declare this button I'm going to move it to the Constructor and let me just rearrange everything self. button equals a q push button widget within my initializer method that's when I like to rearrange everything and style it we can also disable buttons when we click on them to do that we will take self. button call the set disabled method then pass and true when I click the button it will be disabled I can no longer click on it for the last part of this demonstration when we click on our button let's change the text of a label let's declare self. label within our Constructor equals a q label the text of the label will be hello we will add this label to self the window when we set up the user interface let's set the geometry of the label self. label do set geometry we could use a layout manager but just to keep things simple I'm going to set some coordinates 150 for X 300 for y the width will be 200 and the height 100 let's change the font size self. label do set style sheet I will set the font size to be 30 maybe 50 better all right within our onclick function let's instead take self. label. set text method then pass in some new text to display we're saying hello but when we click the button let's say goodbye so now when I click the button we will change the text on a separate widget my label which now says goodbye so with buttons you need a signal that's connected to a slot the signal is an event the slot is an action that this widget is going to take when the signal occurs and well everybody that is an introduction to push buttons in pi qt5 hey uh so today I got to explain checkboxes in pqt 5 to work with checkboxes we will need the following import from the module of widgets from PI qt5 import Q check box to work with different states we will also need the following import from PI qt5 do QT core import QT this module of QT core it contains non- classes relevant to Pi qt5 applications so be sure that you get the this import as well to create a checkbox I will create this within the Constructor of my main window we will create a checkbox with self the name of the checkbox which I will name checkbox equals call The Constructor of the Q checkbox class the first argument is going to be the text of the checkbox what do you want the checkbox to say let's ask do you like food the second argument is the parent widget where we will be adding this checkbox let's say self self will apply to this window we could use a layout manager but I want to keep this lesson as simple as possible we're just going to focus on checkboxes and their functionality so we should have a checkbox however we can barely see it the font is really small I have a method to initialize the user interface that's where we'll set the stylesheet and the g ometry of our checkbox let's set the stylesheet self do the name of the checkbox checkbox do set Styles sheet method then we can pass in some CSS like properties let's set the font size to be 30 pixels and I will pick a font family font family aial oh and we should change the geometry of the label it's getting cut off self do the name of the checkbox which is checkbox let's set the geometry pass in some X and Y coordinates for the placement as well as a width and a height I will pick 500 and 100 uh maybe I'll move it a little more to the right by 10 pixels that's pretty good our checkbox has an initial State it's normally unchecked that's the default Behavior but we could set that to be checked with the following method when the window loads let's take our checkbox self. checkbox call the set checked method then pass in true so then when the window loads the checkbox is already checked but let's keep that is false now this checkbox it doesn't do anything when I check it let's add some functionality we'll take our checkbox connect a signal to a slot the slot can be a function or a method let's define a method within our main window class let's name this method checkbox changed we will call this method when the state of our checkbox changed changes there is one parameter besides self a state now the state parameter is going to be provided to us when we interact with our checkbox when we check the checkbox let's print something like a test message you like food we have to connect a signal of State changed to a slot of checkbox changed we will take self dot the name of the checkbox which is checkbox the signal will be State changed to connect a slot to a signal we use the connect method then pass in a function or method name so we are working with methods this method belongs to the window class we'll prefix the method name with self self. checkbox changed so when I run this program when I check the checkbox we execute this method you like food now when I uncheck it I instead would like to display you do not like food so that's where our state is going to come in I'm going to print our state just to see what it is our state is going to be a value when we check the checkbox our state has a value of two when we uncheck it it has a value of zero 0 zero means unchecked two means checked there's also one for partially checked but that's not going to be relevant to this topic so zero or two we could add an if statement such as if state is equal to two then print you like food however that's not really readable other developers looking over your code aren't going to understand what two is by looking at it instead let's use the following we will access the class of QT there's a built-in constant of checked this also equals two but it's more readable it's a constant so if state is equal to QT checked print you like food I will check the checkbox you like food when I uncheck it nothing happens let's add an else statement else let's print you do not not like food so then when I check the checkbox we print you like food when I uncheck it we print you do not like food you like food you do not like food you like food you do not like food all right everybody so that is an introduction to checkboxes in pi qt5 all right let's do this thing today I got to talk about radio buttons in pi qt5 to work with radio buttons we will need the following imports from the module of QT widgets we will need the class of Q radio button as well as Q button group to group together different buttons let's create three radio buttons within the Constructor of my main window we will construct three radio buttons for the first radio button this will be named radio one we will call the Constructor of the class Q radio button then we can pass in some text what is the radio button going to say let's say that we're working with payment options let's say visa for the first option then for the second argument I will pass in we will add this radio button directly to our window that would be self let's create two more additional radio buttons Radio 2 and radio 3 the text of radio button two will be MasterCard and three will be a gift card we are selecting different payment options we need to set the geometry of these radio buttons because we're not using a layout manager I have a method to initialize my user interface this is where I will set the geometry of my radio buttons so let's say self. radio1 we will call the set geometry method pass in some coordinates 0 0 is good that applies to the top left corner of my window for the width 300 and the height 50 is good let's do this with radio buttons 2 and three Radio 2 radio 3 we'll just move each radio button down on the Y AIS by 50 pixels each so 50 then 100 here are the three radio buttons however the font is kind of small we can barely see it so let's apply a stylesheet here's a trick that we can do with stylesheets we can apply multiple CSS like properties to an entire group of widgets rather than having to type them and apply them individually we will select our window of self set the style sheet of our window with the set style sheet method we will add a selector the selector is going to be the name of the widget Q radio button in this case then add a set of curly braces we can apply CSS like properties to an entire group of widgets this way so let's set the font size of all radio buttons to be 40 pixels better let's set the font family to be aial then I will add a little bit of padding around each radio button padding 10 pixels that's pretty good so with radio buttons we can only select one from any one radio button group if I was making a payment I can't pay with a Visa and Mastercard at the same time I can only select one option that's the point of radio buttons we're limited to just one option with the default behavior of Pi qt5 all radio buttons unless explicitly stated are all part of the same group to demonstrate that let's create two additional radio buttons Radio 4 and Radio 5 radio button 4 will be for a payment method rather than a payment type for example we could say we're paying in store radio button 5 will be we're paying online radio buttons 1 through 3 will be for the payment type radio buttons four and five will be for the payment method we're either paying in store or we're ordering something online we do need to set the geometry for these two radio buttons I'll just copy these two lines add Radio 4 Radio 5 we'll set the y-coordinate of four to be 150 and 5 to be 200 all radio buttons will be within the same button group if I was to select in store we deselect one of these options what I would like is one option from this first group and another option from this other group these buttons are all in the same group group I can only select one if I would like to pay with the VISA in store and I click the in store radio button we unselect the radio button for Visa I would like these radio buttons within different groups we need to create two different groups and add them accordingly here's how within our Constructor we will access self declare a button group let's name it button group one for Simplicity equals call The Constructor of the class Q button group then pass in to set the parent widget to be the window then we will create button group two we're going to access self select the radio button group button group one call the add button method then pass in a radio button self. Radio 1 then we'll add Radio 2 and radio 3 we'll select button group two this time button group two add radio button 4 and radio button 5 the first three radio buttons are within the same group radio buttons 4 and five are within a different group we can only select one radio button from any one radio button group maybe I would like to pay with a Visa card in store or a master card online or a gift card in store these radio buttons are within different button groups we're limited to one selection in any one radio button group when we select these radio buttons they don't quite do anything for each radio button we have to connect a signal to a slot here's how let's define a method of radio button changed there will be no parameters beside self temporarily I'll write pass we'll fill this in in a moment we will take each radio button let's start with radio one Radio One the signal will be toggled when this radio button is toggled we will connect a slot we will pass in a function or a method self dot radio button changed then we will do this with the other radio buttons one through five let's print a test message you selected something just to be sure that everything is working you selected something okay we know that that works currently what we're going to need to do is get the sender widget which radio button sent the signal of toggled I will create a local radio button to store that radio button whichever one emitted the signal we can determine that with self. sender method the sender method is going to return the widget that sent the signal so if we select radio button one our radio button will be radio button one if it was five then it's five in this case then we'll determine if our radio button is checked take our radio button use the is checked method this will return a Boolean true or false if it's checked if this returns true then let's print the following I'll use an F string we will get the text of the radio button radio button called the text method to return the text of the radio button is selected all right then let's see if this works let's select Visa Visa is selected MasterCard is selected gift card is selected in store is selected and online is selected that's how to determine which radio button was selected which one is the sender which one sent the signal all right everybody so that is an introduction to radio buttons in pyqt5 why hello everybody today I got to explain line edit widgets in pyqt5 also known as textboxes in pretty much anything ever made ever why are they called line edit widgets I really don't know let's begin from the module of QT widgets we will import the following class of q line edit to create a text box I I mean a line edit widget we are accessing our window of self we will call this line edit widget line edit equals call The Constructor of the class q line edit then we will pass in self to add this line edit widget to the window let's set the geometry but we do have a text box in which we can type in stuff I have a method to initialize the user interface within this method I will access self dot the line edit widget and set the geometry let's set it in the top left corner where X is 10 Y is 10 set a width 200 is good and a height 40 that's not too bad now the text is really small we can change that by applying a stylesheet access our window with self access our line edit widget then call the set stylesheet method we can pass in some CSS like properties including a font size let's pick 25 pixels and here's my new text box we can read the text now let's also change the font family font family I will pick aial this text box by itself it really doesn't do anything we need some way to get the text from the text box let's add a button when we click on the button we will get the text from the text box and do something with it cuz right now it doesn't do anything we will need to import Q push button let's create one button self. button equals call The Constructor of the class Q push button let's say that this is a submit button I will pass in a string of submit and we are adding this button to our window and we do need to set the geometry of the button we're not using a layout manager right now access our window with self access our button that we have previously created in our Constructor then call the set geometry method we'll place our button where X is 210 Y is 10 the width will be 100 and the height will be 40 not too bad let's change the font size of the button I'll copy these two lines of code because I'm lazy instead of selecting our line edit widget we will select our button that's better if I were to click on the button it doesn't do anything we'll set up the signal of clicked to connect to a method that will do something let's define a method of submit we're submitting something we're submitting the text within the text box and for now all right pass we'll get back to this in a second we're going to take our button self. button we'll connect the signal of clicked clicked. connect method we will connect the method of submit self. submit so when we click on the button we will call this method let's print a test message you clicked the button let's type in something press submit and we get our test message you clicked the button let's get the text from the text box then do something with it let's create a local variable of text text equals now we have to get the text from our line edit widget self. line edit that's the widget to get the text we can use the text method to return the text then let's print the text I'll use an F string we'll say hello add a placeholder then display the text so now after typing in something why don't you type in your name then press submit we will display hello your name you could add some placeholder text too let's do that here let's take self do line edit widget set placeholder text and let's say enter your name when I run this program we have some placeholder text that says enter your name this time I will type in SpongeBob then press submit hello SpongeBob all right everybody so those are line edit widgets also commonly referred to as text boxes and well everybody those are line edit widgets in pi qt5 hello everybody so in today's video I'm going to explain setting stylesheets in pyqt5 CSS means cascading stylesheets if you're not familiar with CSS you can still follow along but knowing CSS is helpful as a reminder I do have a full free course on YouTube on HTML and CSS if you would like to learn more let's begin for this demonstration we will need the following Imports we will be designing some buttons we will import Q push button we'll be working with the layout manager we will import Q widget and for a horizontal layout manager we will need Q hbox layout so import these three from the module of QT widgets now in previous topics we've set the geometry of our window since we're using a layout manager we don't necessarily need that anymore so I'm going to delete it in the past I have also created a method to initialize our user interface and we are calling that within the Constructor of our main window we will create three push button widgets self. button one will be the first button equals take our Q push button class and call the Constructor we can add text to the button we will pass that as an argument now since we're using a layout manager we don't need to add this button to self our window we don't need to do that let's create two more buttons we'll have button two and button three button two will say number two button three will say number three now we'll create a layout manager under normal circumstances we can't add a layout manager to our main window with main window widgets there's already a specified layout and format we're going to add a layout manager to a central widget and this widget will be added to the main window let's take care of that within our initialized user interface method we will create a central widget equals call The Constructor of Q widget then we will take self that means our window and set the central widget set Central widget then pass in our Central widget to set it then we will create a layout we will call The Constructor within the class of qbox layout let's name this layout hbox for a horizontal box equals call The Constructor within this class we will take our layout of horizontal box then add the following widgets add widget self. button one we'll do this with two and three then the last thing we need to do is take our Central widget call the set layout method then pass in our layout manager and now we should have those three buttons they're all arranged horizontally now we're going to apply some CSS like styling using the method of set style sheet here's how rather than apply the CSS properties individually such as self. button one do that stylesheet and in the past we've passed in individual CSS properties we're instead going to set the stylesheet of our window self we have a lot to write instead of double quotes we're going to use triple quotes triple quotes are used to write very long strings in a more organized way all of the CSS properties that we're going to write are going to be within this set of triple quotes so let me give you a demonstration we could individually apply CSS like properties to each of these widgets but we could select an entire class of widgets too let's select the class of Q push button then add a set of curly braces the following CSS properties will apply to all Q push button widgets So currently this is what we have we increase the font size for every push button so we will add the following property of font size then set it to be 40 pixels each be sure to end each CSS property with a semicolon so the font size is now 40 for every button let's set the font font family I will pick aial let's add some padding we can add some space around the text and the button itself so with padding if I was to set this to 75 pixels we would have 75 pixels worth the space between the text and the border of the button I would like to change the dimensions of the padding so let's apply 15 pixels to the top and bottom of the button and 75 to the sides that's better margin is the space around a button let's set the margin to be 25 pixels now the buttons are more spread out if this was 250 they would really be spread out that's margin it's the space around a widget let's set that back to 25 I'm going to change the border border 3 pixels solid this would change the border of the buttons we now have a black border that's three pixels and width if you would like to round the corners we can use border radius I will set that to be 15 pixels with all the buttons the corners are now rounded within our set style sheet method we're applying all of these CSS like properties to every push button now what if you would like to apply CSS properties to Only One widget rather than all of them here's how with each of our widgets buttons 1 two and three we need to set an object name let's do that before we call the set stylesheet method we will take our buttons self. button one call the set object name method then pass in a name for this widget we'll keep the name the same as button one so let's do this with button two and button three button two button three within the context of set stylesheet we will refer to these widgets by their object name buttons 1 2 and three and now we can select them individually let's say that with button one I would like the background color to be red we're going to access our class of Q push button follow this with a pound sign I like to call it a hashtag then we need the object name button one button one refers to the widget of button one again I kept the name the same then we need a set of curly braces between the set of curly braces we can list one or many different CSS properties let's change the background color I will set it to be red and now the background color of only that button is red and not all of them if I was to set the background color within the class well then all of them would be red okay so with button two I'll just copy what we have and paste it we are selecting the ID of button two let's set the background color to be green so then the background color is now green and button three button three will be blue if you would like a greater variety of colors I recommend looking up a color picker you can just Google Color Picker so if I would like a very specific shade of red I can pick that let's go with that there are a few options provided to you you can use hex values now we have a very specific shade of red you can use RGB RGB en close it with within a set of parentheses and then paste those numbers or my favorite which is hsl hsl means Hue saturation and lightness we will enclose our values within hsl if you copy these values directly from Google you would have to remove this degree symbol I like hsl because I can also control the saturation and the lightness pretty easily okay let's pick a very specific shade of green that's good I would say I'll use the hsl values hsl remove the degree symbol and now we have a very specific shade of green and blue that's good I would say that's not too bad if you're already familiar with CSS we can apply pseudo classes such as when we hover over one of the buttons here's how let's copy these three blocks then paste them again we can add CSS properties when we hover over something we have to use the hover PSE sudo class after the ID of each of our buttons we will add Cod in Hover we can apply the following CSS properties when we hover over the buttons all I'm going to do is up the lightness let's say by 20% each then when we hover over one of the buttons the lightness is going to change we apply the new CSS properties all right everybody so that is a more in-depth explanation of the set stylesheet method in pi qt5 all right everybody in today's video we're going to build a digital clock widget using Python's Pi qt5 library at the top of our python file we will need the following Imports import CIS CIS means system this module provides variables used and maintained by the python interpreter we would also need widgets widgets are the building blocks of a guy application from the package of Pi qt5 we need to access the module of QT widgets import the following Q application Q widget this is a generic widget we'll turn our digital clock into its own widget and Q label to work with labels we will be using a layout manager more specifically QV box layout there's another import we'll need too from the package of Pi qt5 access the module of QT core the QT core module it provides functionality not related to guy components this is where we'll get a timer to keep track of the time from this module we will import Q timer Q time and QT QT is for alignment we will create a class of digital clock instead of inheriting from the main window window widget we will inherit from The Base Class of Q widget Q widget is a base class to create our own widgets our digital clock will be a widget we will need a Constructor so let's define that Define init pass and self if there are any arguments to send to the parent we will call the Constructor of the parent the super class super called the init method at the end of The Constructor what I like to do is call a method of initialize UI init UI this will be a separate method Define init UI there are no parameters besid self and for now I'll write pass it's within this method that we will be designing the layout of the digital clock within the Constructor that's where we will be constructing all of the different entities for the clock at the end of my python file I will add the following statement if Thunder name is equal to a string of Dunder main this statement will be true if we are running this program directly to create an application we will create an F object equals call The Constructor within the class Q application as an argument to the Constructor we will pass in the following argument access the module of CIS a RGV which means arguments this would apply if we're running from command prompt or terminal but we won't be doing that in this video but it's nice just to set it up in case we do in the future now we are going to create a clock object clock equals we will call the Constructor of our digital clock class there are no arguments now the window doesn't appear That's because we have to use the show method of our clock take our clock call the show method now it's only going to appear for a brief second just momentarily I don't know if you saw that to ensure a clean and proper exit of our application we need to call the following method access our module of sis call the exit method then pass in the following we will take our app object then call the following method eccore and then a set of parentheses it's a method it's the execute method it starts the main event Loop of the application it also handles events such as key presses Mouse clicks or other user interactions so then we should have a window that stays in place until we exit okay now we have the base functionality all set up we have a class of digital clock that inherits from the Q widget based class we're not going to be using main window in this video within the Constructor of my digital clock I will create a label self. time label this will be a label that displays the time we will call the Constructor within the class Q label then be sure to pass in self we will be adding this label directly to our widget of clock we will need a timer self. timer equals call The Constructor of Q timer then pass in self we are adding the timer to the clock now with designing the layout of our clock I'll handle that within the initialized user interface method we're going to set a title for the window self. set window title method pass in a string that will be used for the title of the window let's say digital clock then our window should say digital clock let's set the geometry of the window self. set geometry the first two arguments are going to be for for the placement of the window where will it appear within your screen so I'll pick something approximately in the middle for me but feel free to change these values then we need a width for the window let's say 300 and a height 100 for the height so my window should appear approximately in the middle of my screen the base width is 300 the base height is 100 now we're going to need a layout manager I will name this layout manager vbox for a vertical box vbox equals call The Constructor within the class QV box this will arrange all of our widgets vertically but we only have one widget a Time label so we will take our layout manager of vbox add widget that's a method we will pass in self. time label as an argument we're adding our label to this layout manager of vbox then to set the layout we will take self that applies to our clock call the set layout method then pass in our layout manager of vbox So currently if I run this we don't see anything temporarily within our label I will add some text just as a placeholder so we can see what we're working with let's say 12 o' so then we should see something at least although the font is kind of small we will be getting rid of this later we just want to be sure that we can see everything all right so after our layout I would like the label to be Center aligned horizontally here's how we can set that up we will take our label self. time label call the set alignment method access the class of QT access align Center this should Center align our time now let's work on the font I can barely read it we will take our label self. time label set style sheet we can pass in multiple CSS like properties let's set the font size I'll set it to be 150 pixels now we can read it you could pick a font but we're going to change that at the end of this video we'll import a custom font but temporarily let's say font family aial you could change the color too so if I set the color to be green then the font color is going to be green but I would like a very specific shade of green you could always Google a Color Picker then pick a very specific color uh let's go with that something that's bright green you can copy the hex value RGB or hsl hsl means Hue saturation and lightness I'll use hsl values for the color we will type hsl add a set of parenthesis then paste those values but there is a degree symbol you do have to get rid of that now the font color is going to be bright green let's change the background color here's how we will take self that applies to our clock then call the set stylesheet method pass in a background color we will set the background color property to be black I think that looks pretty good but doesn't quite do anything quite yet that's the next step let's create a method to update time no arguments beside self I will create a local variable of current time equals now to get the current time we can access the class of Q time Q time do call the method of current time we will need to convert it to a string we will method chain the two string method within the two string method we will Design the layout of the time so I would like hours first I will type 2 H's colon minutes that's 2 M's colon 2 s's to set the text of the label we will take self. time Lael call the set text method then pass in our current time so if I run this currently we still have our placeholder time let's update it with the current time we can get rid of our placeholder text of 12 we can delete it after we set the font let's call the method of update time self. update time now we should display the current time so me I'm recording this video at 7:44 in the morning if you would like to add amm or p.m. after your time here's how after our string format specifiers we will add Capital AP a means anti- meridium and P means post meridium so then we should display AM or PM depending on when you're coding this currently the time for me is 7:45 a.m. to get the clock to update every second we need to connect our timer widget to a slot of update time we will take our timer self. timer this isn't the time label it's the timer to keep track of the time during a signal of time out we will connect the following slot of self. update time self. update time with our timer we need to trigger a timeout signal every 1,000 milliseconds every second that is to handle that we will take our timer self. timer call the start method then pass in 1,000 from 1,000 milliseconds so then when we run this program our clock should update every second and display the new current time as an added bonus if you would like to download a custom font here's how using Google or another search engine I would recommend looking up a font of you're choosing so one font that I like is DS digital what we need is a ttf file meaning true type font I'll just pick this first link so these fonts are pretty good so I'm going to download them I'll pick this specific font DS digit and again the file extension is ttf so once you have your font move it to your project folder so for convenience we have that ttf file right next to our main python file okay to work with specific fonts we will need the f following import from PI qt5 do QT GUI import Q font as well as Q font data base since we're going to use our own custom font we can delete that from the set stylesheet method of our time label so let's set the font right here we will assign a local variable a font ID equals Q font data base Q font database is a class for managing and querying fonts available to the application to add a custom font we will call the following method within it add application font within the set of quotes we're going to pass in a file path this can be a relative file path or an absolute file path this ttf file is right next to my main python file I only need the file name my font file is named DS digit and get the file extension of ttf we will create a local variable of font family we will retrieve the name of the font family from this ID again we will access qfont database do call the application font families method so this method returns a list of font names we will pass in our font ID but there's another step we're going to use the index of operator and get the index of zero this will retrieve the first element of the font family that's because we're working with a list we will need just the first element at index zero now we'll have a font family to work with now to set the font we will create a local variable of my font equals called the class call The Constructor within the class Q font pass in the following arguments our font family that's the first argument and then a font size let's say 150 to set the font we will take our time label self. time label called the set font method then pass in my font our custom font so then we should have our custom font that digital font that we've downloaded art everybody so that is how to create a digital clock widget using pi qt5 hey yeah everybody so in today's video we're going to create this stopwatch program using Python's pyqt5 Library once that's out of the way you will need the following Imports import CIS CIS means system it handles system variables for your python interpreter we will need the following widgets from PI qt5 access the module of QT widgets widgets are the building blocks of a pi qt5 application we will import the following widgets Q application Q widget Q label Q push button QV box layout and qh box layout let me put these on a new line just so we can read everything from the package of Pi qt5 access QT core we will import Q timer our timer will emit a signal after a given interval which is what we need for a stopwatch Q time to keep track of the time and QT for alignment let's do a test run to be sure that there's no errors looks like L and label should be Capital there we go no errors once you have the following Imports we will construct a Class A Class of stopwatch which will inherit from The Base Class of Q widget our stopwatch will be a widget we will need a Constructor we'll Define that Dunder init no arguments besid self if we have arguments to pass to the parent of Q widget we will call the super class the parent call The Constructor of the parent no arguments currently now if we are running this file directly we'll use an if statement to verify that if Dunder name is equal to a string of Dunder Main if this is true if we are running this file directly then we will construct a stopwatch we will create an app object call The Constructor within the Q application class pass in the following access CIS our system access AR RGV which means arguments this is if we're using command line arguments which we won't be using but it's nice to Future proof our code just in case we do in the future we will create a stopwatch object stopwatch equals call The Constructor within our class of stopwatch our window is not going to show unless we call the show method take our stopwatch call the show method now our window is only going to show for a brief second we need to ensure a clean exit we can access CIS call the exit method pass in the following app then call the excore method this method starts the main event Loop and handles events so then we should have a basic window which stays in place until we close it we now have the main skeletal structure of a pi qt5 application set up if you're one of the people that have jumped ahead up until this point we have a class of stopwatch which inherits from the Q widget class we've constructed a stopwatch object and we're showing it so now we can begin designing our stopwatch we will create a Time object self. time equals call The Constructor within the class of Q time for arguments we'll pass in the hours minutes seconds and milliseconds all zero we need a label for the stopwatch self. time label equals called The Constructor of Q label what would we like the text to say I'll display some placeholder text a bunch of zeros zero hours minutes seconds and milliseconds we will add this label to self our stopwatch we need a start button self. start button equals called The Constructor within Q push button what would we like the text of the button to say let's say start we are adding this button to self our stopwatch we need a stop button let's replace start with stop change the text from start to stop and reset the name of this button will be the reset button the text will be reset we will need a timer to emit a signal at a given interval self. time equals call The Constructor within the class qtimer then pass in we're going to call a method of initialize UI self. init UI but we still have to Define this method all right within our stopwatch class we need the following methods a method of init UI this is where we'll be designing the user interface I'll write pass for now as a placeholder we need a method to start to start the stopwatch that is a method to stop the stopwatch a method to reset the stopwatch we'll create a method to format our time format time besides self there's one parameter we have to pass in a time to format we will will be returning a string a string representation of the current time and a method to update our display update display here are the six methods we'll need within our initialized user interface method we will set the title of the window because right now it says python we will take self our stopwatch call the set window title method and we will pass in stopwatch that should change the title of the window to stopwatch we're going to use a vertical layout manager for the label and the buttons we will create a layout manager named vbox vbox equals call The Constructor of q v box layout we will take our layout manager and add the following widgets self. time label then our start stop and reset buttons start button stop button and reset button we will take self set the lay layout passing our vertical layout manager so we have all of our buttons we have our widgets arranged in a column we're going to take our time label and also Center it horizontally we will take our time label self. time label call the set alignment method access our class of QT access the flag of a line Center that's going to Center align the time it should be aligned both vertically and horizontally now with your buttons they're arranged in a column we could group them together horizontally here's how we will create a horizontal layout manager of hbox hbox equals call The Constructor of qbox layout instead of adding these buttons directly to our vertical layout manager let's cut them paste them underneath hbox replace vbox with hbox then with our vertical layout manager vbox we will add our layout of hbox this group of buttons is arranged vertically with with the time label now we'll be applying a style sheet access self our stopwatch call the set stylesheet method we can pass in one extremely long string with a set of triple quotes all of the CSS like properties We'll add we'll do so between the set of triple quotes let's select our buttons Q push button we are selecting an entire class within a set of curly braces let's add the property of font size the font size of all buttons will be 50 pixels let's customize our label select the class of Q label within a set of curly braces let's add the following properties font size will be 120 if you would like we can add a background color too to the label we can select a background color temporarily I will select blue but we can pick more specific shades of blue or another color here's how you can look up a Color Picker and select a very specific color you can use hex values RGB or hsl I've already selected a color I'm going to copy these hsl values so instead of a color name we will select hsl then paste those values if you have a degree symbol you will need to remove that and now we have a very specific shade of blue I will also round the corners of our label add the property of Border radius I will set that to be 20 pixels this will round the corners between each button and label We'll add some padding we're going to use multiple selectors we will select all push buttons and all labels apply the following properties to each I will add padding of 20 pixels around these widgets and I will also make the font weight bold font weight will be bold all right I think that looks pretty good hey this is bro from the future I currently editing this video if you would like you can add a font family one font that I think looks really good is C we'll apply that to all push buttons and C labels I really like this font I think it fits a stopwatch but it's up to you if you would like to change the font I just thought I would mention that now we just have to add some functionality because these buttons don't do anything for each of our buttons we have to connect a signal to a slot we will take our start button self. start button with the signal of clicked we will connect the following slot we will call the start method self. start method let's do this with the stop button change start to stop clicked connect self. stop method reset self. reset button called the reset method at a given interval we're going to update our display self. timer during a signal of timeout we will connect the following method self. update display self. update display within our start method we will take our timer self. timer call the start method pass in 10 for 10 milliseconds we will set an interval for a time out every 10 milliseconds within our stop method we will take our timer and instead called the stop method we'll get back to reset in just a moment let's work on the format time method from our time that we pass in we have to get the hours minutes seconds and millisecs seconds we will create some local variables hours equals access our time that we pass in call the hour method to return hours we have variable minutes time do call the minute method to return the minutes we have a variable of seconds seconds equals take our time called the second method then for milliseconds access our time call the MC which means milliseconds and call it this is a method I'm going to return a string an F string to represent the time we will add four placeholders hours minutes seconds and milliseconds each will be separated with a colon except for milliseconds which will be a DOT a period we will display the hours I'll add some leading zeros two leading zeros let's do this for minutes we're using a format specifier for two leading zeros as well seconds and milliseconds now we will work on the update display method we have to get the time self. time equals we will take our time but call the add milliseconds method Ms e CS then pass in 10 for 10 milliseconds we're going to take our time label self. time label and set the text of it we will call our format time method but we have to pass in a Time we will be passing in self. time let's see what we have currently we can start the stopwatch and we can stop it however we're displaying three digits for the milliseconds we can eliminate that within format time when we get the milliseconds we will use integer division we will divide by 10 this will convert our milliseconds from three digits to two we're basically dividing by 10 so here's our stopwatch currently we can start we can stop we can start again and we can stop again now we just need to reset here's how within the reset method we will take our timer self. timer use the stop method to stop we will reassign our time call The Constructor of Q time we have to pass in hours minutes seconds and milliseconds they're all going to be zero we're resetting our time and then we'll reset the text again of our time label self. time label call the set text method when we set the text we will first format it with the format time method but we have to pass in a time we will pass in self. time and now should be able to reset our stopwatch we can start we can stop we can reset start again and stop again all right everybody so that is a cool stopwatch that you can make using python hey uh what's going on everybody so in today's video we're going to create a working weather app that fetches realtime weather data from an API this is a massive project so feel free to take your time take several days or even weeks if you need to complete this heck you can even add this project to your portfolio well let's get started everybody all right let's get started everybody this is a fairly useful API to get real-time weather data the website is openweathermap.org you will need your own API key but signing up for an account is free to create an account we'll go to sign in create an account enter your information and then sign in once you're signed in to find your API key go to this drop- down menu go to my API keys and you would just need to copy this API key if the status is in active you'll need to toggle it to active like so now it may take several minutes for your API key to become active hopefully by the time of this project where we will need it it'll be active I would either leave up this window or copy this key and paste it somewhere we will need the following Imports we will import CIS CIS means system it handles system variables for your python interpreter we will import the request module to make a request to an API then we'll need widgets widgets are the building blocks of a pi qt5 application from the package of Pi qt5 access the module of QT widget import the following widgets Q application Q widget Q label q line edit Q push button let me put some of these on a new line for readability QV box layout this is a vertical layout manager to work with alignment we'll need the following from the package of Pi qt5 from the module of QT core import the following class QT which is used for alignment so these are the Imports that you'll need just to be sure that I didn't misspell anything or get the capitalization wrong I'm just going to do a test run no problems processed finished with exit Code Zero sometimes I make one of these characters a lowercase and then it doesn't work okay we have our Imports we will need to create a class of weather app weather app is going to inherit from the parent of Q widget we will need a Constructor so we'll Define that Dunder init no arguments besid self in case we have arguments to send to the parent we will call the the parent with super meaning the super class then call the Constructor but currently we don't have any arguments if we are running our main python file directly we can verify that with the if statement if Dunder name is equal to a string of Dunder main if we are running this file directly then we will create a weather app object otherwise we won't if this statement is true we will do the following we will create an app object app equals call The Constructor within our Q application class but we will pass in the following access the module of CIS then access a RGV which means arguments if we have command Aline arguments to send to our application this is how we would take care of that but we're not going to be using command line arguments in this video but it's nice to Future proof our code just just in case we do we will construct a weather app object weather app equals call The Constructor of our weather app class now this window isn't going to show we have to call the show method of our weather app Weather app. Show and now it's going to show for a brief second we need to ensure a clean exit access sis call the exit method within this method we will pass in the following take our app call the execute method which is excore it is a method so we have to call it this method handles events within our application such as closing the window so now our window should stay in place until we close it if you're one of the people that have jumped ahead we have created a class of weather app which inherits from the parent of Q widget we've constructed a weather app object and we're showing it if you've made some Pi qt5 Projects in the past you would just have to change some of these around within the Constructor of our class weather app we will declare the different widgets that belong to our weather app object we will create a label that prompts the user to enter in a city we will name this city label equals this is a q label widget we can set the initial text of the label let's say enter city name then the second argument is going to be self we are adding this label to our weather app object here's what we have currently we still have to do some CSS formatting but we'll take care of that soon we will need a line edit widget basically a textbox we will name it City input the widget is line edit no parameters besides self here is our line edit widget we're not currently using a layout manager these widgets are going to overlap we need a button self. getet weather button this is a q push button the text on this button button will be get weather we are adding this to self our weather app object here's our button when we click on this button we'll make a request to an API for the next following widgets we're going to add some placeholders just so that we can see what we're doing when we apply CSS styling we need a temperature label to display the temperature temperature label equals a q label temporarily for the label let's say that the temperature is 70° fight or pick something else in Celsius so to add a degree symbol if you're using Windows make sure numb lock is on hold alt then on the numpad type 0176 I will pick 70° fah and then we will add this to self again we're just using this temperature as a placeholder we'll delete it when we do a test run if you would like to include an emoji or some other image we can create a label for that I will name this Emoji label equals a q label I will add an emoji of a son as a placeholder again we're going to delete this when we do a test run we are adding this to self again everything is overlapping that is fine and we need a description of the weather description label equals a q label as a placeholder let's say that it's sunny and we are adding this label to self okay here are all the widgets they're all overlapping so we need to fix that all right moving on everybody so now we have to design the layout of our web app right now all of our widgets are gravitating to the top left corner so I will Define a method to initialize our user interface at the end of this Constructor we will call this method self. initialize UI then call it once we've constructed our widgets we'll format them and design the layout so we are now within our initialized user interface method first let's set the title of our window self. set window title let's say that the title is weather app so that should change which it does we're going to use a vertical layout manager to handle all the widgets let's name the layout manager vbox equals call The Constructor of the class QV box layout we're going to take our layout manager of v-box then add a widget we will start with the city label that's first we will pass in self. City Lael and we'll do this with the other widgets too we have City input get weather button temperature label Emoji label and then a description label take self our weather app set the layout we will pass in the layout manager of vbox and here's what we have currently all the widgets are arranged in a column now we just have to centeralign them horizontally here's how we will take self. City label call the set alignment method access the class of QT access the flag of a line Center we're going to align all of our widgets in the center except for our weather button currently our button expands to take up the width of the window so we don't need to horizontally align that so we have five widgets to align we have City label City input temperature label Emoji label and description label all of the widgets are going to be arranged in a column horizontally now we just have to apply some CSS styling because right now it's kind of ugly we will apply Styles based on an object name but we have to set that object name so let's start with our city label self. City label call the set object name method pass in a unique ID for this widget I will name it City label I'll keep it the same okay we have to do this with the other widgets too we have a total of six we have City label City input we have the get weather button temperature label Emoji label and description label then we're going to set a stylesheet take s our weather app apply a stylesheet with set style sheet we have a lot of properties to write I will do so within a set of triple quotes just to keep everything more organized we can apply CSS Styles based on a class so the class is going to be Q label within a set of curly braces we can list multiple CSS properties I will set the font family to be calibri as well as all push buttons Q push button so here's the font although it's still kind of small let's select our ID of City label it's good practice to preedee this ID with the name of the class so Q label pound sign the ID we precede the ID with the name of the class just so we're only applying these CSS properties to any ID that's a city label that falls within the class of Q label let's set the font size to be 40 pixels let's set the font size to be 40 pixels that's better I'll set the font style to be italic font style italic that's pretty good let's select the ID of City input this is a line edit widget q line edit pound the ID of City input within a set of curly braces let's set the font size to be 40 pixels we will select our push button which is named get weather button the class is Q push button pound the ID of get WEA button within a set of curly braces we will apply the following let's set the font size to be 30 pixels and let's make it bold font weight bold let's select our temperature label the ID is temperature label and this is a q label pound temperature label we will increase the font size font size 75 pixels better let's work on our Emoji next we will select the ID of emoji label the class is Q label the ID is Emoji label we'll set the font size first font size 100 pixels I would like a large image to display emojis properly we're going to use a very specific font we're going to set the font family to be now I don't know if I'm saying this right seg o UI emoji I probably pronounced this word wrong but I don't care so then our Emoji should display correctly using this font it's colorful then we have the description label of the weather that is the last widget description label the class is Q label the ID is description label let's take the font size and set it to be 50 pixels all right so this is what our weather app is going to look like we have the city label a text box to enter in a city the get weather button the temperature label an emoji label and a description of the weather currently now we just have to add some functionality because currently this doesn't do anything all right so now we just have to add some functionality to our weather app temporarily I'm going to to collapse our initialized user interface method we will Define a few extra methods let's declare a method of get weather no parameters besid self I'll write pass for now as a placeholder we will need a method to display any errors display error there's going to be one argument besid self a message we will pass in an error message if there is one and a method to display weather that's if there's no errors we will need some data our weather data so be sure that you write these three methods back within our initialized user interface method at the bottom we have to connect a signal to a slot when we click on the button with the signal of clicked we will connect a slot of get weather we will access self take our get weather button with a signal of clicked we will connect a slot upself dog getwe and I will print a test message just to be sure that it's working you get the weather so I press the button and and we will display you get the weather we can get rid of our placeholder text for the temperature our emoji and the weather description so we can delete these strings But be sure to keep self scrolling down to our get weather method when we click the button we're going to create a few local variables the first is going to be our API key equals this will be a string back to the open Weather API you will copy your API key and make sure that it's active you can use the toggle button to make it inactive and active so make sure that it's active paste your API key within a string please use your own it still may take several minutes for your key to be itive just keep that in mind we will need to get the city that we're looking up so let's say we type in Miami I have to get the text from this widget this line edit widget we will create a local variable of city city equals access our line edit widget it had a name of City input so self. City input to get the text we will call the text method we have the API key and the city now we will create a URL this will be an F string using the request module we will pass in a URL to make a request too so back to our open Weather API to get the URL for a city we have to go to the tab of API scroll down to current weather data and there's going to be some API documentation to the right we have a link for built-in API request by city name we will copy this URL and paste it within our F string there's two changes we're going to make we will replace city name with City the name of that variable and API space key with API uncore key it doesn't matter what you name these just make sure they're consistent with your variables when we make an API request we will be returned with a response object response equals access our module of requests call the get method then pass in our URL with our response object we have to convert it to a Json format we will be returned with an object we will name this object data it's going to be readable to us data equals take our response object and use the Json method to convert it to a Json format so let's print our data to see what we're working with let's say I look up the city of Miami so we have one gigantic object this is our weather data we have coordinates such as longitude and attitude a weather description currently in Miami there's broken clouds there's an ID of the weather this is the temperature but it's in kelvin if we scroll all the way to the end we are looking for an HTTP status code which is named Cod short for code 200 means that the response was successful depending on what this number is we will display one of a few are messages if our status code is 404 that means the city wasn't found and there's many others so 200 means that the request was successful so let's write the following if our data object at Key of cod if this is equal to 200 if the request was successful then we will call the display weather method self. display weather there but we do have to pass in our data now temporarily I'm just going to print our weather data we'll do some more complex stuff later but I just want to be sure that everything is working so let's look up Los Angeles so here's the weather in Los Angeles there is currently broken clouds and again the status code is 200 the request was successful I'll write an else statement for now we will print our data what if we can't find a city for example I will look up the city blah blah blah and get the weather so here's our weather data we have an error code of 404 and a message of City not found let's do some exception handling in case we run into one of these status codes that's not 200 we can get rid of our else statement what we'll do is enclose all of our dangerous code that means any code that might cause an exception within a tri block we will try all of this code and handle any exceptions with an accept block there's two types of exceptions we're looking for the first is an HTTP error HTTP error is an exception raised by the request module when an HTTP request returns a status code that's 400 or 500 however this exception is found within the request module that we've imported so we can't simply just say accept HTTP error we first have to access the request module then access exceptions then we can list the specific exception of HTTP error we'll encounter this exception if the status code is between 400 and 500 and for now all right pass so there's one more step within our Tri block if we're going to handle any HTTP errors we have to raise an exception within our Tri block because our Tri block by itself normally doesn't catch these we will take our response object and call the raise for status method this method will raise an exception if there's any HTTP errors normally our Tri block doesn't do that so we have to manually type this there's another type of exception we'll catch and that's the request exception We'll add another block for accept request exception this is found within the request module requests exceptions request exception with a request exception this can be due to network problems invalid URLs exceptions of that nature in case we run into one of those types of exceptions we will execute this block of code but for now I'll right pass we'll get back to it later going back to our accept block where we handle any HTTP errors let's use a match case statement we need to get the status code of our response I'll print that temporarily let's print our response objects status code and see what it is again let's make up a city get the weather we have a status code of 404 that means the city will wasn't found depending on what this number is the status code we'll use a match case statement so we will match our response objects status code the first case will be 400 that means there's a bad request so let's print the following bad add request I'll add a new line character please check your input we'll create a total of I believe eight cases we'll copy what we have so we have 400 401 403 404 that one we're familiar with 500 5 2 503 504 so for case 401 that means we're unauthorized maybe our API key isn't active yet so let's say unauthorized invalid API key for 403 that means access is denied it's forbidden so let's print forbidden access is denied 404 is for something that's not found not found City not found 500 is for an internal server error internal server error please try again later 502 is for a bad gateway bad gateway invalid response from the server 503 is for service unavailable service unavailable server is down then 504 is for a Gateway timeout Gateway timeout no response from the server in case there's any unexpected error we can add a wild card of an underscore with our HTTP error let's give it a name as HTTP error and then we'll just print it in case there are no matching cases let's print the following HTTP error occurred I'll add a new line let's convert this to an FST string add a placeholder and then I will print our HTTP air all right let's do a test run so in case we can't find our city we should encounter a 404 error not found City not found eventually we will display this message within our app but we know that it works what if my API key is invalid so I will take my API key set it to be inactive but it might take a few minutes to take effect the status code of our response object should be 401 so this time I'm going to look up a city I have an invalid API key and I get that error message of unauthorized invalid API key all right everybody so I am on day three of working on and recording this topic over the course of the day I thought of one change that I can make we're going to add a few extra accept blocks so we will accept access requests access exceptions we will handle any connection eror exceptions as well as any timeout exceptions and any redirects too many redirects so if we run into a connection error let's say that our internet gets disconnected well we can print something so let's print the following let's print connection error I'll add a new line character check your internet connection if we encounter a timeout then we will print the following we have a a time out error the request timed out if we have a too many redirects error that M should be Capital by the way let's State too many redirects check the URL and if there's anything else we don't anticipate I'll give this exception a name of as Rec error and then we'll just print it this is a last resort I'll use an F string request error I'll add a new line I'll add a placeholder then display our request error so I'm actually going to turn off my internet I'll see if I can get a connection eror intentionally so my internet is currently off I will attempt to look up a city get the weather and we get a connection error check your internet connection all right my internet is connected again let's perform a test run and we get the weather in Miami now what we're going to do is if we have an error we'll display the error message within the app and not within our console so we're going to replace print with the call to our display error method let me zoom out a little bit so replace print with self. display error and we're passing in a message so let's replace those one thing I forgot to add although it's not necessary I'm going to add a colon after each initial message I think it'll look better you don't have to do this but I'm OCD about the appearance if we encounter one of these exceptions we'll pass along a message to our display error method and display it within the app let's take our temperature label self. temperature Lael and set the text to be our message that we pass in let's do a test run let's look up a city that doesn't exist get the weather so we get that error message not found City not found while we're within this method I'm going to change the font size just so that it's a little bit smaller so let's take our temperature label self. temperature label I'm just going to copy this because I'm lazy I will call the set stylesheet method and pass along a new property let's set the font size to 30 pixels let's look up north pole I don't think that's a city oh I guess it is interesting the North Pole is a city I guess let's look up blah blah blah not found City not found let's do another test what if our API key is invalid I'll just delete one of the digits let's look up Los Angeles unauthorized invalid API key let's change that back again I will turn off my internet then look up Miami Connection Error check your internet connection all right so we know that our exception handling works okay now we're within the display weather method we'll receive an object to represent our data we have to get the temperature but first I'm going to print our data so let me zoom in a little bit let's look up Houston Houston Texas I need the temperature within our data object we are looking for a key of Main and that is right here main contains a dictionary with key value pairs once we've accessed main we have to access temp to get the temperature and this temperature is in kelvin we'll have to convert it to Celsius or Fahrenheit it's your choice so we need to extract this value I will store it as a local variable temperature let's say temperature _ k for Kelvin equals take our data object access the key of main that's right here then we have to go one level deeper and get the temperature the key is temp then give me the value at the Key of Temp and that should return the current temperature so to test it let's print it let's print the temperature in Kelvin so what is the weather in Houston Texas the temperature that is 309 Kelvin let's convert it to Celsius and Fahrenheit let's create temperature C if you want to use celsius if you would rather use Fahrenheit you can skip this step to convert from Kelvin to Celsius we will take our temperature in Kelvin subtract 273.15 then for Fahrenheit let's take temperature f for Fahrenheit equals this is a little more complicated take our temperature in Kelvin time 9 / 5 subtract 45967 okay so let's print the temperature in celsius let's look up Houston 36.467853 [Music] self. temperature label I'll just copy this then we will set the text I'll use an F string add a placeholder I'll use Fahrenheit but feel free to use celsius then I will add a degree symbol with Windows make sure numb lock is on hold alt then on your numpad type 0176 for a degree symbol then f for Fahrenheit let's look up get the weather and here's the temperature 94.9 64 now let's say I would like no digits after the decimal I can add a format specifier after our temperature I'll add a colon 0f to display no decimals let's try that again I will look up Miami get the weather the current temperature in Fahrenheit is 95° Fahrenheit now here's one issue let's say we display an air then display the weather if we display an err we're going to be changing the font size so let's look up blah blah blah get the weather City not found then let's look up Miami again get the weather and the font size is a lot smaller so if we display the weather let's reset the font size we can really just copy this line so within the display weather method let's set the font size back to 75 what it was originally let's try that again let's look up a city that doesn't exist get the weather City not found then we'll look up the city that does exist like Miami and get the weather 95° F now let's get a description of the weather we'll display that at the bottom in the center we'll display a picture or an em but we'll handle that last now we need a description of the weather like is it sunny is it cloudy is it raining so after we calculate the temperature so I'm going to print our data again let's look up Los Angeles So currently it's 85° Fahrenheit so for the weather description that is found at the Key of weather we now within a list at index zero within our list we'll look up the key of description which states clear sky so we will create a local variable of weather description equals access our data at the Key of weather there's layers to this we're then within a list and actually it's a list with only one item in it so add the index of zero then at the Key of description that's going to return this description of clear sky so we will take our description label self. description label let me just copy it this one right here then we will set the text and then pass in our weather description what is the weather description of Los Angeles 86° fhe and there's a clear sky okay now the last thing we're going to do is add an emoji We'll add it right to the center between the temperature and the weather description you don't NE necessarily have to but I think it'll look cool and that's a good enough reason so let's create another method to handle that we will Define a method of get weather Emoji or a picture if you would rather use a picture we don't need self necessarily we're going to need a weather ID this method isn't going to rely on any class data or instance data we could make it a static method I'll add a decorator of static method in summary a static method we haven't covered these for a little bit they belong to a class but don't require any instance specific data or any other methods they're used as more of a utility tool we're going to be passing in a weather ID and returning an emoji I'm going to show you where we can find that weather ID I'll use a print statement I will print our data let's look up Miami again that's the first thing that came to mind now at the Key of weather there's a key of ID and the value is a three-digit number I'll show you this chart depending on what this three-digit number is that cor responds to a certain group of weather so the 200 range is a thunderstorm 300 is a drizzle 500 is rain 600 is snow 700 is atmosphere like if there's a tornado or there's a volcanic eruption 800 exactly is a clear sky anything that's 801 or above refers to clouds so this ID is 803 we have broken clouds depending on what this ID is I would like to return a certain Emoji based on the weather so we need this ID I'll delete our print statement we no longer need it let's say before our weather description we will create a local variable of weather ID equals access our data object then access the key of weather the value at weather is a list but this list only has one item in it so we need the index of operator at zero and then we will access the key of ID the key is ID so our weather ID is going to be a number a three-digit number okay everybody we're near the end so after setting the temperature we're going to set the Emoji label self. Emoji label and call the set text method within the set text method we will call self. getwe Emoji method this will return a string an emoji within a string but we have to pass in our weather ID it's that three-digit number so now we are within our get weather Emoji method depending on the range of that three-digit number we will return one of a few emojis we could use a match case statement I think it's more complicated with with the match case statement we'll use LF statements for Simplicity so if our weather ID is greater than or equal to 200 and our weather ID is less than or equal to 232 now we have two conditions here linked with the and logical operator there is a shortcut to this and actually py charm is telling me that there is we can simplify these Expressions instead of two separate conditions we can combine them into one if 200 is less than or equal to our weather ID and our weather ID is less than or equal to 232 if this one combined condition is true then we will return an emoji so to add an emoji on Windows you can hold on the window key and press semicolon so 200 to 232 that's for a thunderstorm depending on the font style of your IDE some of these emojis might not display properly you can always just copy them from someplace else I think that's better it's more colorful than else if 300 is less than or equal to our weather ID and our weather ID is less than or equal to 321 this this is for a partially cloudy Sky we will return some clouds a partially cloudy sky and again I don't like that one so let's use this one instead else if 500 is less than or equal to our weather ID Which is less than or equal to 531 we will return rain that's better 600 to 622 else if 600 is less than or equal to our weather ID Which is less than or equal to 622 we will return snow so 701 to 741 is missed or fog else if 701 is less than or equal to our weather ID Which is less than or equal to 741 we will return some mist or fog 762 specifically is for Ash like from a volcano so else if our weather ID is directly equal to 762 we will return let's return a volcano 771 is for a Squall that's a violent gust of wind else if our weather ID is directly equal to 771 we will return let's return that a violent gust of wind a Squall 781 is for a tornado else if our weather ID is equal to 781 return a tornado a 800 exactly is for a clear sky else if our weather ID is equal to 800 return a sun a sun emoji else if 801 is less than or equal to our weather ID Which is less than or equal to 804 we will return some clouds now if there are no matches let's return an empty string to not display anything okay let's do a test run let's look up Miami we get scattered clouds it's 94° Los Angeles get the we we have a clear sky and a sun now there's one fix we need to make let's say that I make up a city again blah blah blah get the weather we should clear our Emoji label and the weather description but we still get that error message so after we display our error within the display error method after we set the text of the temperature label let's take the Emoji label self. emoji label and call the Clear method to clear it then we have to do this with the description label self. description label and call the Clear method now we should be able to clear it when we get an error okay let's look up Houston get the weather few clouds 98° let's make up a City Pizza City get the weather not found City not found and the Emoji label and the weather description are cleared okay what if I type in nothing what happens let's get the weather we have a bad request please check your input that's if we have an HTTP status Cod to 400 we handled this exception bad request all right one last City what about Paris let's get the weather it is 68° F and there's light rain all right everybody so that is a weather app that you can make using python add it to your portfolio and thanks for watching