YTread Logo
YTread Logo

Python Tutorial for Beginners [Full Course] Learn Python for Web Development

Apr 27, 2020
of this house, so we set the price at 1 million, that is, 1 with 6 zeros. Then we need a variable to know if this buyer has good credit, then he has good credit, and we set it to true, now we need an if statement, so if he has good credit it has two points true, here we need to calculate a down payment so that The initial payment must be equal to 0.1 x the price. That's 10 percent of the price of this property. Otherwise, the down payment must be 0.2 times the price. Now, we finally remove the indentation and print here, we can use a valid string form, first we add a label, two dots upfront and right after that we add a placeholder or a hole for our upfront variable.
python tutorial for beginners full course learn python for web development
So, down payment with keys. Let's run this program so that the down payment for a buyer with good credit is $100,000. Now let's improve this by adding a dollar sign before this number. So let's go back to our formatted string, just before the curly brace I'm going to add a dollar sign. Let's run this one more time, that's better. In this

tutorial

I am going to talk to you about logical operators within Python. We use these operators in situations where we have multiple conditions.这是一个例子。 Let's say we are creating an application to process loans. If an applicant has high income and good credit, then they are eligible for a loan.
python tutorial for beginners full course learn python for web development

More Interesting Facts About,

python tutorial for beginners full course learn python for web development...

So, in this example we have two conditions, one is to have a high income and the other is to have good credit. So, if both conditions are met, then the applicant is eligible for a loan. This is where we use the logical and operator. We use this operator to combine two conditions and by the way this is not specific to the Python programming language, pretty much any programming language that supports if statements also supports logical operators. So, going back to our program, let's define two variables, has high income, we set it to true. And another has good credit, we also set this to true, now our statement if you have high income is true and you have good credit is also true, then we will print eligible for null.
python tutorial for beginners full course learn python for web development
This is where we use the and operator. So if both conditions are true, this message will be printed. If one of them is false, we will not see this message. Let's try this. So I'm going to run this program so we can see that you are eligible for the loan, but if we change any of these conditions to false and run the program again, the message goes away. So this is the logical operator and. We also have the logical or, and we want to use it in situations where we want to do certain things at least one of the conditions is true, for example let's change the rule for this program, so that if the applicant has high income, or good credit, then they are eligible for a loan, so if one or both conditions are true, then the candidate is eligible.
python tutorial for beginners full course learn python for web development
Now, returning to our program, we can implement this rule using the logical or operator. So we just replace and with o, now when we run this program we will see this message because at least one of our conditions is true, let's take a look. Therefore, the applicant is eligible for a loan because he has good credit. If you change this to false but set the other condition to true, we will still see the same result, but if both conditions are false, we will no longer see this message. This is the difference between these operators. With the logical operator and both conditions must be true, with the logical operator u at least one condition must be true we also have another logical operator called not and that basically inverts any boolean value that we give it, if we give it, we give it a boolean value true makes it false.
For example, let's create a new room, if the applicant has good credit and no criminal record, then he is eligible for a loan. Let me show you how to implement this. Then, we return to our program, in this example we do not need a first variable to delete. Let's set this variable to true and also define another variable like has criminal 记录。 We set this to false. Now we want to verify if this applicant has good credit and no criminal record. This is where we use the not operator. So if they have good credit and no criminal record, then in this example if they have a criminal record is set to false, when we use the not operator this is basically changed to true, so we have two conditions that are true.
Here are some and here is another. Then our applicant is eligible for a loan. And when we run this program we see this familiar message. If an applicant has a criminal record, let's change this to true, now when we run this program we can see that our applicant is not eligible because when we apply, then we operate on this variable, we will get false. Then true changes to false. And we will end up with two conditions, one that is true and the other false. And that is why this message is not printed. So it's all about logical operators in Python.
In this

tutorial

I will talk to you about comparison operators in Python. We use comparison operators in situations where we want to compare a variable with a value, for example, if the temperature is greater than 30, then we want to print that it is a hot day. Otherwise, if it is less than 10, it is a cold day, otherwise it is neither hot nor cold. And by the way, I mean degrees Celsius, not Fahrenheit. So to incorporate these rules into our program, we need to use comparison operators. Coming back to app.py, I define this temperature value, let's write an if statement, if the temperature now we want to check if it is greater than 30, then we use the greater than operator.
If this is greater than 30, we want to print that it is a hot day; otherwise, let's just print that it is not a hot day.现在, when we run this program, we will see this second message because 30 is not greater than 30. So our first condition is that a value is false. Let's check that. So run, it's not a hot day. Now if you change the temperature to 35 and run this again, we'll see a different message, it's a hot day, so this is where we use comparison operators. Now what we have here, as you know, is an expression because it is a piece of code that produces a value.
More precisely, this is a boolean expression. So this is the greater than operator, we also have greater than or equal to, we have less than, less than or equal to, here is the equality operator, so if the temperature is equal to 30, then you can say it's a hot day. Note that this is different from the assignment operator which has only an equal sign. You can see that if we use just an equals sign here, we immediately get this red underline because this is simply an assignment statement. We are changing the temperature value. you are setting the value of something else.
So we don't have a boolean expression, you're not producing a boolean value. So our equality operator has two equal signs and finally we have no equal, which is an exclamation mark followed by an equal sign. Now here's an exercise. You've probably seen that when you fill out an online form, sometimes the input fields have validation messages, for example, let's say we have an input field for the user to enter her name. Now, if the name has less than 3 incorrect characters, we want to show a validation error, like the name must have at least three characters; Otherwise if the name is more than 50 characters then we want to show different validation error like name can be maximum 50 characters.
Otherwise, if the name is between 3 and 50 characters, we just want to tell the user that the name looks good. So go ahead and write a plan to implement these rules. Alright, let's define a variable called name and set it to, say, j. So we assume that this is what the user types in an input field. Now we want to get the number of characters in this string. So we use the len function, right? Len by name. When we print this we get 1, you've seen it before. Now here we want to use an if statement, so if the length of the name is less than 3, then we want to print the name must be at least 3 characters.
Now here we need a second condition to check the upper bound. So if the length of the name is greater than 50, then we want to print a different message, the name must be a maximum of 50 characters.好的? And otherwise, if none of these conditions are met, it means that the name looks good.所以, print, the name looks good. Let's run our program. So in this case we get this message because our name is too short. Now, if you come back here and write something really long. If we run our program we will see a different message name which should be a maximum of 50 characters and finally if we type a suitable name here like John Smith and run our program we get the name 看起来不错。 Here is another good exercise that combines many of the materials you have

learn

ed so far, so you previously created a program to convert a person's weight from pounds to kilograms.
Now we want to extend this program and allow the user to enter his weight in kilograms or pounds and then we will convert it to another unit. This is how our program will work. I then enter my weight in pounds, so 100 and 60 now tell me if it is in pounds or kilograms. So here I'm adding l to pounds or k to kilograms. And by the way, this program is not case sensitive, so when I enter an uppercase l or a lowercase l, it takes it as pounds. Now it tells me that you set it in kilos.
Let's run this program one more time, this time I'm going to enter my weight in kilos, so send it to is the weight and the unit is kilograms, so k, and it says I weigh 160 pounds. So go ahead and spend a few minutes on this exercise; you will see my solution below. Okay, first let's ask the user his weight. So we use the input function, weight colon, get the return value and store it in the variable called weight. Now the second question, once again we use the input function el for pounds. Or k for kilograms. So let's get that too and store it in a variable called unit, now we need an if statement.
So if the unit is equal to l, then we must convert this weight to kilograms. However, with this implementation we only allow the user to enter a capital l; If you enter a lowercase l, this code will not work. This is where we use the top method of string objects, so this unit is a string because, as I told you before, the input function always returns a string. So we can use the dot operator to access all its methods or functions, here we call the top method, this will convert everything the user enters to uppercase and then we will convert it to a capital l.
Now if this condition is true then we need to get the weight and multiply it by 0, 0.45. However, as you know, this weight is a string object and we cannot multiply a string by a floating point number, we talked about this earlier in this

course

. So first we need to convert this weight to a numerical value. Right here, when we call the input function, we can get the return value and pass it to the int function. Then, we call the int function and give it the return value. value of the input function. Now, the in function will return an integer so we can store it in this weight variable.
So here is the converted weight, let's store it in a variable called converted, then print here, we can use a formatted string, so we prepend this string with f and add curly braces to dynamically insert the value of the converted variable. And finally we add kilo. Otherwise, if the unit is kilograms. We need to divide the weight by 0.45. q So, weight divided by 0.45 and just to refresh your memory, this division operator returns a floating point number, but if we use double slashes we will get an integer. In this case, we want to get a floating point number, finally let's print a formatted string, its keys, converted pounds.
Let's run this program and see what happens. So the weight is 160 and lbs and that equals 72 kilos, perfect, if we run it one more time and enter 72 kilos we get 160 lbs. In this tutorial, I will show you how to use y loops in Python. Loops and loops are used to execute a block of code multiple times and are often useful for creating interactive programs and games. In a future tutorial, I'll show you how to create a simple game using a loop. So let's start with the basics, we write a statement and right after that, we write a condition followed by a colon, as long as this condition is true, the quote we write in this block will be executed repeatedly.这是一个例子。 We can define a variable as i, as shorthand for index and set it to 1.
Now we set our condition to i less than or equal to 5, so whenever I is less than or equal to 5, we can print I, in the terminal. And then we need to increment i by 1. So we set i to i plus 1. TheThe reason we do this is that if we don't do this it will be 1 forever, so we will end up with an infinite loop. Because this condition will always be true. One is always less than 5, so in each iteration of this loop, we increment i by 1, so at some point, i will be six and that's when this condition will be false and then we'll jump out of this. loop, okay?
Now, to demonstrate how everything works after this loop, I'll add a print statement that says done. Note that these two lines are indented so that they are part of the y block. Okay, now let's go ahead and run this program and see what happens. Then take a look, we get the numbers 1 to 5 followed by done. So this is how this program is executed: first we set i to 1, now the Python interpreter executes line 2, this condition is true because i is less than 5, so i is printed to the terminal and then incremented at 1. Then control returns to the beginning of the loop and.
Then it doesn't move on to the next statement. Then we come back here and now we're on the second iteration. In the second iteration, i is 2, and since 2 is less than 5, our condition is still true, so i will be printed to the terminal and once again incremented by 1, so at some point i will be 6 , and that is when this condition will be false so our search will end and this message will actually be printed to the terminal. These are the basics of loops and. Now let's make this program a little more interesting. Here we can write an expression like this.
Add a string, and in this string we add an asterisk and then we multiply this string by i. With this expression, we can repeat a string, when we multiply a string by a number. , that string will repeat. For example, if i is two, this expression will produce a string with two asterisks. Now let's run the program and see what we get. So we see this little triangle shape here. Because in the first iteration i is 1, 1 time an asterisk produces 1 asterisk. In the second iteration, i is 2, so when we multiply 2 by 1 asterisks, we will get 2 asterisks. In this tutorial, I'll show you how to use a loop to create a guessing game like this.
So we have this secret number that is currently set to 9. Now the computer is asking me to guess. So let's say 1 is not correct because the secret number is 9, okay, try again, 2, no, it is not correct. , let's try it again, so I only have three chances to guess. If I can't guess the number the program tells me I failed. Let's run the program one more time, this time I'm going to guess the number, it's 9, there you go, it says you entered. So let's go ahead and build this program using a loop. Alright, let's start by defining a variable to store our secret number, so we call the underlined secret number and set it to 9.
Now we need a while loop to repeatedly ask the user to guess. So while the condition two points What is our condition here? Well, we want to give our user a maximum of three guesses. Similar to the last tutorial, we can define a variable like I, set it to 0, and assume that this represents the number of guesses the user has made. And then we write our condition as i less than 3. Please note that here I am not using the less than or equal operator, because with this condition our loop will be executed 4 times, while i is 0, one, two and three. , then here we should use the less than operator.
Now if we give this code to someone else, it's not clear what I represent here, it's just in our head that it represents the number of guesses the user has made. Therefore, as a best practice, always use meaningful and descriptive names for your variables. Therefore, it is better to rename this variable to guess and count. Let me show you how to change the name. So right click on i variable and then go to refactor and rename it. Look at the shortcut. On a Mac computer it's shift and f 6. Now in this dialog we can easily change the name of your variable and pycharm will update all references to that variable so we don't have to manually update each instance, okay?
Let's change this to write_count enter, there you go, that's better, it's also better to store 3 in a separate variable to make our code more readable, because it's not very clear what 3 represents here. So let's define a variable called guess limit, let's say to 3, and then we can change 3 to guess limit underscore, now our code is more readable while the guess count is less than the guess limit, see, it reads as a story, this is how you should write code.可以,然后呢 as long as this condition is true, we want to provide the user to guess. So here we use our input function, guess.
Now everything the user enters comes out as a string, so we need to convert it to an integer. So here, we pass the result to the final function and then we get it and store it in a separate variable called guess. So at this point the user made a guess, now we need to increment the guess count so we set it to plus equals 1 or okay now we need to check if the user will make the correct guess. So here we need an if statement. If what the user guessed is equal to our secret number, you will see again that our code is so readable.
It's like a story that you can read as if it were English. So if this condition is true, we want to tell the user that they won. So print, you won. Now let's go ahead and run our program up to this point. So, okay, you're asking me to guess, I'm going to make a wrong assumption, so one asked me again, 2 again, 3, okay, what's missing from this implementation is the message telling me I failed. . We'll deal with it momentarily, but let's run the program one more time and make the correct assumption. So 9 is fine, it says you won, but it still asks me to guess, because our while loop will be executed 3 times.
Figures 1 and 2. Therefore, we need to change our program so that if the user makes the correct guess, we need to finish our while loop, we need to jump out of it.我们怎么做? So here, if the user guesses correctly, after printing this message we can use the brick statement to terminate terminate a loop, when the Python interpreter sees this, it will immediately terminate our loop and will not evaluate this condition again. Now let's run our program and see what happens.所以,我要去 guess the correct number, you won and look, now they ask you to make two more guesses, beautiful. Now the last thing we need to add here is the message that tells the user that he failed if he couldn't guess the correct number 我们怎么做? Well, in Python our while loops can optionally have an else part. similar to if statements.
Previously you

learn

ed that our if statements can optionally happen in the else part. Here, if this condition is true, do this; otherwise, do something else. In this case our if statement does not have an else part. Now, similar to if statements, our while loops, our while statements can also have an else part. So right at this level we can add an else block, so two points. And the code we write here will be executed if this while loop completes success

full

y without an immediate interruption. In other words. If the user guesses the correct number, you break this loop, jump out of it so that the code we wrote in the else block does not execute.
But if the user cannot guess this number, he will never exit this loop, so this loop will run to completion until this condition becomes false. In that case, the code we wrote in the else block will be executed and this is the perfect opportunity for us to tell the user: "Hey, you made three guesses but none of them were correct." So, print, sorry.失败。 Now, let's try the program one more time. So guess 1, 2, 3, I'm sorry you failed, let's run it one more time. This time I'm going to make a wrong guess, and then the right guess, we won and our cycle ended immediately.
Alright, now it's time for you to practice what you've learned so far. So once again let's create a game. This game is a simulation card game. Now our game is non-GUI and non-sticky and it doesn't really matter for now, our focus is entirely on building the engine for this game. So let's see how this works. When we run this, we get this little symbol here and our program is waiting for us to enter a command. If you type help in lowercase or uppercase, we get the list of commands that our program or game currently supports. So we can write start command to start our car, we can write stop command to stop our car and exit to finish the game.
Any other command we type into our program will tell us, "Hey, I don't understand that." For example, if I type asd here, it will say I don't understand that. If you type start, we get this message, auto started, ready to go, if you type stop it says auto stopped and finally, if we type Press Exit, our program ends. This is a great exercise for you to practice what you've learned, so pause the video and spend 5-10 minutes working through this program. Alright, let's start with a while loop with a condition. What is our condition here? We want to run this loop until the user types exit.
So we can define a variable or a story to sort what the user enters, and then we can run this loop as long as the command is not equal to exit. So, just before the loop, we define a variable, command, and initially set it to an empty string. An empty string is a string that contains no characters. We only have the quotes. So we write our condition while command is not equal to exit and then we do something. Now immediately we have a problem here because we assume that the user writes the command in lower case, so if he writes this in upper case our program will not behave correctly, so to fix this problem you have to call the bottom method of the string object and then compare the results.
With this he resigns. You can also call it uppercase and then type quit in uppercase. It's all about our personal preferences. In this demonstration, I will use lowercase characters. So, okay, now in this loop we need to ask the user to enter a command. So once again we're going to use our input function, we're going to add a greater symbol followed by a space, whatever the user enters, we get it and store it in our command variable. Now, in addition to the exit command, there are three other commands that we need to support. Start, stop and help.
So here we need an if statement to compare what the user enters with one of the supported commands. So if command.lower equals start, then you'll want to print the message as if the car had started. Then print, the car started. Ready to go, it doesn't matter, now the second condition. What if it doesn't start, maybe it stops? If command.lower is equal to stop, there you go, then we print a different message, auto stopped. Now look at our code. We have repeated this lower descent several times. This is bad, in programming we have a term called dry, which is short for don't repeat yourself.
So any time you've duplicated your code, it means you're doing something wrong. So how can we solve this problem? Well, instead of calling the bottom method on each condition, we can call it right here when we receive input from the user, so this input function, as you know, returns a string, we can immediately call the bottom method on this string, and with this command it will always be lowercase, so we don't need to call this method in all conditions. Thus, we eliminate duplication and our conditions are shorter and easier to read. There is also one more place we need to modify, it is here.
That is better. Now, the third command. We need one more if. If command equals help, then we want to show the commands we support. Here we are going to print a multi-line string. Use triple quotes like this and give the user a guide like this. So start to start the car, stop to stop the car and stop to stop. Now finally we need one more part, so if what the user enters is not any of these commands, we will say, hey, we don't understand them, otherwise, type a colon, sorry, I don't understand that. And by the way, note that I'm using double quotes here, I can easily use a single quote as an apostrophe, okay?
So let's run our program up to this point and see what happens. Alright, let's type start, car is on, beautiful, stop, car is stopped, help, we get this guide, but there's so much indentation before our commands that we'll fix that in a second. And finally let's try the exit command. Oops, our program didn't work properly. here is theYou have some advice. Using your for loop you need to iterate over this list. On each iteration you get a number, this determines the number of x's that will be displayed on that particular line. So if you want to cheat you can get this number and multiply it by a string containing x, so if you multiply x by 5 we will get 5 x, that's not what I want you to do.
I want you to use an inner loop here to generate a string containing 5 x. Let's imagine that in Python we cannot multiply a string by a number, so to solve this problem we need a nested loop. So go ahead and spend five minutes on this exercise. And by the way, do your best to fix this. It's a little challenging, but not extremely difficult. It just requires a little concentration. You will see my solution below. Alright, first we need to iterate over all the elements in this list. So for elements in numbers, or, you can rename this variable to x_count.
That's the number of x's on each line. Now I told you that if you want to cheat you can write code 像这样。 Print x for x underline count. If you run this program we will obtain the same result. This is the beauty of Python, with Python we can write expressions like this, we can multiply a string by a number to repeat it. Many other programming languages ​​do not support this feature. For this exercise, I wanted you to imagine that we don't have this feature in Python, so you'll have to use an inner loop to solve this problem.做 works.
In the first iteration, the count of x will be 5. So we need to output 5 x. How can we do that? Well, let's say we define a variable called output and initially set it to an empty string. Now we need to add 5 x to this chain. Additionally, we can use another loop to count in the range, the underscore count of x. So we are using the range function to generate a sequence of numbers from 0 to x count. So in our first iteration, the count x will be 5, so the range of 5 would output the numbers 1, 2, 3, 4. So this inner loop will be executed 5 times.
That's exactly what this count represents. So now in each iteration we simply need to add an x ​​to our output variable. So we set the output, plus, equal to x, and then after this inner loop we simply print the output. With this we will print 5 x in the first row. We then move on to the second iteration of our outer loop. At this point the count x will be 2, now on line 3, we will reset our output variable to an empty string. So we start again. Then we go to our inner loop, this loop will run 2 times, so we will add x to the output variable and then print it, it's that simple.
See, it wasn't actually that difficult, but it was a little more difficult than the previous exercises. So let's run this program, there you have it. Now if you're adventurous, I want you to modify the values ​​that we have in our list of numbers, to print and I here. Now, in this tutorial, we'll take a closer look at lists. So I'm going to define a list of names, let's send them to John Bob Mosh Sarah and Mary. Also, if you print this list here, what we see in the terminal will look exactly like we defined our lists that we have squared. brackets, and between these brackets we have our item, our items, so we have 5 strings in this list.
So we can also access an individual element using an index in the same way we can access an individual character in a string using an index. So here we write square brackets and specify an index. The index of the first element in this list is 0. So let's run this program, voila, we get Jon now. If you want to print the third element in this list, its index is 2, so names 2, Mosh returns, now we can also pass a negative index here, so negative 1 refers to the last element in this list, that is say, Mary, let's run the program, there you go, we see Mary, if you pass negative 2, this returns the second element from the end of the list.
So let's run the program, there you have it, we get Sarah, so this is exactly like accessing individual characters in a string. We can also use a colon to select a range of elements, for example if you pass 2 colons. This will get all elements starting from index 2 i.e. Mosh here till the end of the string. So let's run this program and that's it. We get this list with 3 elements, Mosh, Sarah and Mary. We can also specify a final index, say 4, so this will return all elements up to this index, but does not include the element at this index.
So when we run this program we only see Mosh and Sarah, the element that I have indexed 4, which is the fifth element or fifth element of this list, is not returned. So Maria doesn't come back. And also here we have default values, so if you skip the ending index, this expression will return all elements starting from index 2 to the end of the list or if you skip the starting index, this expression assumes 0 as default index, so which will return all elements from the beginning to the end of the list. And by the way, just like strings, these square brackets here don't modify our original list, they just return a new list.
For example, if we pass 2 here, you can see that this returns a new list with 3 elements. So if you come back here and print our original list of names right after, you can see that she won't be affected. So here we want to use square brackets with colons to select a range of elements, we get a new list and by the way, we can also modify any of the elements in this list. For example, let's say we made a mistake and the first element should not be John with an h, then we want to remove the h, that's very easy, so we access it using an index which is names of 0, and set it to a new value像这样。 Now, let's print our list so you can see that the first item in this list is now data.
These are the basics of lists. And here you have an exercise. I want you to write a program to find the largest number in your list. This is a fantastic exercise for

beginners

, so go ahead and spend a few minutes on it, then come back and continue watching. Alright, let's define a list of numbers, numbers, with a bunch of random numbers 3, 6, 2, 8, 4 and 10. Now, let's find the largest number in this list. We need to define another variable, let's call it max. This variable will contain the largest number. Now you initially want to assume that the first element of this list is the largest number.
So we set max to numbers of 0. We just assume that the first element is the largest number. Most likely, our assumption is wrong. So we need to iterate over this list, we need to loop through it, get each element and compare it with max. If it is greater than Max, then we need to reset the maximum to that number. So in the first iteration we get 3, and max is also 3. Is 3 greater than 3? No, so we go ahead, we get the second number, is it 6, greater than 3? It is, so we need to reset the maximum to 6. Again, we go ahead, we get 2, these two are greater than 6, no, it's not, so we go ahead, then we get 8, is 8 greater than 6?
It is, so we should reset the maximum to 8. That's easy enough. So here we need a for loop, for the number in numbers colon now we need to also see if this number is greater than the maximum, then if the number is greater than the maximum, colon maximum, then we need to reset the maximum, so that the maximum is this. new number, that's all we had to do. So, let's print max and run our program. We can see that the largest number in this list is 10. It does not matter whether this number is at the end of the list or at the beginning.
So if I move 10 and put it right at the beginning, we should see the same result. Let's run our program, we still see 10, if I put this somewhere in the middle, our program should still work. Let's put it right after 2. Run the program, we still get 10. In this tutorial I will tell you about two-dimensional lists in Python. Two-dimensional lists are extremely powerful and have many applications in data science and machine learning. Here is an example. In mathematics we have a concept called a matrix, which is like a rectangular array of numbers, let me show you. We have 1, 2, 3, 4, 5, 6, 7, 8, 9.
Then we have a rectangular array of numbers. You have rows and columns. So this is a 3 x 3 matrix in mathematics. Now we can model this in Python using a two-dimensional list. A two-dimensional list is a list where each element in that list is another list. If you want to define an array. We set it to a list, each element of this list will be another list, and that list represents the elements of each row. So the first element of our list will be another list, and in this other list we will have the values ​​1, 2 and 3. Now the second element of our array list, once again, we have a list, this list represents the elements of the second row.
Then 4, 5 and 6, and finally 7, 8 9. As you can see, we have a two-dimensional list. Each element in our outer list is another list. Well, this is how we can implement an array in Python, now to access an individual element in our array, once again we use square brackets, let me remove these things, okay, so how do we access 1 here? Well, it starts with our list and then we add brackets. First we need to fetch the first element of this list.对? So we pass 0, now this expression returns another list. That's the internal list. In this list, let's say you want to access the second element, so once again we add square brackets and pass 1, which is the index of 2 in this list, okay.
So if we print this to the terminal we get 2. Okay? So using 2 square brackets we can access individual elements in our array, and we can also modify these values ​​using this syntax, so before printing this, let's change this to 20, so array of 0 and 1, let's change it to 20. and then print it , done, it's modified, now here you can also use nested loops to iterate over all the elements of this array. Let me show you. We start with rows for the matrix rows, so with this loop, we are iterating over our Matrix list, in each iteration the row will contain 1 list, 1 element, okay?
Now, here we need to use an inner loop. So we need to loop through this row, which is a list of elements. We can write 4 elements in the colon row and print the element. So let's run this program, voila, we get all the elements in our list. Hey, I just wanted to make a quick announcement. In case you haven't seen my website yet, check out codewithmosh.com. This is my coding school, where you can find many

course

s on web and mobile app

development

. In fact, I recently published a complete Python course that goes far beyond this YouTube for

beginners

.
And if you really want to learn Python and get a job, I recommend you sign up for this course. Like this tutorial, you can watch it anytime, anywhere as many times as you want, and you'll also receive a certificate of completion that you can add to your resume, and the course comes with a 30-day money back guarantee, as well What if you are not happy that we will refund all your money, no questions asked. The price of this course is $149, but the first 200 students can get it for only $15. So if you are interested, the link is below this video, click on the link and get started.
In this tutorial, I will tell you about list methods or list functions. These are the operations that we can perform on a list. So, let's define a list of numbers, here we pass a bunch of random numbers, like 5, 2, 1, 7 and 4. Now there are several things we can do with this list, we can add new elements to it. , we can delete existing elements, we can check the existence of an element, these are the operations we can perform on a list. In addition, we type numbers, we can see all these functions or, more precisely, the methods that are available in our list of objects.
Then we can call the append method to add a new element to this list. Let's say 13. Actually, no, that's not a good number. I'm joking, I'm not superstitious so let's add 20, it doesn't really matter and then print our list when we run the program, we can see 20 being added to the end of this list, but what if you want to add? A number somewhere in the middle or at the top of our list? For that we use a different method, which is called insert. So insert, now this method takes 2 values, let me show you. So when we open parentheses, look at this little tooltip above the insert method.
You see, the first value we need to pass here is an index, so this is the index where we want to insert this new element. Let's say we want to add an element to the beginning of our list, so we pass our index position of 0, and then the second value is the actual object we want to add to this list. Let's saywe want to add the number 10, now when we print this list you will be able to see that the number 10 is placed at the beginning of the list and all the other elements are pushed to the right.
We can also delete an element, so we call delete and we pass the element we want to delete to 5. Now we print our list so we see that 5 is gone and we have 2, 1, 7, 4. If you want to delete all the elements in the list, you can call the clear method, so this method doesn't take any value, so we just call it and it empties our list, all the elements are removed. We also have another useful method called hop, and with it we can remove the last element from a list. Let me teach you. So, we run our program, you can see that the number 4 is removed from the end of our list.
Now, if you want to check the existence of an element in our list, you can call the index method. So we call index and pass a value here, like 5, and this returns the index of the first occurrence of this element. So let's print this in the terminal. We don't need this line anymore. The index of 5 is 0. What happens if we pass a number that does not exist in this list? Let's say 50? Run the program, we get an error. We get a value error. 50 is not on the list. There is also another way to check the existence of an element: we can use the in operator.
So let me show you that we write our 15 in numbers, before we use the in operator with a string, we check for the existence of a character or a sequence of a character in a string, now here we are checking for existence. of 50 in the list of numbers, so let's print this, we get a boolean value, false, so unlike the index method, this expression does not generate an error, so it is safer to use this. We also have another method of counting the occurrences of an element, let's say we have another 5 here. Now we can call numbers.count and pass in 5 and this should return 2 because we have 2 5's in this list.看一看。你去吧That's pretty useful now if you want to sort your lists you can call the sort method.
Also, here we call the sort method, this method does not take any values, so look at the return value. that is, none, none is an object in

python

that represents the absence of a value. So this sort method doesn't actually return any value, it just sorts this list instead, so instead of printing the return value of its method, we just call it to sort our list and then print our list. , all items are stocked in ascending order. We can also sort the elements in descending order, so after sorting the list we can call the reverse method.
We can simply reverse our list. Now let's go ahead and run our program, let's take a look. Our numbers are arranged in descending order. And one last method that I want to show you here that is quite useful is to copy 方法。 So copy, with this method you can get a copy of our list. So let's define another variable called numbers 2, now numbers 2, which is a copy of our original list. If you make any changes to our original list, if you add new elements to it, if you delete existing elements, these operations are not going to affect our second list.
Let me teach you. So after showing you a copy of our list of numbers, let's add a new element to this list, so numbers.apphend 十。 So the first list is updated, now we have a new element in our first list, then let's print the second one. list. Take a look, we don't have number 10 here, because they are 2 independent lists. These are all the operations that we can perform on lists. We can add new elements to a list, we can delete existing elements, we can check the existence of an element, we can sort our list and copy them.
Now here is an exercise for this tutorial. I want you to write a program to remove duplicates from our list. Once again, this is a fantastic exercise. So spend a few minutes on this and then come back and continue watching. Alright, let's say we have a list of numbers with many duplicates. So 2, 2, 4, 6, 6, 3, 4, 6, 1. We want to eliminate duplicates. Then we need to define another list, let's call it new list. Initially we set it to an empty list. Then we need to iterate over our first list, get each element, and if we don't have that number in this Unix list, we'll add it to this second list.
As simple as that. So for the number between numbers, now we need to check if we have this number in the second list. So we use the in operator. If the number is not in units, then if we do not have an operator in this units list, then we will have to add it, i.e. units. add the number, that's all we have to do. So let's go ahead and print the drive list and that's it. So you have 2, 4, 6, 3 and 1. Duplicates are removed. In this tutorial I will tell you about another important structure. in Python it is called a tuple.
Tuples are similar to lists, so we can use them to store a list of elements. But unlike lists, we cannot modify them, we cannot add new elements, we cannot delete existing elements, tuples are immutable. We cannot mutate or change them. Let me show you. So, I'm going to start by defining a list of numbers, 1, 2, 3, 4, so we use square brackets to define lists and parentheses to define tuples, so if we change this to parentheses, 1, 2, 3. Now we have a tuple. So if we write numbers. Look here, we don't have the add or insert methods, so we can't add new elements to this tuple.
We also don't have remove clear and pop, we can't remove any of these elements here. We only have two methods, count and index. We use count to count the number of occurrences in an element and index to find the index of the first occurrence of an element. So we can only get information about a tuple, we can't change it. And by the way, these other methods you see here start with two underscores, we call them magic methods, they're a more advanced topic, so they're beyond the scope of this tutorial. If you are interested in learning about them.
You can get my Python course, I have covered them in detail. Similar to lists, you can address individual elements using square brackets, so we can get the first element this way and then print another terminal, there you have it, the first element is 1, but if you try to change the first element, it will. we get an error, so numbers of 0, we set it to 10 and run our program and that's it. We get this type of error because the tuple object does not support element assignment. So we cannot mutate or change tuples, they are immutable. In practical terms, you'll use lists most of the time, but tuples are useful too.
If you want to create a list of elements and ensure that there is no place in your program if you accidentally modify that list, then it is better to use a tuple. In this tutorial, I'll show you a powerful feature we have in Python called unpack. So let's find a tuple called coordinates and here we pass 3 values, 1, 2, 3. So imagine these are the coordinates for x and z. Now let's say we want to get these values ​​and use them in some expressions, some complex expressions in our program. We may want to include them as part of a large, complex formula.
So together we will have to write code like this, coordinates 0, then let's say we want to multiply this by coordinates 1, and then multiply it by coordinates 2, our code is getting too long, this is just a very simple example. But let's say we want to use these values ​​in quite a few places in our program, a better approach is to get these values ​​and store them in separate variables, like we can get the coordinates of 0, and store them in x, then you can get coordinates of 1 and store them in y . And similarly we get the coordinates of 2 and then store them in z.
Now we start repeating the coordinates of 2 or the coordinates of 0 several times, we can simply work with these variables, x by y by z, that's better.对? So nothing new so far. But in Python we have a powerful feature called unpack and with it we can achieve the same result with much less code. Then we can define our variables x, y and z. And set them to our tuple. What we have on line 6 is exactly identical to what we have on lines 2-4. So this is a shorthand for achieving the same result. Let me get this out of the way and explain how this code works.
When the Python interpreter sees this statement, it will get the first element of this tuple and assign it to the variable. Then you will get the second element of this tuple, then similarly we get the third element of this tuple and assign it to the third variable that we have here, so we are unpacking this tuple into 3 variables. Now, if we print x, you can see that x is 1, similarly, y is 2, there you have it. So this is unpacking. And by the way, this is not limited to tuples, we can also use this feature for lists.
Also, if I change the parentheses to square brackets, now the coordinates are a list, so we can decompress our list into 3 variables now we run our program we can see that y is 2. In this tutorial I am going to talk to you about the dictionary in Python. We use dictionaries in situations where we want to store information that comes as key-value pairs. Here is an example. Think of a client. A customer has a lot of attributes like name, email, phone number, address... Now each of these attributes has a value. For example, name can be jon smith, email can be [email protected], phone can be anything, so what we have here is a bunch of key-value pairs.
So in this example, our keys are name, email, and phone, and each key is associated with a value. So this is where we use a dictionary. With a dictionary, we can store a bunch of key-value pairs. Let me show you how to define a dictionary in Python. Going back to our program, I'm going to define a variable, customer, and here we set it in curly braces. With these keys we can define dictionary. In this example we have an empty dictionary that does not have any key-value pairs. Now we can add one or more key-value pairs between the braces.
So let's add a key-value pair here. I'm going to set the key to a name and the value to John Smith, then we add a comma to add another key-value pair. So, let's set the age to 30, add another underscore-checked key-value pair, and set it to a boolean value. Now what matters here is that these keys are unique. So if I add another key-value pair here, set the age to 40, now look, pycharm has highlighted the age key, because we've duplicated it and that's not allowed. So each key must be unique in a dictionary, just like the dictionaries we have in the real world, in a real dictionary we have a bunch of words and their definition, each word only appears once in a dictionary.
We don't have the word book twice. So let's remove the second duplicate key-value pair, so the keys must be unique and in this example I am using strings, but they can also be numbers, we will see that later, but the value can be anything, it can be a string, a number, a boolean, a list, literally anything. Now we can access each element of this dictionary using square brackets. So we type client, square brackets and then we specify a key as name and this will return the value associated with the name key. Let's print it in the terminal, let's take a look, there you have it, so the name is John Smith, now what happens if we pass in a key that doesn't exist, let's say the first quote?
You run the program and get a key error because we don't have a key called date of birth. Also, if we spell the name with, say, a capital N, we get the same error because we don't have a key with exactly the same sequence of characters in this dictionary. Now to fix this we can use the get method, so instead of using square brackets we call the get method and specify the key. Now, if you use a key that doesn't exist here, it doesn't yell at us. For example, if you pass the date of birth, it simply returns the value no.
Before I told you that none is an object that represents the absence of a value. Instead of getting a key error, we get none and we can also provide the option to provide a default value, for example, if this dictionary does not have this key, we can provide the default value, say January 1, 1980. Let's run the program now instead of getting none we get this default value. This is how we can access the value associated with the key in a dictionary. We can also update these values, for example, before printing a statement, we can write some code like this, name customer, let's update the name to jack smith, now this little warning tells us here that we can put jac smith here instead of define it once. and then update 它。 Don't worry about them, it doesn't really matter.
Now, with this line, if we print the name of this customer,We should watch Jack Smith, let me show you. So I'm going to use square bracket notation again, let's print the customer name which you can see is updated here, we can also add a new key here, let's set the date of birth to some value like January 1, 1980. And then we can print it here, so that, you see, we can easily add new key-value pairs to a dictionary. These are the basics of using dictionaries in Python. They are extremely important and have many real-life applications. Well, here's an exercise.
So here we have this program that asks for our phone number. We write 1 234. We write it in digits and then this will translate it into words, take a look. Enter, print, 1, 2, 3, 4. It's a very good program, so go ahead and spend a few minutes on this exercise, it's pretty easy, see you next. Alright, first we need to get the user's phone number, we call the input function with label phone, we get the result and store it in this variable, now let's say the user enters 123 4. So we need to check this. string, get each character and translate it to a world, then we need to implement this scenario.
It is a dictionary, because a dictionary is a structure that allows us to give a key to a value. So we can have a dictionary with keys like 1234. And we assign each of these keys to a word. So we can't put the digit 1 in word 1, we can assign 2 to two, you understand. So let's define a dictionary, you can call it digits, underline the mapping. Now to this dictionary I'm going to add some key-value pairs. First, we assign it to 1, 2, we assign it to 2, 3, 3, and finally, 4 to 4. Now, technically, we should add all the digits from 0 to 9, but I don't want to waste all the time. writing repetitive stuff here, you got the point.
So let's move on, now we need to check the phone chain. There are 4 characters in phone, we get each character and then use it to access a key-value pair in the dictionary. So for mapping underlined digits we can use square brackets or call get method, I would prefer to use get method, so that in case the user enters some character which is not part of our dictionary, our program will not shout at him. . So, we call the gt method and pass this character to the key, and if we don't have this key, we can provide a default value like an exclamation mark, so with this we get a word, now we need to add this word to an output string , so we can define an output string, we initially set it to an empty string, on each iteration we get this and add it to our output string.
So, we write output, plus equals. This and we should also add a space in get. So the words are not close to each other, okay? That's all we have to do. Now let's finally print this result, let's run our program, so I want to write 1, 3,4, 5, let's see what we get. We get 1, 3, 4 with an exclamation point. In this tutorial I will show you something really interesting that you can do with dictionaries, so here in this program you can write a message like good morning followed by a smiley face, when we press enter, we get this beautiful smiley face. , or we can write I'm sad, with a sad smiley face and it translates into this beautiful emoji.
So this is another application if we use dictionaries, we have a dictionary that maps these characters to smiley faces. So let's go ahead and build this program together, we start by calling the input function, here we pass a greater than symbol as a prompt for the user to type a message, we give him that message, we store it here, as you know, it's like this. a string, now we need to split this string by a space, so if the user types good morning with a smiley face, we want to split this into 3 words, good morning and a smiley face.
To do that we can call the split method. Then we call message.split and pass in a string with a space as a separator. What this method does is basically loop through this string and anywhere it finds this character, in this case a space, it uses it as a boundary to separate this string into multiple words. And then it will return a list. Let me teach you. So let's store that here, words, and then print it to the terminal, go ahead and run our program. So if you type good morning, sunshine, enter, we get a list with three elements, each element is a string, okay?
Returning to our program, we need to define a dictionary to assign special characters like these two to a smiley face. So, we can call those emojis, set it in curly braces, here we add a key-value pair, a smiley face, and assign it to a string, in this string we want to add an emoji, if you are on a Mac keyboard, you can press the control command and space bar and this should display this emoji box. Honestly, if you're on Windows, I really don't know how you can do this, but there must be apps that do this for you.
So let's go ahead and choose this happy face, okay, now let's add another key-value pair, or a sad face to which we assign this, this face here, okay. So, we have a list of words, now we need to go through this list, get each word and potentially assign it to an emoji. So we can write a for loop for word in words, now we want to go to our dictionary and see if it has an element with this word as a key. If you have an element with that key, we get its value; otherwise we want to use the same word.
So if a user types good morning, we don't want to translate those words, we just want to return them. So that's the case, where we use the get method to provide a default value, then we want to get an element with a keyword, and if we don't have an element with that key, we just use that word as the default value. Now, similar to the exercise we did in the last tutorial, we need an output variable. So let's define that here, let's set the output to an empty string, now let's go back to line 9, get the return value from the get method and add it to our output variable.
So the output plus is equal to what we get from the get method and finally we need to add a space at the end. That's it, we're done. So let's print the result and run our program and I'm going to type good morning sunshine with a smiley face, we get that beautiful, let's also try the sad face, I'm sad.太糟糕了。美丽!所以你可以看到 dictionaries have many use cases in real applications. Here is a solution from the last tutorial where we created an emoji converter. Until now we've been writing all of our code here in app,py, but as our programs grow we need a better way to organize our code.
We need to break our code into smaller, more manageable, easier to maintain chunks that we call functions. So function is a container for a few lines of code that perform a specific task, for example, you have learned about some of the built-in functions in Python like print and input, each of these functions has a purpose, they know how to perform them. a specific task. So when we create large, complex programs, we should break our code into smaller, reusable chunks that we call functions to better organize our code. And that's what I'm going to show you in this tutorial.
So, let's write this simple program to print a greeting message. So let's print, hello, and add another welcome aboard message. Here we have a simple program with only two lines of code. Now let's say we're potentially going to need these two lines in other programs so we can put them in a function that we can reuse. Let me show you how to do that, so we start typing death, which is a reserved keyword in Python and is short for define. When the Python interpreter sees this, it knows that we are defining a function. Next, we need to give our function a name, let's say greet_user.
So all the best practices you learned about naming your variables also apply here, which means we should name our functions with lowercase characters if there are multiple words, we should separate them using an underscore and you should always, always, always use words significant. descriptive names for their functions. So here we define a function called greet user, after that we will need to add parentheses followed by a colon. Now you know that every time we add a colon to the end of a line we are telling Python that we are defining a block of code. So when we press Enter, the next line is indented.
Now any code we write here will belong to this function. So I'm going to move these two lines, these two print statements inside our function. You can just press tab to indent them, beautiful, let's also remove this extra line break, that's better, so these two lines are now part of our user greeting function, so whenever we call this function, these two lines will be executed. Well, let's remove the indentation, so here we are outside of our function, let's make a print statement and start printing, then call our function, so say hello to the user. And finally let's make another create statement and finish printing.
Now we have this little warning here, this underline, if you mouse over this line, this tool was telling you that we need to add two blank lines after the definition of a function. This comes from pep8, which is a document that defines best practices for formatting our code. We will see it in the future. So for now, to make pycharm happy, let's add an extra line break to this function, so that every time we define a function we need to add two line breaks after it. Okay, now let's run our program and see what happens. Alright, so we have 4 messages in the terminal, first we get the start message, then we get the messages coming from our create function, so welcome aboard, and finally we see the finished message.
So let me explain the flow of our program, when Python executes this code, it doesn't actually print these two messages to the terminal because these two lines of code are inside this function, so they will only be executed if we call this function. If we do not call this function, these lines are not executed. So the execution of our program actually starts here, the first message we see in the terminal is the start message. After that, Python sees that we are calling the welcome function, so it will jump here and then execute these two lines. Then it will exit this function and continue the normal execution of our program so it will print the completion message in the terminal.
This is how the functions work. Also note that the order of this code is important, so here we call the welcome function after we have defined it. If you try to call it before defining it, you will see an error. For example, if we call the greet user function right here, we immediately get this red underline that says unresolved reference, greet user, which basically means that Python doesn't know what this greet user is, it's not defined anywhere . That's why we always define our functions first and then call them. Here is a function we created in the last tutorial.
Now I have a question for you: what is the difference between calling this function and Python's print function? The difference is that the print function takes some information, in this case the message we want to print, but our greeting function does not take any information. Wouldn't it be better if you could pass the user's name here and then instead of saying hello there, you could print the user's name? In this tutorial, I will show you how to pass information. to your functions, and that's pretty easy, so going back to the definition of our user greeting function, inside these parentheses, we can add parameters, these parameters are pale brackets for receiving information.
For example, you can add a name parameter and we can pass the name of the user when calling this function. So let's pass Jon here, now when we call this function and pass this value, this name parameter will be set to Jon. So it will act as a local variable that we define inside this function. Imagine, we didn't have this parameter and instead we had a variable as name that was set to jump. Now here we could just print the name of this user, so we could use a formatted string and print the value of the name variable, right?
We don't really have this local variable defined in this function, we have a parameter. , it's exactly the same. With these parameters we can receive information in our functions. Now let's go ahead and run this program, so let's take a look. We are welcomed aboard Hi John, can we take this to the next one. Now we cancall this function one more time. We greet the user and this time provide a different name. Let's say Maria. So we reuse our hello function and pass it a different value. Imagine if we didn't have this feature, you would have to repeat this line twice, once for hi jon and once for hi mary.
This is the benefit of defining functions, we can take a few lines of code that have a specific purpose and put them inside a function, so now let's run our program once again. So you get hello job, welcome aboard and then hello mary, welcome aboard. Now note that when a function has a parameter, we are required to pass a value for that parameter. So if you remove jon from here and run our program, we get this kind of error, greetings to the user, a required positional argument is missing. The argument in programming is the value that we provide to a function, so going back to this example, tying this case together is an argument that we pass to the name parameter.
And many programmers don't know the difference between parameters and arguments and think they are the same. But they are not, the parameters are the gaps or placeholders that we define in our function to receive information, the arguments are the actual information that we provide to these functions. Okay, so let's get this string back jon, now we can also define multiple parameters, for example, let's rename this parameter to name as I told you before, you can right click here, go to refactor and then rename, or Preferably you can use a shortcut. So the shortcut for this on Mac is shift and f6.
And this opens the renamed dialup box, here we can change it to the first underlined name. Now we can add a second parameter, so the comma followed by the underlined last name, so let's go back to our formatted string, let's also print the last name, beautiful, so when we call this function, we can provide another argument for Jon Smith and delete this. line, we don't really need it anymore, run our program, take a look, hello jon smith, so in the last tutorial you learned that whenever we define parameters for our functions we should always provide values, otherwise we will get an error.
Let's look at that error one more time. So I'm going to remove this second argument and just pass jon. Run our program, we receive this message, we greet the user who is missing a required position argument. So these arguments that you have here, like Jon and Smith's, you refer to them as positional arguments. Which means your position or argument matters. In other words, the first argument we add here is the value of the first parameter and the second argument is the value of the second parameter. So if you change their position or order, we will get different results.让我们来看看。 Let's move on to Smith first and then Jon.
Okay, okay, delete, now let's go with this, so instead of saying Hello Jon Smith, we get Hello smith jon. That is why we refer to these arguments as positional arguments, they are matters of position or order. But in Python we also have keyword arguments, and with them the position doesn't matter. Let me show you how they work. So let's say here you want to pass Jon as the value for the name parameter. We can simply specify that here. So the name is the same as jon. Now what we have here is a keyword argument. the argument keyword.
So this combination of having the name of the parameter, followed by its value is what we call a keyword argument, and what we get with this keyword argument, the position, doesn't really matter. So here we provide Jon as an argument for the first parameter. Now similarly we can use one keyword argument to smith so that last name is equal to smith so we have 2 keyword arguments. So with these keyword arguments we don't have to worry about the order of the parameters. That doesn't mean we should always use keyword arguments.并不是的。 Most of the time we use positional arguments, but in certain situations these directing keyword arguments improve the readability of our code.
So on line 7 it's pretty clear that we're providing smith as the last name and jon as the first name. Now, in this particular example, even if we didn't have the keyword arguments, simply passing two positional arguments like jon and smith would be enough, because it's easy to guess what the purpose of these arguments is. But sometimes you are dealing with functions and you are passing them numerical values, in those situations it may not be very clear what those values ​​represent. Let me show you an example. Let's say we have a function to calculate the total cost of an order, so we still call it calculate, underline cost, so when calling this function, you need to provide three pieces of information.
One is the total cost of all items in the order, say $50. The other one is the shipping cost, let's say 5 dollars, and the last piece is the discount, let's say 0, 0.1. Someone reading this code may not be sure what these three values ​​represent; In this case, we can improve the readability of this code by using keyword arguments. Therefore, we can prepend each value with the name of the parameter they point to, for example, we can set the total to 50 and then the shipping to 5, and then discount to 0.1. Now, if you give this code to someone else, they will be able to immediately know what these values ​​represent.
That's the power of keyword arguments. So this is what I want you to take away. For the most part, use positional arguments, but if you're dealing with functions that take numeric values, see if you can improve the readability of your code by using keyword arguments. Simply prepend the arguments you pass with the name of your parameters and this will increase the readability of your code. Now there is one more thing you should know about keyword arguments. These keyword arguments should always come after positional arguments.让我告诉你我的意思。所以, Going back to our simple function of greeting the user, let's use a keyword argument for the first thing.
So let's set the name to jon and see what happens. So we immediately get this error and the positional argument after the keyword argument. So when we call this function, we provide a keyword argument and a positional argument, and Python doesn't like this. However, if you are mixing positional and keyword arguments, you should always use and then keyword arguments. In other words, let's remove this keyword argument here, so jon is now a positional argument and points to the first parameter. Now after this positional argument, we can provide any number of keyword arguments, so if you set the last name to smith look, Python has no problem with this because we are adding a keyword argument after a positional argument.
So let's quickly recap, for the most part use positional arguments if you are dealing with functions that take multiple numeric values ​​and it is not very clear what those values ​​represent, use keyword arguments to improve the readability of your code and finally if you are passing Both positional and keyword arguments, use the keyword arguments after the positional arguments. So far you have learned how to create functions and send information to them using their parameters, in this tutorial I will show you how to create functions that return values, this is particularly useful if you are doing some kind of calculation in your function and want to return the result to whoever is using your功能。 let me show you.
So let's start by defining a function, called square, this function simply calculates the square of a number. So we need to add a parameter here, which is our number, now here we want to calculate the number multiplied by the number, which is the square of a number. Now, to return this color outside of this function, we simply use the return statement. So come back. Our square function is very simple, it only has one line of code. But in a real program, you may have a function that takes ten lines of code to calculate 一些东西。 Therefore, this return statement is very valuable.
So now we can return values ​​to the caller of our function. So with this, when we call the square function, let's say we give it 3, now this function returns a value, just like a Python input function, this input function waits for the user to type something and press Enter and then it will return the user input as a string so we can get it and store it in a variable like this, right? We have the same story with our history, with our square function. So our square function returns the value, we can simply get it and store it in a variable.
Let's call that result. Now, we can print the result in the terminal, there you have it, so the result is 9, we could also pass this function call directly inside the print function without defining a separate variable. Sometimes this is useful for writing shorter code, like in this case. So in this case, we don't really need this result variable. We simply want to print the square of 3. So we could simply pass this function call right here, as an argument to print 功能. So let's remove this variable now that our code is shorter, so with this we'll call the square function. , this returns a value and we will pass that value as an argument to the print function.
Example When we run this program, we get exactly the same result. Now what happens if we don't use a return statement in our function? So in the last example we simply use a print statement. Let's temporarily remove this return statement and print the result to the terminal.像这样。 So, let's run our program one more time and see what we get. We see two things, the number 9 and none. What's going on here? When the Python interpreter runs this code, it will first call the square function. Then the control moves to the square function here we calculate the square of this given number and then print it to the terminal.
That's the reason we see 9 here, now by default all functions return the value none. So if we don't have a return statement here, by default Python doesn't return any. This is an object that represents the absence of a value, it is like nothing or null ic, c++ java and Javascript. So in this example, we did not have a return statement and by default Python did not return any from this function. So after executing this square function, the value none is returned and passed as an argument to the print function, that is the reason we see none in the second line.
Here are the two things you should learn from this tutorial. By default, all functions in Python return none. You can change that, so that if you have a function that calculates something, you can return the result using the return statement. Here is the code for our emoji converter program that we wrote earlier. If you missed that tutorial be sure to go back and watch it, as I told you before there is a table of contents right below this video in the description. Then we can just click on the emoji converter tutorial to view it. Now, your exercise is to rearrange this code using a function.
So I want you to extract a function in this code, because this algorithm for converting these smiley faces into emojis is something that we probably want to use in a couple of different applications. We can use it in a chat application, in an email application, etc. We don't want to write all this code every time we want to turn these characters into smiley faces. So out of all these lines of code we have from line 1 to line 10, lines 10-2 belong to our algorithm, all these lines together implement this feature. So, you should put these lines in a separate function.
Now, why don't we have the input in this function? If the input can come in different forms, currently we are using the import function to receive the input from the terminal, but in other applications we can receive the input from a graphical user interface, so the input can come in different forms. We don't want to put that in our function, because this line will not be reusable. You want to give our function the actual message, like a string. We don't care how we receive that message. In one program you can get it from the terminal, in another program you can get it from a gui.
That is the reason why this alignment code should not be in that function. For the same function, you should not include the last line of that function because what we do with the output is different from program to program. In this program, we are printing the result to another program, you can send a result as an email or as a replyin a chat app, so as a general rule your function shouldn't worry about receiving data and printing it. he. These lines of code should not belong to your functions. So go ahead and reorganize this code by extracting a function.
Alright, at the top, we first need to define our function. So, first we write def, we give our function a name like emoji_converter, so that the name of this function clearly tells me what it does. Each role should be responsible for one and only one task, and that task should be clearly explained in the role name. So our emoji conversion function should take a parameter, we call that message, which is a string, right? Two points now we need to move lines 5 to the end of our for block in the function, so let's select all these lines, you can cut them from here, by pressing command y x on Mac, or control y x on Windows, then we paste it here, as you can See, these lines are auto-indented, so they are part of the emoji conversion feature.
If this didn't happen on your computer, be sure to select these lines and use the indent tab. them. Alright, here's our emoji converter feature. Now after that, in the main flow of our program, we first get the user input, store it in this message variable and then call the emoji converter and pass this message, this function should return a value, that's what we use to calculate the end of this function, so right after this block we need to add a return statement, return the output, now that our function returns a value, we can get it and store it in a separate variable, let's call that result and then We can just print it here, or we can shorten this code, we don't really need this code here, so we can just call the emoji converter and print the result.像这样。 Now here we have an underline because, as I told you before, we need lines in white after our function definitions.
So currently we only have one blank line, we need to add another black line, okay, let's go ahead and run this program and make sure everything works as before, so I'll write a message like "good morning" with a smiley face. Okay, let's run it one more time, multiplied by that, to add, okay, beautiful, so here's the final result, we define this function called emoji converter, this function takes a parameter called message. And finally returns the output. In this tutorial I'm going to teach you how to handle errors in your Python programs, so let's start by writing a small program to get the user's age from the terminal.
So we call the input variable input, and a label here, like age, this returns a string, so we need to pass it to the final function and store the result in a variable called age, now let's print the age to make sure it has We implement everything correctly we run our program we write 20, 20 is printed here, beautiful, now look at the exit code of this program, the exit code 0 means our program finished success

full

y, there were no errors, but what if we run this program? Once again, instead of entering a numeric value, we enter something like asd.
We received a value error with its literal message invalid for int with base 10. Basically, what this message tells us is that this asd string does not contain a valid starting number that can be converted to an integer. Now look at the exit code of this program, exit code 1 means our exit code failed, so 0 always means success and any value but 0 means failure. Now, as a good Python programmer, you must anticipate this situation. You don't want your entire program to fail just because the user entered an invalid value. So instead of letting the program crash, you should handle the situation and print a proper error message, and that's what I'm going to show you in this tutorial, now, before we look further into the type of error we get here , values ​​error, so remember this, we will come back to this shortly, how we can handle these errors, in Python we have a construct called try Accept and we use it to handle errors.让我告诉你它是如何工作的。 So in the top we write try: Now, as you know, we are defining a block of code, so I'm going to move these two lines inside our try block, so press tab here.
And delete this black line, now these two lines are part of our test block, right? So after trying, we type accept and then add the type of error that our program can encounter i.e. error value. Next, we add a colon and in this block we can define what should happen if our program encounters an error of type error value. In this case we want to print a proper error message, so print an invalid value. So with this try and accept, we are telling Python, hey, go ahead and try to run one or these two lines of code, if you encounter a type error.
Value error, so instead of crashing the program, try this error message in the terminal, that's how it works. Now, more precisely, in programming we refer to this type of error as an exception. So an exception is a type of error that crashes our program. So our user enters an invalid value, this line of code on line 2 will throw an exception, and on line 4 it will catch it and print this error message, so our program will no longer crash. Let me teach you. So let's go ahead and run this age 20, everything works the same as before and the exit code is 0, let's run this program again and enter asd, so we get this proper error message, invalid error menu and once again the exit code is 0.
That means our program completed successfully. It didn't fail, now we can also handle different types of errors or exceptions, for example, just when we get the age, define a variable income and set it to 20,000. And then define another variable called risk and set it to income divided by age. Let's run this program and enter 0 as a game to see what happened. So 0 is obviously a numeric value, so when we enter this value, technically we shouldn't get any exceptions.看一看。 Our program failed, we made a division error 0, because we can't divide a number by 0. Look at a again the exit code, so we couldn't catch this type of error or this type of exception with this acceptance. block.
The accept block only charges error exceptions of type value. And this happens when we try to convert a non-numeric value into an integer. So in a situation like this. We should handle different types of exceptions, we can add another except statement for a split error type 0 exception. Now in this block we can print a different type of message, like age cannot be 0. Let's run our program once again. I'm going to enter 0 as the age so we get this error message. Age cannot be 0 and Look at the exit code. It is 0, so our program did not fail, so to recap, we use try Accept blocks to handle exceptions that arise in our programs.
As a good programmer, you should always anticipate these types of exceptions and handle them appropriately. In this tutorial I will talk to you about comments in Python. We use comments to add notes or comments to our programs. For example, here I am going to make a printed statement, the sky is blue. Now before that, I can add a comment using a hello sign and then whatever we type here will be ignored and will not be executed. Let me show you, let's run this program, look, we only see this message. The sky is blue. So, with this comment we can explain something about our code, we can use it as reminders to fix or clarify things, or we can use it to communicate things with other developers who read our code, why we have written this code in a certain way.
These are good use cases for using comments, we can also have comments on multiple lines so we can simply add more comments, each line should start with a new hello sign. One thing you should avoid when using comments is explaining what the code does. Here is an example of a bad comment. Let me delete these two lines, and with this comment I'm going to say print the sky is blue. Is this a bad comment, because it tells me the obvious, it tells me that this slide will print the sky is blue? Now the problem with this comment is that, in addition to being verbose and repetitive, if you come here and change the sky for the ocean, now this comment becomes 过时.
So over time we change this code, then we have to go back and modify the corresponding comment. . I've seen some developers add comments in front of their functions, for example they define a function, say a square that takes a number and simply returns number multiplied by number. But it is obvious that this function calculates and returns the square of the given number. So there's really no need to add a comment and explain that. Calculates and returns the square of a number. This is very repetitive and creates noisier code. Someone else reading your code is distracted by all these unnecessary comments, so use comments to explain the whys and hows.
Not why, if you have made certain assumptions, we can use comments to explain those assumptions. Or we can use them to add notes to remind yourself or other developers to do something in the code. So comments are good, but too much of a good thing is bad. In this tutorial I will talk to you about classes in Python. Classes are extremely important in programming and are not specific to Python; in fact, many other programming languages ​​support the notion of classes. We use classes to define new types. For example, so far you have learned about the basic types of Python like numbers, strings and booleans, these are the basic or simple types in Python, you also learn about a couple of complex types like lists and dictionaries.
While these types are extremely useful, they cannot always be used to model complex concepts, for example, thinking about the concept of a dot or a shopping cart. A shopping cart is not a boolean, it is not a list, it is not a dictionary, it is a different kind of meaning. Then we can use classes to define new types to model real concepts. Now in this new model, I'm going to show you how to define a new type called point, and this new type will have methods for working with points. For example, let's go back to our main program.
Let's create a list, numbers, 1, 2, 3, you know that here, when we write that point, functions or methods available on the objects in the list, now similar to this, we are going to create a new type called point, this The point will have goals like move, draw, obtain, distance from another point, these are the operations that we can perform on the points. Let me show you how to do this. We start by defining a class using the class keyword, and immediately afterward we give our class a name. Now look at the naming convention I've used here. I have capitalized the first letter here, this is what we call pascal naming convention.
So the naming convention we use to name our classes is different from the convention we use to name our variables and functions. For variables and functions we always use lowercase letters and separate multiple words using an underscore. But when naming classes, we do not use an underscore to separate multiple words, but instead capitalize the first letter of each word. So in this case, our class has only one word, if it had multiple words, let's say the email client looks, I've capitalized the first letter of each word. Again, this is called the Pascal naming convention and comes from the old Pascal language that you may have heard of.
So let's go back to our points class. Here we add a colon which means we are going to define a block, now in this block we can define all the functions or methods that belong to dots, for example we can define a function called move to move a port, now note that so As soon as we type open parenthesis, pycharm automatically adds self here, this is a special keyword and we'll come back to this shortly. So for now, in this method, let's print move in the terminal, now let's define another method like draw, so let's define draw and in this method, let's print draw in the terminal, now let's remove the indentation, we are done with the definition of our class of points, so we need to add two line breaks, so with this class we define a new type, with this new type we can create new objects, so an object is an instance of a class, a class simply defines the plane or the template to create objects, and the objects are the actual instances based on that blueprint.
So we can have tens to hundreds of points on the screen, these are the objects or the instances. So to create an object, we write the name of our class and thenwe call it as a function, this creates a new object and then returns it. So we can store that object in a variable, let's call that dot 1, there you go, now that we use the dot operator. Look, we have these two methods that we defined, draw and move, we also have many other methods that we start with two underscores, these are called magic methods and we will see them later in the course.
Now, let's call the draw method of our point object and run our program so you can see that the drawing is printed in the terminal. Apart from methods, these objects can also have attributes and these attributes are like variables that belong to a particular object. For example, here, after you have defined .1. We can set .1.x to 10. And .1.1 to 20. Now we can easily print these attributes, let's print .1.x and run our program once again. Take a look, so the x coordinate of .1 is 10. Now we can create another object, let's call it .2 then .2 once again we write the name of our class and then call it as a function.
Now this object is completely different from the first object. So if you print .2.x, we get this attribute error, because this point object doesn't have an attribute called, so each object is a different instance of our point class. Now here we can assign a value to .2.x. Let's set that to 1 and then run our program so we can see that the x coordinates of .2 are 1. So to summarize, we use classes to define new types, these types can have methods that we define in the body of the class and also They can have attributes that we can configure anywhere in our programs.
You have learned how to create new types using classes. Now there is a small problem in this implementation. We can create a point object without an x ​​or y coordinate, let me show you. So, we create this object here, and before we set up point.x, let's print point.x, run our program, we get this attribute error that you saw in the last tutorial, so the point object doesn't have any attribute called x. This is the problem we have here, it is possible to have a point object without x or y coordinates. And that doesn't really make sense, because whenever we talk about a point, we need to know where that point is located.
To solve this problem, we use a constructor. A constructor is a function that is called at the time of creating an object. So here on line 9, when creating this point object, we want to pass in values ​​for the x and y coordinates, let's say 10 and 20, and with this, this point object that we get here will have its x and y coordinates initialized. So how do we do this? We need to add a special method in this class called constructor. So at the top I define a new function, I look at the name of this function, double underscore init, double underscore.
So init is short for initialized and this is the function or method that is called when we create a new point object. Now press Enter to have this added automatically, self in parentheses. We will return to this shortly. Now, right after self, we want to add 2 additional parameters, x and y, so let's write x and y, and then in the body of this method, we need to read the above values ​​here and use them to initialize our object. , then when we pass 10 and 20, these arguments will be used for the x and y parameters. Now, to initialize our object, we write our code like this.
Self.x is equal to x. And then self.y is equal to y. What's happening here, this self that you see here is a reference to the current 宾语. So, going back to line 13, when we create a new point object, the self references that object in memory, the same object that we are referencing using this cariable. So before we wrote point.x is equal to 10, with this code we set the x attribute of this point object. Now what we have in the constructor is exactly the same, we use self to reference the current object and then set the x attribute for the x argument passed to this function.
Also, using this init method, we can initialize our objects and We refer to this method as constructor, this method is used to construct or create an object, okay? So now let's delete line 14, so we create a point object with these values ​​and then print point.x. Let's run our program and voila, x is 10, we can also change these values ​​later, so just before printing point.x. We can set point.x to 11 and then run our program so that x updates, beautiful, okay, here's an exercise. I want you to define a new type called person. These person objects must have a name attribute as well as a conversation attribute.
This is a very easy exercise, so you can tackle it in probably a couple of minutes. Alright, first we start with a class keyboard, define this person class once again. Look at the naming convention I've used here, the first letter of the first word, in this case the only word is capitalized. Now in this class we define all the methods we need, currently we only have one method which is the talk method, so we define talk, pycharm automatically adds self, we will come back to this shortly, for now let's just print talk. This is the body of our person class.
We remove the indentation and add two line breaks after defining our classes. Now we can create the person object, let's call it jon, we set it to person, we can call jon. Talk, let's run the program so that we receive this message, beautiful, but our person objects must also have a name attribute, there is no point in having a person without the name. So that's when we use the constructor function. So at the top we add a new method, in the name of this method there is double underscore, init double underscore.所以我们 calls this constructor method. Now in this method we need to add another parameter which is name so we just set self.name as name.
Again, self refers to the current object, we are setting the name attribute of the current object, to the passed name argument. to this method. With this we can go back to line 9, and when creating a person object we pass the name, let's see jon smith now let's print jon.name and run our program there you have it. So Jon Smith is printed on the terminal, beautiful, so this is all you had to do as part of this exercise. Let's make this program a little more interesting. Instead of printing this boring message here, let's print Hi, I'm Jon Smith.
So we can use a string formatted with a message like Hello, I'm, now we want to dynamically add this person's name. How do we do this? Well, look at the parameter of this conversation method. As I told you before, each method of our class must have this parameter, self. And they should be the first parameter of each method, okay? With this self we can get a reference to the current object, so we can add curly braces and write self .name. This returns the name attribute of the current person object. With this we can remove line 10, where we print jon.name and simply call jon.talk.
Let's run our program. Hi, I'm Jon Smith. There we go, beautiful. Now we can construct another person object, let's say Bob, it's a new person called Bob Smith, when we say Bob.talk. And when we run our program, we receive a different message. Hi, I'm Bob Smith, so each object is a different instance of a Person class. In this tutorial I am going to talk to you about inheritance in Python, inheritance is a mechanism for using code and once again it is not limited to Python, most languages ​​that support classes also support inheritance. So let us know how this works.
Let's say we have this dog class with a simple walk method, in this method we are simply printing the walk message to the terminal, now let's say in a real program, instead of just one line of code here we are going to have 10 lines of code. Now, what if in the future we want to define another class, say cat, and we want to add this walk method there too? Then we will have to repeat all that code, in this new class, walk.这是不好的。 because it has repeated or duplicated our code. In programming we have a principle called dry, which is short for don't repeat yourself.
Let's say that at some point in the future we discover a problem with our walking method. If we have repeated or duplicated this method in many other places, then we will have to go back and fix that problem in each place where we have duplicated this code. . That is why in programming we should not define something like that. So how can we solve this problem? There are different approaches, one that is easier for beginners to understand is inherence. Now this is how it works. We define a new class called maml and move the walk method right there.
We will then make the dog and cat classes inherit that method from their parents, just as humans inherit certain attributes or behaviors from their parents. That's exactly the same thing, so at the top we define a new class, let's call it mammal, and then we need to move the walk method there. Then we select it, we cut it, using the command y x on Mac, or control x on Windows and then paste it here, beautiful, now we want our dog class to inherit this class from the mammal class, so right after the name of the class we add parentheses and then write the name of the main class.
In this case, mammal. That's all we have to do. So, with your dog class you will inherit all the methods defined in the mammal class. Now there's a little problem here, if you look at line 9, there's a red underline here. The reason this happens is because Python doesn't like empty classes, so right now our dog class is empty, it doesn't have anything, or we need to add dog-specific methods or just to make Python happy, we can use the path declaration, and that basically means nothing. We're telling the Python interpreter, hey, pass this line, don't worry. But with this, we don't have an empty class, okay?
Now, as I told you before, after each class you should have two line breaks, so now we only have one line break and that's the reason we have this little warning here, so let's add another black line, beautiful, so our dog class is When inheriting the mammal's walk method, you must apply the same change to the cat class. So we'll make the cat inherit from the mammal and then we'll use the path declaration here. With these changes, we can now create a dog or cat object, let's say dog, one, we configure it as a dog object, and when we write dot look we have the walk method that is defined in the mamall class.
We can easily call it, let's run our program, there you have it, you will see the walk message, so both the dog class and the cat class inherit all the class methods defined in their parent class. Now here we can add dog specific methods, for example we can define a method called bark and then print bark. Now, we don't need the route declaration because we already defined a method in our dog class. Now when we write dog1. Look, we have two methods, one is the walk method that we inherited and the bark method that we just defined in the dog class.
Similarly, we can add a specific method for a cat, for example, we can define a method called being annoying, I hate cats, so let's print annoying, now when we create the cat object, let's remove that, cat1 and write cat1. . You have these two methods, dog and you are annoying. These are the basics of inheritance in Python. Now there is more to this that is really beyond the scope of this beginner tutorial. If you are interested in learning more about inheritance and other mechanisms for reusing code, I encourage you to get my complete Python course. In this tutorial, I will tell you about modules in Python.
A module in Python is basically a file with some Python code. And we use modules to organize our code into files. Like sections in a supermarket. When you go to a supermarket there are different sections of fruits, vegetables, cleaning products, etc.我们没有 a section with all the supermarket products. We have the same concept in programming. So instead of writing all of our code, instead of writing all of the functions and classes in app.py, we want to split our code into multiple files. We refer to each file as a module. With this, not only will our code be better organized and structured, but we will also have the ability to reuse it.
For example, here in app.py, I defined two functions to convert weight from pounds to kilograms and vice versa. Now we can take these two functions and put them in a separate module called converters, and then we can import that module into any program that needs these conversion functions. Let me show you how to do this. So let's open our project panel and right click on the project, go to new and add the new file, we'll call it converters.py. Then we go back to app.py, select all of this code, cut it, and then paste it into our new module. converters.py.
With this we have cleaned up the module of our application, it is not packed with different functions, so asstart from package.module and then import a specific function. How to calculate shipping. So, these were the basics of using packages in Python. As I told you before, packages are extremely important, especially when you want to work with a framework like Django, we use Django to create web applications with Python, and I will show you that later in this course. So in Django we have quite a few packages and each package contains several modules. So make sure you watch the modules and packages tutorials once again, otherwise you will get confused later when we get to Django.
In this tutorial I am going to tell you about the built-in modules in Python, so Python comes with a standard library that contains several modules for common tasks like sending emails, working with date and time, generating random values ​​and passwords. etc. There are so many modules already built into Python and that means there are already a lot of functions that we can reuse. Let me show you where you can find this standard library. So open this browser and search for

python

3, module index, be sure to add the version number, because modules in python 2 are different from modules in python3.
So here we look for the Python 3 module index, and the first page here, you can see is the Python module index, or Python 3, let's move on, these are all the modules built into Python, for example, we have modules to work with date and time, we have modules for sending emails to encode values, there are many modules here. Now the explanation of all this is beyond the scope of this course, which really requires its own course. Because we have a lot of modules here, but don't let this list intimidate you. This is not something you need to learn right now, as you learn Python and create more applications, you will gradually become familiar with more modules here;
In fact, no one knows all the modules in the Python standard library. Everyone knows some modules based on the applications they have created. So in this tutorial, I'll show you how to use one of the built-in modules to generate random values. So at the top, we import the random module. Now, because random is a built-in module, we don't need to have a file here called random.py. So the Python interpreter knows that random is a built-in module as long as it knows where to find it. Now, if you're curious about where this random module is stored on disk, let me show you, so here in the project panel, expand external libraries, then expand Python 3, and then once again the Python 3.7 library path.
So this is a folder somewhere on your computer, in this folder we have all the built-in modules in Python. If you scroll down you should be able to find them. The random module.你去吧它就在这里。 So random. py. You can open this and it will show you the source code of this module. There you go. Now, in this tutorial, we don't want to worry about that, so let's go back to our app.py and use this module to generate random values. So when we import this module, we now have this object, random, so we can use the dot operator to access its methods.
One method that is useful here is the random method, and every time we call it it generates a random value between 0 and 1. So here we can do a for loop, say for I in range 3. So just to refresh your memory we are using the range function to create a range object. We can look through this range object and on each iteration this object will return a value. So with this for loop, we can run this code 3 times. Now, let's bleed this. Okay, and finally, let's print the result, so we can see that in each iteration we get a new random value between 0 and 1.
Now, what if we want a random value for a particular age? Let's say random values ​​between 10 and 20, well there is another method here, rand int, here we use 2 arguments to specify our range, let's say 10 and 20. Run our program once again. Now we have the numbers 20, 13 and 18. If we run our program once more, we get different values, so 20, 19, 11, once again. Look, you also have another powerful method to randomly select an item from a list. Let's say we have a list of team members and you want to choose someone at random as a leader. Let me show you how to do it.
So, we define the list of team members, we set it as jon, mary, bob and mosh. Now we can call .choice random and pass in our list of members. This method randomly selects a method from this list and returns it. So, we can store the result in leader and then print it to the terminal. let's run our program, so now the leader is Mary, if you run our program one more time, this line is mosh now it's mosh again one more time, you really like mosh, you get the point. The random module is very powerful. and it has many applications.
Now here is a very interesting exercise. I want you to write this program to roll a dice. So every time we run this program we get a different value. Now we have 3 in 1, next time we get 3 and 6, once again 5 and 6, 4 and 3, double one, that's a great exercise. Before we begin, I want you to pay attention to a few things. I want you to define a class called dice. In this class we are going to have a method called string, so every time we call this method, we get a tuple. Remember that a tuple is a list of values, but the values ​​cannot be changed.
We can't add a new element to it, we can't remove it. So it's like a read-only list. So whenever we call the row method, we should get the tuple of two random values. So go ahead and do this exercise. You will see my solution below. Alright, we start by importing the random module at the top, then we define a class called dice: In this class we want it to have a method called row. So define row parenthesis, this is added automatically, now in this method, you want to generate two random values ​​between 1 and 6. So we call random.randint.
And pass in 1 and 6. So this generates the first number, we can write it here, now let's call this one more time, so I'm going to copy what we have on line 5, put it here and change this variable to second. So we have two variables first and second. With two random values, we eventually need to return them, in a tuple, so return parentheses instead of square brackets, first and second, now in Python when you want to return a Python from a function, you don't have to add this. parentheses, so you can simplify your code and Python will automatically interpret it as a tuple.
We are now done with the definition of our class, we removed the indentation and added two line breaks. Now we create an object of this type for you to configure dice by dice. Then we roll the dice, so say.roll and print the result to the terminal, that's all you have to do. Let's run this program, so now we have 2 and 5, let's run it one more time, 3 and 2, 1 and 1, beautiful. Now we have this little warning here, saying that expected 2 black lines found 1. Again, this comes from pep 8, pep is short for python and proposal. We have so many Python improvement proposals or peps.
Pep 8 is a very famous 1 and in this document we have all the best practices to format our code. So pep 8 says that after defining our classes we should have 2 line breaks, we have already done that, so the reason this is complaining is because we had 1 line break before the class, so let's add a line break. line more, now Pycharm is happy. Basically pycharm follows all the best practices defined in pep8. Now you don't have to memorize any of these best practices, as you code in pycharm, pycharm gives you a little more warning and gradually you'll learn how to properly format your code so that other people can read it.
In this tutorial, I'll show you how to work with directories in Python. So here in python3, module index, you can see that we have a module called lib path that provides an object-oriented file system pact. Basically, that means that it provides classes that we can use to create objects to work with directories and such. So if you click here, you can see how this module works, we can see all kinds of examples. For example, here about basic usage, you can see how we import the route class from the route lib module. Let me zoom in so you can see clearly.
Okay, look, from the lib path, that's our module, import path, note the naming convention. P is capitalized, that means the path is a class, so we need to create an instance of this class as you can see, right here, now there's so much documentation here, you can read this on your own, but let me show you quickly. Some examples to help you get started. So after pycharm at the top, from the route module, the route class is imported. Now we need to create a path object to reference a file or directory on our computer. Basically, there are two ways to do this: we can use an absolute path or a relative path, which basically means a path starting from the current directory.
For example, if we want to reference this e-commerce directory in our project, we can use the relative path. So we start from the current directory and then go to another place. With absolute paths we start from the root of our hard drive. For example, if you're on Windows, you might have an absolute path like this, c drive, backslash, program, files, backslash microsoft, so these are directories on the c drive. In Windows we use a backslash to create a path. If you're on Mac or Linux, your paths will look a little different, so instead of backslash we have a forward slash, say user/local/bin.
These are examples of absolute paths. In this tutorial we are going to work with the relative path to work with this e-commerce directory that we have in our project. Now, if you didn't create this directory before, just right click on the project and then go to the new directory. Oak? So let's close this panel, create a path object, now if you don't pass an argument here, this will reference the current directory, alternatively we can pass a string, in this string we can add a file or a directory. Let's say the eCommerce directory. Now this runs a route object, so we store it here.
Now this route object has some interesting methods, for example we can check if a route exists by calling the existence method. This simply returns a boolean value, so let's print it to the terminal and that's it. So this path exists, what if it changes to eCommerce 1, we run our program and it becomes false? We can also create a new directory, for example, let's change our path to email. Now, when we run this program, we obviously don't. We have this directory but we can create it by calling the mk dir method to create the directory. Let's run our program okay, this method does not return any which basically means it does not return any value.
Now if you look at the project panel you can see here that we have a new directory called emails, we can also delete this directory so instead of mk dir we call rmdir which is short for delete directory but let's move on now We can see that the directory has disappeared. We can also see all the files and directories in a given path, that's very useful if you want to write a small program to automate something. For example, you can iterate over all the spreadsheets in a directory and process them. Let me teach you. We first change the path to the current directory and then call the balloon 方法.
With this method we can search for files and directories in the current path. So, as the first argument we need to pass a string that defines a search pattern. We can type an asterisk and that means everything, all files and all directories. Optionally, we can add an extension, so to get all the files, you need the files that the star.star.有了这个 pattern uses, we will only get the files in the current directory. But not the directories. We can also search for all py files, or all Excel spreadsheets. Anything. So let's find all the py files in the current directory, now when we run our program we get this generator object.
Spawn objects are a fairly advanced topic and are beyond the scope of this beginner's Python course. But for now all you need to know is that we can iterate or loop through these generator objects. So instead of printing this generator object, let's iterate over it using a for loop, so that, we archive the generator object that is returned from the glob method. q Let's print the file. We run our program, there you have it. These are all the py files in my current directory, this might be different on your machine if you didn't follow the exercises I gave above.
For example, this utils.py, we created it as part of one of the previous exercises in this course. So don't worry ifthe files you see here are different on your machine. So, you can use the global method to search for files using a pattern, we can also get all the files and directories in the current path, so, we just use an asterisk, then we run our program, take a look, so we have In this directory of ecommerce, we have notes.txt, this is a file that I added earlier just to write notes as part of my presentation, so you won't have this file.
We also have a lot of directories and files. Although the Python standard library is complete and has so many modules for common tasks, it is by no means complete. That's why we have this directory called Python Package Index. Or pee. And in this directory you can find hundreds of packages to do amazing things. These are packages that people like you and I have created as part of our projects and then published them as part of this directory. For other people to use. That's why we have a fantastic community in Python, there are so many Python developers out there and there are so many packages right in front of us to reuse in our programs, let's say you want to send text messages in your programs, we don't have to create this functionality from scratch, we can simply go to pypi.org and search for sms.
As you can see, there are many projects or packages that provide you with this functionality. Of course, not all packages, not all projects are complete or bug-free, some of them are still in

development

or have bugs, but if you look around, I'm pretty sure that for any kind of feature you can imagine , there is a good and reliable one. and well documented package for you. In my complete Python course, I'll show you some of the most useful pypi packages. Plus, you'll learn how to access Yelp.com information in your programs. So you can write a program and search for businesses registered on Yelp.
Let's say you want to look for the best barber 在纽约市. I'll show you how to do it. You'll also learn how to use a technique called web scraping, which means you can create an engine and have that engine scan a website and extract information from HDML files. This is the same technique that Google uses to index multiple websites. So they have several engines, or web crawlers, these web crawlers continuously search various websites and extract information from their pages. When you publish a blog post, Google's web crawler finds the title of your post, its keywords, etc. extremely powerful, because it can automate testing of your web applications.
So, you might get a job as a test engineer and your daily job is to browse a website, click here and there, fill out this form, that form, and make sure this website works properly. You can automate all of that with a powerful Python package called Selenium, as I've shown in my complete Python course. Now, in this tutorial, I will show you how to install packages, from pypi.org.所以, here at pypi.org let's search for open py xl. This is a package we use to work with Excel spreadsheets. So let's find this.package, there you go, so it's currently at version 2.5.
At the top you can see this instruction pip install open pyexcel. This is the command we need to type in the terminal window to install this package in our program, so let's go back to pycharm, here in the status bar. You can open a terminal window to run various commands. So let's open it up, now if you're on Windows you'll probably see something different instead of this dollar sign, don't worry about that, just run this command that I'm going to show you. So pip install open py xl Make sure you write everything correctly. So, pip is the tool that comes with a Python installation and we use it to install or uninstall packages registered on pypi.org.所以在这里, we are using pip to install this package. open py xl.
Come in, let's go ahead with that, it'll take a few seconds, done, now we can import this package and its modules just like the built-in modules in Python, or the modules that we have in our project. Now, if you're curious about where this package is stored on disk, let me show you. So open the project panel and then expand external libraries, then expand Python 3 and then expand visual packages. This is where all these packages that we installed with pip are stored. So here we have open py xl, you can open this, in this folder we have another folder called cell, now, look what we have here you have this type of startup, before I told you that every time we add this file to a folder, Python treats that folder as a package, so sell is a package and this package we have are modules.
Sell, interface, read-only and text. As you can see, this openpyxl package has several subpackages like cell, home, chartsheet, etc. And in each package we have several modules, in the next tutorial I will show you how to work with excel files. We have covered all the basics of Python, I hope you learned a lot. Please support my hard work by liking this video and sharing it with others. And be sure to subscribe to my channel for more tutorials like this. Next, we will work on our first Python project that involves automation. You're going to write a Python program that can process thousands of spreadsheets in less than a second.你兴奋吗?让我们开始吧。 In this tutorial I'll show you something really amazing you can do with Python.
You will learn how to process spreadsheets, and this is extremely valuable in situations where you have hundreds or thousands of spreadsheets that need to be updated. If you want to do this by hand, it can take hours or days, weeks or even months; You can simply create a Python program in less than half an hour. And have that Python program automatically process thousands of spreadsheets in less than a second. So here we're going to work on this Excel spreadsheet. You can download it below this video. In this spreadsheet we have three columns, Transaction ID, Product ID and Press.
Now don't worry about the fourth column yet. So in this spreadsheet we are going to record all types of transactions, but let's say because of an error, it could be a human error or a system error. The price we have here is wrong. Let's say we need to decrease this by 10 percent. If you want to do this manually, we'll have to come back here and add a formula, so we type in the equals sign, let's say you want to recalculate, let's say you want to recalculate the value of this cell. We have to get that and then multiply it by 0.9 and that's like 90% of the original price, we're reducing the original price by 10%.
Now, when you press Enter you will be able to see the updated price. Next we will need to come back here, select this cell and apply the same formula to all the other rows. Now what happens if you have thousands of rows here? You will have to scroll up and down, this will be very tedious. So let's write a Python program that will do this for us. Automate this process and not only that, it will also add this beautiful chart right here, again if you want to open hundreds or thousands of spreadsheets and add a chart to each one, this will take at least a week or two.
Our Python program will do all this in a matter of seconds. Then let's get started. Alright, the first thing I want you to do is download this transactions file and add it to your project. I leave you the link below this video so you can download it. So if you're wondering how to put this in this project, you can simply right click on the project and if you're on Mac, you have this item where it's revealed in the finder; If you're on Windows, you should see something like reveal. in explorer, or file explorer, or whatever it's called, when you click here, it opens the shortcut to your machine where it's stored.
So just copy and paste the transaction file right here. Here at the top, we first need to import the open py excel package. So import open py excel, we can give it an alias to shorten our code. So asxl. This is not necessary, but it simply makes our code a little cleaner. Let me teach you. So now instead of writing open pyxl. we write xl. Okay, so that's an alias for this package. Now in this package we have a function to load an xl workbook. So let's call load workbook and as an argument, pass transactions. .xlsx.
So we load our Excel workbook and return a workbook object.好的? Now if you open this workbook, you can see that it adds only 1 sheet, and it is called sheet 1, so to access it you have to use square brackets and Specify the name of the sheet, which is sheet one, be sure to write this with a capital S. Because this is case sensitive, if you don't type it correctly you will get an error, so this returns a sheet, now in this sheet, we have multiple cells. You need to learn how to access a particular cell, and that's very easy.
Back to py charm, with this sheet object, you can use square brackets and give the coordinate of a cell. The coordinate is the combination of the column and the row. For example, the coordinate of this cell is a1. So going back to pycharm, we can type a1 and this returns our first cell. Also, there is another approach to get a cell, instead of using square brackets with a string, we can use the cell method of the sheet object, so, sheet.cell, you pass the row and column, then row and column 1 these return exactly the same. Now let's print the value of this cell, cell.value and run our program so that the value is the transaction id, beautiful, so now we need to iterate over all these rows and for each row we need to get the value of the third column.
That's the price. We'll get that and then multiply it by 0.9. First we need to know how many rows we have in this spreadsheet. We can get that from the leaf object, so the leaf has an attribute called mx_行. Let's print this, so on this sheet we have 4 rows, and you can check that here. So we have a total of 4 rows. Then we need to add a for loop. that would output the numbers 1 to 4. So let's remove this print statement and add a for loop for the row. We are going to use the range function to generate a range of numbers, starting from 1 to the sheet. max_grow.
Plus 1. The reason we add 1 to this is because, as I told you before, this range function will generate numbers, starting from this value to this value, but it will not include the second value. So currently the max row returns 4, if you use the range 1 to 4 this will output the numbers 1, 2 and 3 but not 4. So to include 4 we need to add 1 to it. Let's review here so we join the row sheet underline.max plus 1. Now before we continue, let's print the row and make sure our program is working up to this point. So let's run this, we get beautiful numbers from 1 to 4.
Now we can easily get the cells of the third column. We don't really want this first cell, that's the header. so technically you want to ignore the first row. Back here, you want to change our range function and start from 2. Now, we'll use sheet.cell to access the cell in this row. And the column should be 3. We get a cell object, let's print its value and make sure it's on the right path, so run the program, these are the values ​​we get. 5.95 6.95 and 7.95 these are the values ​​in the third column. Then we need to multiply each value by 0.9 so instead of printing cell.value we multiply by 0.9 and this is the corrected underline price, so this is the mistake we are going to make with our program, now we need to add a new cell to our sheet working, so we want to add all the corrected prices i.e. a new column, you could also overwrite the values ​​in this column, but in this tutorial I will show you how to add a new column.
So using the same method, now we need to get a reference to the cell, to the given row, but in the fourth column. So, we call sheet .cell and pass row and four as arguments. Again, this returns a cell object, let's store it in a separate variable and call it cell_price. Please note that my variable names are very descriptive. There is no need to make guesses. You have corrected the price that contains the actual value and we have corrected the price, which is a cell object in this spreadsheet. Next we have to set the value in this cell.
Then we set the corrected price cell. value at this corrected price. With these few lines we can easily update our spreadsheet, but first we must save it. After our for loop, we call workbook. save. Now let's save this to a new file because we don't want to accidentally overwrite the original file in case our program has an error, so I'm going to call it transactions 2.sms ex. And finally let's run our program, so, you can see it happened in a split second, now here we have a new file transactions 2. When we open this we get something like this.
As you can see, we have this fourth column with the updated prices.美丽。 Sohalf of the problem is solved, now we need to add a graph here. To add a chart, we need to add a couple of classes on top, so after this import statement, let's write from open py excel.chart, import, bar chart, comma, reference. So let's see what's going on here. In this package you have a chart module and from this module we are importing two classes, a bar chart and a reference. Again, note the naming convention used 这里。 The first letter of each word is capitalized.
It's also best to add a line break after our import statements to make our code cleaner. So before saving our workbook, we need to add a chart to the current sheet. First we need to select a range of values. For this exercise, I will select the values ​​in the fourth column/. So all the values ​​in rows 2 through 4 are the values ​​I will use in our chart. Now in this example from part 2, it doesn't really make sense to add a chart per transaction, but that doesn't really matter, we just want a bunch of numbers to create a chart, so after our for loop, let's use the class reference to select a range of 值。 Now the first argument in the constructor is sheet.
So we pass our sheet here, then we add 4 keyword arguments, the first one is min_row, we set it to 2. The second one is max_row, we set it to the maximum row in this sheet. That's the sheet, .max_row, so we want to select the cells in rows 2-4. OK? Now, to make this code a little cleaner, I'm going to put this on a new line, so we can see clearly, now this will select all the cells in all the columns of these rows. values ​​in the fourth column, so here we need to set a couple of keyword arguments plus men_call or column, we set it to for, and also max underscore call, we set it to 4 as well.
So we are limiting the range of cells we select to the fourth column. Now, we are creating an instance of the reference class, let's store the result in a variable called values, so this values ​​object will have all these values ​​in the fourth column, now we are ready to create a chart, so we create an instance of the bar chart class and save it in this object. Next, we call chart.add_date and pass in our values. That's pretty simple, finally we need to add this box to our sheet. So, we call the sheet, .add_chart and pass in this chart object.
We also need to specify where we want to add this graph. Let's say we want to add it here, in row 2, after the fourth column. So the coordinate of this cell is e2, and this will be the top left corner of our graph. So as the coordinate I'm going to pass e2, that's all we had to do, done. Let's run our program one more time, beautiful, let's open the update book. And here is the final result, just after the fourth column, we have this beautiful graph. Now we could take this to the next level, we could add a legend here, we could change the color of these bars, we could even use a different type of chart, it doesn't have to be a bar chart.
So to learn more about this we can read the openpyxl documentation. Our program is complete, because our code is dirty, it is not clean, it is not organized. We don't have any function here. We have written all the code in app.py. So let's go ahead and organize this code like a professional software developer. So on line 4, we are loading our workbook and then we get a reference to the first sheet, but we don't really need these two lines here, this is purely a demonstration to show you how to access a cell. let's remove these unnecessary lines, this is a very important practice since you are coding, always look at your code, always review it, see if you have any code that is not used.
Always delete them. Well, next we iterate over all the rows, set the prices, then select the values ​​to add a chart and finally save the workbook. Now, if you were to use this to automate the process of updating thousands of spreadsheets, this program would not work because it only depends on this file. So we want to rearrange this code and move it inside a function. This function must take the name of a function. So, define a function. Let's call it process_workbook. Gets a file name. Now, we move all the code inside this function, so let's select everything and press tab, beautiful, now let's go back to our function, instead of loading this transactions file, we're going to load this file name, that's better.
Also, now that our program is working correctly, there's really no need to store the result in a separate file. So here we can just overwrite the same file. So let's pass in the file name, that's the end of our function, so now we have this reusable function, we can just reuse it to process thousands of spreadsheets. Earlier in this Python course, you learned how to find all files in a directory, so we can get every file in a directory and pass the file name to this function, this function will go ahead and update this spreadsheet in just a second . or less.
So, that was just one example of using Python to automate boring, repetitive, time-wasting tasks. But automation is not just about processing Excel spreadsheets, there are many things we can automate. Here's a question: what do you want to automate? How do you want to use Python to make your life easier? Use the comment box below and let me know. I love hearing your ideas. Next, we will work on a project that involves machine learning, which is a subset of artificial intelligence.你兴奋吗? 让我们开始吧。 In this section, you will learn about machine learning, which is a subset of AI or artificial intelligence. .
It is one of the trending topics in the world these days and will have many applications in the future.这是一个例子。 Imagine that I ask you to write a program to scan an image and find out if it is a cat. or a dog. If you want to create this program using traditional programming techniques, your program will become too complex. You'll have to create a lot of rules to create specific curves, edges, and colors in an image to tell if it's a cat or a dog. But if I give you a black and white photo, your rules may not work, they may be broken.
Then they would have to be rewritten. Or I can give you a picture of a cat or dog from a different angle that we didn't predict before. Therefore, solving this problem using traditional programming techniques will be too complex or sometimes impossible. Now to make things worse. What if I ask you to extend this program to support 3 types of animals? Cats, dogs and horses, once again you will have to rewrite all those rules. That's not going to work. So machine learning is a technique for solving these types of problems, and this is how it works. We build a model or an engine and give it a lot of data.
For example, we give you thousands or tens of thousands of photographs of dogs and cats. Our model will then find and learn patterns and input data, so we can give it a new image of a cat we haven't seen before. And ask it if it's a cat, a dog or a horse and it will tell us with some level of precision that the more input data we give it, the more accurate our model will be. That was a very basic example, but machine learning has other applications in self-driving cars, robotics, language processing, vision processing, forecasting like stock market trends and weather, gaming, etc.
That's the basic idea about machine learning. Next we will see machine learning in action. A machine learning project involves a series of steps, the first step is to import our data, which often comes in the form of a csv file. You may have a database with a lot of data, we can simply export that data and store it in a csv file for our machine learning project. So we import our data and then we need to clean it. And this involves tasks such as data duplication. If you have duplicates in the data, we don't want to feed this to the model, because otherwise our model will learn wrong patterns in our data and produce wrong result, so we need to make sure our input data is in a good and clean shape .
If there is data that is irrelevant we need to delete it, if it is duplicate or incomplete we can delete or modify it, if our data is text based, like the name of countries, or music genres, or dogs and cats, we need to convert it to values numeric. So this step really depends on the types of data we are working with, each project. Now that we have a clean data set, we need to split it into two segments. One to train our model and the other to test it, to make sure our model produces the correct result.
For example, if you have 1,000 photographs of dogs and cats, we can reserve 80% for training and another 20% for testing. The next step is to create a model, and this involves selecting an algorithm to analyze the data. There are many machine learning algorithms, such as decision trees, neural networks, etc. Each algorithm has advantages and disadvantages in terms of accuracy and performance, so which algorithm you use depends on the type of problem you are trying to solve and your input data. Now, the good news is that we do not have to explicitly program an algorithm, there are libraries that provide these algorithms, one of the most popular, which we will see in this tutorial, is lateral learning.
So we build a model using an algorithm, then we need to train our model. Then we feed it our training data. Our model will then look for patterns in the data, so we can then ask it to make predictions. Going back to our cat and dog examples, we can ask our model if it is a cat or a dog and our model will make a prediction. Now, prediction is not always accurate, in fact, when you start, it is very likely your predictions. They are inaccurate. That is why we need to value predictions and measure their accuracy.
We must then go back to our model and select a different algorithm that produces a more accurate result for the type of problem we are trying to solve. Or adjust the parameters of our model. So each algorithm has parameters that we can modify to optimize accuracy. These are the high-level steps that are followed in a machine learning process. Next, we will look at libraries and tools for machine learning. In this lecture we will also look at the popular Python library that we use in machine learning projects. The first is numpy and provides a multidimensional array. A very, very popular library.
The second is pandas, which is a data analysis library that provides a concept called data framework. The data frame is a two-dimensional data structure similar to an Excel spreadsheet. So we have rows and columns, we can select columns in a row or a column or a range of rows and columns, again, very, very popular in data science and machine learning projects. The third library is mad plot lib, which is a two-dimensional plotting library for creating plots on plots. The next library is Sidekick Learn which is one of the most popular machine learning libraries that provides all these common algorithms like decision trees, neural networks, etc.
Now when we work with machine learning projects, we use an environment called Jupiter to write our code; Technically we can still use vs code or any other code editor, but these editors are not ideal for machine learning projects, because we need to inspect frequently. the data, and that's really difficult in environments like vs code and 终奌站. If you are working with a table with 10 or 20 columns, viewing this data in a terminal window is really difficult and complicated, which is why Use Jupiter. That's why we use Jupiter, it makes it really easy to inspect our data. Now to install Jupiter, we will use a platform called anaconda.
Then, head over to Anaconda.com/download. On this page you can download the Anaconda distribution for your operating system, so we have distributions for Windows Mac and Linux. So let's go ahead and install Anaconda for Python 3.7. Download, Alright, here is Anaconda, download it to my machine, let's double click here. Very good, you will first run a program to determine whether the software can be installed. So let's continue and once again, pretty easy, continue once again, I agree to the license agreement, we can use the default location, you can use the default installation location, so don't worry aboutthat, just click install, hit In a few seconds, now the beautiful thing about Anaconda is that it will install Jupiter, as well as all those popular science data libraries like numpy, Pandas, etc.
Therefore, we don't have to install this manually using pip. Okay, now as part of the next step, Anaconda suggests installing Microsoft vs code. We already have this on our machine, so we don't have to install it, we can go ahead and close the installation, now we can finally move this. to the trash because we will not need this installer in the future. Okay, now open a terminal window and type jupiter, with oh, space, notebook. This will start the portable server on your machine. So come in there you have it. This will start the laptop server on your machine, we can see these default messages here, don't worry about them, now it automatically opens a browser window, pointing to local host port 888.
This is what we call Jupiter panel. In this panel we have a few tabs, the first tab is the files tab and by default it points to your home directory. So each user on their machine has a home directory, this is my home directory on Mac, you can see here we have a desktop folder as well as documents, downloads, etc. On your machine you will see different folders, so somewhere on your machine you will need to create a Jupiter notebook. I'm going to go to the desk, here's my desk. I don't have anything here and then I'll click new.
I want to create a notebook for Python 3. In this notebook we can write Python code and execute it line by line. We can easily visualize our data as you can see in the next videos. Let's go ahead with this, okay, here is our first notebook, you can see that by default it is called untitled, let's change it to Hello world, so this will continue. be the hello world of our machine learning project. Let's rename this now. If you look at your desktop, you can see this hello world.ipynb file. This is a Jupiter notebook. It's somewhat similar to our py files where we write our Python code, but includes additional data that Jupiter uses to run our code.
So let's go back to our notebook, print hello world. And then click this run button here and here is the result printed in Jupiter, so we don't have to navigate back and forth between the terminal window, we can see the entire result.就在这儿。 Next, I'll show you how. to load a dataset from a csv file into Jupiter. Alright, in this lecture we are going to download a data set from a very popular website called caggle.com. Caggle is basically a place to do data science projects. So the first thing you need to do is create an account, you can sign up with Facebook, Google or use a custom email and password, once you sign up, come back here at caggle.com, here in the search bar. look for video game sales.
This is the name of a very popular data set that we will use in this lecture. Here in this list, you can see the first item with this kind of reddish icon, so let's get on with that, however I can. Check out this data set that includes sales data for over 16,000 video games. In this page you can see the description of various columns in this data set, we have rating, name, platform, year etc, so here is our data source, it is a csv file named vg sales.csv, as you can see . There are more than 16,000 rows and 11 columns in this data set.
Just below you can see the first records of this data set. So here is our first record, the rating of this game is 1, it is the wi sport game for wii as a platform and it was released in the year 2006, now what I want you to do is go ahead and download the data set. , and as I told you before, you must log in before you can download it. This will give you a zip file as you can see here, here is our csv file. Now I want you to place this right next to your Jupiter laptop, on my machine that's on my desk, so I'm going to drag and drop. this in the desktop folder.
Now, if you look at the desktop, you can see here is my Jupiter notebook, Hello World, and right next to it we have vgsales.csv. With that, we go back to our Jupiter notebook, delete the first line and instead import pandas as pd. With this, we are importing the pandas module and renaming it to pd, so we don't have to write pandas. several times in this code. Now let's write ps. read_csv. And pass the name of our csv file. That's vgsales. csv. Now, because this csv file is in the current folder right next to our Jupiter notebook, we can easily upload it; otherwise we have to provide the full path to this file.
So this returns a data frame object which is like an Excel spreadsheet. Let me teach you. So we store it here and then we can just type df to inspect it. So once again, let's run this program. Here's our data frame with these rows and these columns so we have the platform name Frank, etc. Now, this data frame object has a lot of attributes and methods that we're not going to cover in this tutorial, that's really beyond the scope of what we're going to do, so I'll let you read it. pandas documentation or follow other tutorials to learn more about pandas data frames.
But in this lecture, I will show you some of the most useful methods and attributes. The first is the shape, so let's run this one more time, so here is the shape of this data set, we have over 16,000 records and 11 columns. Technically, this is a two-dimensional array of 16,000 and 11, okay? Now we can see that here we have another segment to write code. So we don't have to write all the code in the first segment so here in the second segment we can call one of the data frame methods i.e. df.describe. Now when we run this program we can see the result of each segment right next to it.
Here is our first segment, here we have these three lines, and this is the result of the last line. Below we have our second segment, here we call the describe method, and just below we have the result of this segment. This is the beauty of Jupiter, you can easily visualize our datsa, doing this with vscode on Windows is really tedious and clunky. So what does the description method return? Basically it returns basic information about each column in this data set. So as you saw above we have columns like range, year etc. These are the columns with numerical values.
Now, for each column we have the count, which is the number of records in that column. You can see that our sort column has 16.5 -98 records, while the year column has 16.3 - -27 records. This shows that some of our records do not have the value for the year column. We have null values. So, in a real data science or machine learning project, we will have to use some techniques to clean our data set. One option is to delete records that do not have a value for the year column. Or we can assign them a default value.
That really depends on the project. Now another attribute for each column is the mean, so this is the average of all the values. Now in the case of the rank column, this rank doesn't really matter, but look at the year. So the average year for all of these video games in our data set is 2006. And this could be important in the problem we're trying to solve. We also have the standard deviation which is a measure to quantify the amount of variation in our set of values, below that we have min, as an example the minimum value for the year column is 1980.
Very often when we work with a new data set, we call the describe method to get some basic statistics about our data. Let me show you another useful attribute. So in the next segment, let's write df.values. Let's run this, as you can see, this returns a two-dimensional array, this bracket indicates the outer array and a second one represents an inner array. So the first element of our outer array is an array itself, these are the values ​​of this array, which basically represent the first row of our data set. Then the video game that we occupy position 1, which is called Wii Sports.
This was a basic overview of pandas data frames. In the next lecture I will show you some of Jupiter's useful shortcuts. In this lecture, I'll show you some of the most useful shortcuts on Jupiter. Now, the first thing I want you to pay attention to is this green bar on the left. This indicates that this cell is currently in edit mode, so we can write code here. Now, if we press the Escape key, the green turns blue, and that means that this cell is currently in command mode. Basically, the activated cell can be in edit mode or command mode.
Depending on the mode, we have different shortcuts, so here we are in command mode. If we press h, we can see the list of all the keyboard shortcuts, just above this list we can see the Mac OS modifier keys, these are the extra keys on a Mac keyboard. If you are a Windows user, you will not see them. As an example, here is the shape of the command key, this is control, this is option, etc. With this guide you can easily understand the shortcut associated with each command. Let me teach you. Here we have all the commands when a cell is in command mode.
For example, we have this command, open the command palette. This is exactly the same as the command palette we have in vs code. Here is a shortcut to run this command. That's command shift and F. Okay, we have a lot of shortcuts here, of course you won't use them all all the time, but it's good to take a quick look here to see what's available to you. With these shortcuts you can write code much faster. Let me show you some of the most useful ones. I'm going to close this, now with our first cell in command mode, I'm going to press b and this inserts a new cell below this cell.
We can also go back to our first cell, press escape, now the cell is in the command 模式。 We can insert an empty cell above this cell by pressing a. So a or b. A up or b down. Now, if you don't want this cell, you can press d twice to delete it.像这样。 Now in the cell I'm going to print a hello world message. So print hello world. Now, to run the code in this cell, we can click on the Run Here button, so here is our print function, and just below you can see the output of this function.
But keep in mind that when you run a cell, this will only run the code in that cell. In other words, code in other cells will not be executed. Let me show you what you want, I mean, in the cell below the cell, I'm going to remove the call to a description method. Instead, I'm going to print 海洋. Now, I'm going to place the cursor back in this cell where we printed this hello world message and I'm going to run this cell. So we can see that hello world is displayed here, but the cell below still displays the description table, so we don't see the changes here.
To solve this problem, we can go to the cell menu at the top and run all the cells together. This may work for a small project, but sometimes you are working with a large data set, so if you want to run all these cells together, it will take a long time. This is why Jupiter saves the result of each cell. , so we don't have to rerun that code if it hasn't changed. So this notebook file we have here includes our source code organized into cells, as well as the output for each cell. That's why it's different from a normal py file where we only have the source code.
Here we also have autocomplete and intelligence, so in this cell, let's call df data frame. Now, if you press tab, you can see all the attributes and methods on this object. So let's call describe, now with the cursor on the method name we can press Shift and Tab, to see this tooltip that describes what this method does and what parameter it takes. So here in front of the signature you can see the method description, these are the parameters and their default value, and right below that you can see the description of what that method does. In this case, it describes, generates descriptive statistics, which summarize the central tendency, etc.
Similar to vs code, we can also convert a line to a comment by pressing command-slash on Mac, or control bar on Windows.像这样。 Now that that line is a comment, we can press the same shortcut one more time to remove the comment. , these are some of the most useful shortcuts on Jupiter. Now, in the next few lectures we are going to work on a real machine learning project, but before we get there, let's delete all the cells here, so we start with just one empty cell, so here, in this cell, first I'm going to press the Escape button, now the cell is blue, so we are in command mode and we candelete the cell by pressing d twice.
Now, the next cell is activated and you are in command mode. So let's delete this as well, so we have two more cells to delete, there you go, and the last one, like this, so now we have an empty notebook with a single cell. In the next lectures, we will work on a real machine learning project. Imagine that we have an online music store, when our users register, we ask them our age and gender and, based on their profile, you recommend various music. albums they are likely to buy. So in this project you want to use machine learning to increase sales.
So, we want to build a model, we feed it with some sample data, based on existing users. Our model will learn the patterns in our data, so we can ask it to make predictions. When a new user signs up, we tell our model, hey, we have a new user with this profile, what is the type of music this user is interested in, our model will say jazz, hip hop or whatever. and based on that we can make suggestions to the user, this is the problem we are going to solve, now let's go back to the list of steps in machine learning projects, first we need to import our data, then we need to prepare. or clean it, then we select a machine learning algorithm to build a model, we treat our model and ask it to make predictions.
And finally, we evaluate our algorithm for its accuracy. if it is not accurate, we adjust our model or select a different algorithm. So let's focus on the first step. Go to bit.ly/music.csv. This is a very basic csv I created for this project, it's just some random made up data that isn't real. So we have a table with 3 columns, age, sex and gender. The gender can be one that represents a man or a 0, which represents a woman. I'm making some assumptions here. I guess men between 20 and 25 like hip hop. Men between 26 and 30 years old like jazz, and after 30 years old, they like classical music.
For women I suppose that if they are between 20 and 25 years old they like dance music, if they are between 26 and 30 years old they like acoustic music, and like men, after 30 years they like classical music. Again, this is a made up pattern, it is not the representation of reality, so let's go ahead and download this csv. Click this icon... here and download this file. In my downloads folder, here we have this music.csv. I'm going to drag and drop this onto the desktop because that's where I saved this Hello World notebook. So I want you to place this csv file right next to your Jupiter notebook.
Now back to our notebook, you need to read the csv file, so as before, we need to import the pandas module first, so import panda as pd. And then we'll call pd, .read_csv and the name of our file is music.csv. As you saw above, this returns a data frame that is a two-dimensional array similar to an xl spreadsheet, so let's call it music_数据. Now let's inspect this music_data to make sure we load everything correctly to run it, so here's our data frame, beautiful. , then we must prepare or clean the data. And that is the topic of the next conference. next conference.
The second step in a machine learning project is to clean or prepare the data, and that involves tasks like removing duplicate null values, etc. Now, in this particular data set we don't have to do any kind of cleaning, because we don't have any duplicates and as you can see, all the rows have values ​​for all the columns, so they don't have null values. But there is one thing we need to do: we need to split this data set into two separate data sets, one with the first two columns, which we refer to as input set, and the other with the last column which we refer to as the output set.
So when we train a model, when we train a model, we give it two separate sets of data. The input set and the output set. The results set, which in this case is the gender column, contains the predictions, so we tell our model that if we have a user who is 20 years old and male, he likes hip hop. Once we train our model, we give it a new set of inputs. For example, we have a new user who is 21 years old and male, what is the genre of music this user probably likes. As you can see from our set of inputs, we don't have a sample for a 21-year-old man, so we'll ask our model to predict him.
That is the reason why we need to split this data set into two separate sets. Input and output So, going back to our code, this data frame object has a method called drop. If you put your cursor on the method name and press Shift and Tab, you can see this tooltip, so this is the signature of this drop. method, these are the parameters you can pass here. The parameter we are going to use in this lesson is set to none by default. With its part we can specify the columns we want to remove, so in this case we set the columns to an array with a string, now this method doesn't actually modify the original data set.
In fact, it will create a new data set but without this q call. So by convention, we use a capital X to represent that data set, so capital x is equal to this. Now, let's inspect x, so you can see that our input set or x includes these two columns, age and gender, not having the result or the predictions. Next we need to create our output array, once again we start with our data frame using data, using square brackets we can get all the values ​​in a given column. In this case, gender. Once again, this returns a new set of data.
By convention we use a lowercase y to represent that. So that's our result. Let's inspect it too. In this data set we only have the predictions or the answers. So we have prepared our data, next we want to create a model using an algorithm. The next step is to build a model using a machine learning algorithm. There are so many algorithms out there, each algorithm has its pros and cons, in terms of performance and accuracy. In this lecture we are going to use a very simple algorithm called a decision tree. Now the good news is that we don't have to explicitly program these algorithms, they are already implemented in a library called side kick learn.
So here at the top, from sklearn.tree let's import the decision tree classifier. So, sklearn is the package that comes with the add-on learning library, this is the most popular machine learning library in Python. In this package, we have a module called tree. And in this module we have a class called decision tree classifier. This class implements the decision tree operator, okay? So now we need to create a new instance of this class. So in the end, let's create an object called models and configure it to a new decision instance, tree classifier. Now that we have a model, we next need to train it to learn patterns in the data, and that's pretty easy.
You call the model, .fit, this method requires 2 sets of data. The input set and the output set. So they are x, y capital letters. Now, finally, we need to ask our model to make a prediction, so we can ask it: what kind of music does a 24-year-old man listen to? Does he like it? If we do that, let's temporarily inspect our initial data set.那是 music data. So, look what we have here. As I told you before, I assumed that men between 20 and 25 years old like hip hop music, but here we only have 3 samples for men between 20, 23 and 25 years old.
We don't have a sample for a 21-year-old man. . So if you ask our model to predict the type of music a 21-year-old man likes, we expect him to say hip hop. Similarly, I assumed that women between the ages of 20 and 25 like dance music, but we don't have a sample for a 22-year-old woman. So once again, if you ask our model to predict the type of music a 22-year-old woman likes, we expect her to say dance. So with these assumptions, let's go ahead and ask our model to make predictions. So let's remove the last line and instead call the .predict model.
This method takes a two-dimensional array. So here is the outer array. In this array, each element is an array. So I'm going to pass another array here, and in this array I'm going to pass a new input array. a 21 year old male. So 21, 1 is like a new record in this table.好的?所以, this is a set of entries, let's pass another entry for a 22-year-old woman. So here is another matrix, here we add 22 point 0, so we ask our model to make 2 predictions. Then we get the result and store it in a variable called predictions, and finally let's inspect that in our notebook.
Run, look what we have, our model says that a 21 year old man likes hip hop and a 22 year old woman likes dance music. So our model will make successful predictions here. But wait a minute, building a model that makes predictions accurately isn't always that easy. After building a model, we need to measure its accuracy. And if it is not accurate enough, we should adjust it or build a model using a different algorithm. So in the next lecture I will show you how to measure the accuracy of a model. In this lecture, I'll show you how to measure the accuracy of your models.
Now, to do this, we first need to split our data set into two sets. One for training and the other for testing, because right now we are passing the entire data set to train the model and we are using 2 samples to make predictions. This is not enough to calculate the accuracy of a model. A general rule of thumb is to write down 70-80% of our data for training and another 20-30% for testing; then instead of passing only two samples to make predictions, we can pass the data set for testing and we will get the predictions and then compare the predictions with the actual values.
On the test set. Based on that, we can calculate the precision. That's really easy, all we have to do is import a couple of functions and call them in this code. Let me teach you. So first in this top part of the sklearn.model underline selection module, we import a function called train test split. With this function we can easily split our data set into two sets. So, training and testing, now, right here, after defining the x and y sets, we call this function, so train the split test. We give it 3 arguments, x, y, and a keyword argument that specifies the size of our test data set.
So test _size we set it to 0.2. Therefore, we allocate 20% of our data for testing. Now this function returns a tuple, so we can decompress it into 4 variables 就在这儿。 x_train x_test y_train and y _test. then the first two variables are the input sets for training and testing. And the others are the output sets for training and testing. Now, when training our model, instead of passing the entire data set, we want to pass only the training data set. So x_train and y_train. Also, when making predictions instead of passing these two samples, we pass x_test.
So that's the data set. Contains input values ​​for testing. Now we have the predictions. To calculate accuracy, we simply have to compare these predictions with the actual values ​​we have in the result set for the test. That's very easy. First at the top, we need to import a function, so from sklearn.metric .metrics import precision _score. Now at the end. We call this function, so we score the precision and give it two arguments y_test. Which contains the expected values ​​and the predictions which contain the actual value. Now this function returns a precision score between 0 and 1.
So we can store it here and just display it in the console. So let's go ahead and run this program. So the accuracy score is 1 or 100%, but if we run this one more time, we will see a different result because every time we split our data set into training test sets. We will have different data sets, because this function randomly selects data for training and testing. Let me show you, so place your cursor in the cell, now we can see that this is activated. Note that if you click this button here, it will run the cell and also insert a new cell below this cell.
Let me teach you. So if I go to this second cell, I press the skip button, now we are in command mode, I press d twice, okay, now it is deleted, if we click on the run button, we can see that this code was executed and now we have a new cell, so yesyou want to run our cell multiple times each time you have to click here and then run it, and then click again and run it, it's a bit tedious. Then I'll show you a shortcut. Activate the first cell, press control and enter, this runs the current cell without adding a new cell below it.
So back here, let's run it a few times. Now look, the accuracy was reduced to 0.75, still good, so the accuracy obtained here is between 75% and one hundred%. But let me show you something, if I change the test size, from 0.2 to 0.8, we are essentially using only 20 percent of our data to train this model. And you're using the other 80% for testing. Now let's see what happens when we run this cell multiple times. So check and enter, look, the accuracy immediately dropped to 0.4 Again, now 46% 40%, 26% is really, really bad. The reason this happens is because you are using very little data to train this model.
This is one of the key concepts in machine learning, the more data we give to our model and the cleaner it is, the better results we will get, so if you have duplicate data, irrelevant data or incomplete values, our model will learn again. patterns in our data. That is why it is very important to clean before training our model. Now let's change this back to 0. 2, run this one more time, okay, now the precision is 1.75%, now we go down to 50% again, the reason this happens is because we don't have enough data. . Some machine learning problems require thousands or even millions of samples to train the model;
The more complex a problem is, the more data we need. For example, here we are only dealing with a three-column table, but if we want to build a model to know if there is an image of a cat, a dog, a horse or a lion, we will need millions of images. The more animals it supports, the more images we will need. In the next lecture, we will talk about model persistence.所以这是一个 very basic implementation of building a training model to make a prediction. Now, to keep things simple, I removed all the code you wrote in the last lesson to calculate precision, because in this lesson you will be focusing on a different topic.
Basically, we import our data set. Create a model, train it, and then ask it to make predictions; Now, this code snippet you see here is not what we want to run every time we have a new user or every time we want to make recommendations to an existing user. sometimes it takes a long time. In this example, we are dealing with a very small data set that only has 20 records. But in a real application, you might have a data set with thousands or billions of examples, and training for it can take seconds, minutes, or even hours.
And that's why model persistence is important: from time to time, you build and train our model and then we save it to a file. Now, the next time we want to make predictions, we simply load the model from the file and ask it to make predictions. That model is already trained, you don't need to retrain it, it's like an intelligent person. Let me show you how to do this. It's very very easy. At the top, from the sklearn.externals module we import joblib. This job lib object has methods to save and load modules. Also, after training our model, we will simply call job lib .dump and give it two arguments.
Our model and the name of the file in which we want to store this model. Let's call this music -recommender.job lib. That's all we have to do. Now I'm temporarily going to comment out this line, we don't want to make any predictions, we just want to store the train model in a file. So let's run this cell with control and forward slash, okay, look, in the result we have an array that contains the name of our model file. So this is the return value of the dump method. Now back to our desktop, right next to my laptop we can see our working library file, this is where our model is stored.
It is simply a binary file. Now let's go back to our Jupiter notebook. As I told you before, in a real application we don't want to train the model every time. So let's comment on these few lines: On Mac, we can press command and slash and on Windows control slash. Okay, these lines are commented out, now this time, instead of dumping our model, we are going to load it, so we call the load method, we don't have the model, we just pass the name of our model file. .这个 returns our trained model. Now with these two lines we can simply make predictions, so before, we assumed that men between the ages of 20 and 25 like hip hop music. let's print predictions and see if our model is behaving in a way that we control, that's how we persist and load the models.
Earlier in this section I told you that decision trees are the easiest to understand. And that's why we started machine learning with decision trees. In this lecture, we are going to export our model in visual format, so you can see how this model makes predictions, that's really cool. Let me teach you. So once again I have simplified this code so that we simply import our data set, create input and output sets, create a model and train it, that's all we are doing, now I want you to follow me and write everything exactly. as I show you in this conference.
Worry about what it all means, we'll get back to that shortly. So at the top, of the sklearnimport tree, this object has a method to export our decision tree in graphical format. So after training our model, let's call the tree _graph vis. Now here are some arguments we must approve. The first argument is our model, the second is the name of the output file. So here we are going to use keyword arguments, because this method takes a lot of parameters and we want to pass keyword arguments selectively without worrying about their order. Also, we're going to set the out_file parameter, we're going to set it to music. -recommend .period.
This is the point format, which is the graph format, which is a graph description language, you'll see that shortly. Now the other parameter you want to set is the _names characteristic. We set this to an array of two strings, age and gender. These are the features or columns of our data set. So they are properties or characteristics of our data.好的? The other parameter is the class names. So class_names we should set this to the list of classes or labels that we have in our output dataset, such as hip hop, jazz, classical, etc. So this data set includes all the genus or all the classes of our data, but they are repeated several times in this data set.
So here we call y.unit, this returns the unique list of classes, now we need to sort this alphabetically. So, we call the sorted function and pass the result to y.unique. The next parameter is labeled, we set it to a string, everyone, once again, don't worry, about the details of these parameters, we will come back to them shortly. Then set the label to all and then round. , to true and finally the field to true. So this is the final result, now let's run this sound using control and enter, okay, here we have a nw file music recommender... that's a bit of fun.
So we want to open this file with vs code. So drag and drop this into a vs code window. Well, here's a point format, it's a texture language for describing graphics. Now, to display this graph, we need to install an extension in vs code. So on the left side, click on the extensions panel and look for dot dot. Check out this second extension here. Graphvis or Stephon's .language vs. Go ahead and install this extension and then reload the vs code. Once you do that, you will be able to view this point file. So let me close this tab.
Alright, look at this... on the right side. Click here, you should have a new menu, open the preview next to it. So, all right, here's our decision tree visualization, let's close the point file and that's it. This is exactly how our model makes predictions. So we have this binary tree, which means that each node can have a maximum of two children. Above each note we have a condition, if this condition is true we go to the child node on the left side. Otherwise we go to the child node on the right side. So let's see what's going on here, the first condition is an age less than or equal to 30.5.
If this condition is false, it means that the user is 30 years old or older, so the genre of music they are interested in is classical. So here we classify people according to their profile. That's the reason we have the word class here, so a user aged 30 or older belongs to the classical music class. Or people who like classical music. Now what happens if this condition is true? That means the user is under 30 years old, so now we check the gender, if it is less than 0.5, which basically means it is equal to 0, then we are dealing with a female.
So we go to the child node here, now once again we have another condition, so we are dealing with a woman under 30 years old. Once again we need to check her age, is the age less than 25.5 years? If that is the case then that user likes dance music, otherwise he likes acoustic music. This is a decision tree that our model uses to make predictions. Now, if you're wondering why we have these floating point numbers like 25.5, these are basically the rules that our model generates, based on the patterns in our data set. As we feed more data to our model, these rules will change, so they won't always be the same.
So they are not always the same, and the more columns or characteristics we have, the more complex our decision tree will become. We only have two characteristics, age and gender. Now, coming back to our code, let me quickly explain the meaning of all these parameters. We set the field to true so that each frame or each node is filled with a color. We set rounded to true, so they have rounded corners. We set label on everything so that each node has labels that we can read. We set class names for the unique list of genders, and that's to show the class for each note, right here, and we set feature names for age and gender, so we can see the rules in our notes.
That was a nice short introduction to Machien learning. Now you can use the materials you learn in this section and apply them to solve a different set of problems. Now here's a question: What ideas do you have for machine learning? What kind of problems do you want to solve with machine learning? Use the comment box below and let me know. I love hearing your ideas! Next we will use Python and a popular framework called Django. To build a web application. Are you ready? Let's get started. In this tutorial, I'll show you how to create your first website with Python, A, and a very popular framework called Django.
So it is written with a silent D and pronounced django. It's a web framework for perfectionists with deadlines. So if you are a perfectionist and want to quickly create a website that is fast, scalable and secure, Django is your best friend. And here are the popular websites built with Django. Like Instagram, Spotify, YouTube, Washington Post, etc. Now you could say what is a framework and why we need a framework to create a web application or a website. Well, the framework is essentially a library of reusable modules. These modules provide functionality for common tasks, for example, in the case of a web framework like django, we have modules for working with http request URLs, sessions, cookies, etc.
These are the concerns of virtually every website or app out there. So all this functionality is built into Django, we don't have to code it from scratch, that's why we use a framework like Django.现在, Django. Now, technically a framework is more than a library, in addition to providing these modules, it also provides a structure for each application. It tells us what folders or files we should have in our project. So this provides consistency between multiple Django projects. So as you move from one company to another and work on different projects, you can easily move from one project to another, because all these applications follow the same structure now, with that interaction, let's create our first Django project.
So let's go back to pycharm, close the hello world project and create a new project, create a new project, let's call this new project pyshop, go ahead, okay, now at the bottom let's open a terminal window, in this window Let's install Django. So we use pip to install django. But make sure you add two equal signs here followed by 2.1. With this we are telling pip that we want to install version 2.1 of Django. The reasonWhy I'm doing this is because in the future, when you watch this video, there will likely be a newer version of Django. I want to make sure you can follow these tutorials easily, although what I do What I'm going to show you in these tutorials will probably work with the latest version of Django.
I just want to be on the safe side. So let's move on, django is installed, then we need to create a django project, so here press control and L this clears our terminal window, it doesn't have to, but it's easier to see. To create a Django project, we need to run this command, django, -admin space start project space, you will call this project pyshop space period. So when we install django, django comes with a command line utility called django admin, so this is a utility or program that we can run from the command line or terminal, right here.
Now, this program takes several arguments, in this case we want to use this argument to start the project, with this we are going to create a project called pushup in the current folder. So this period is imported here, that means the current folder, if you don't add this period, this utility will create an additional folder and that seems a bit repetitive, so let's move on with this, okay, now, Back to the project panel , if you expand py shop we can see that this is our project that we created in pycharm and in this folder we have these files.
So, init.py, you've seen this before, that means this folder is a package, so we can import multiple modules, from this package to other modules, and in this module, we define various configurations for our application, you go to see this later in this course. You also have the module for this URL, and with this module we define what the user should see when they see the about/contact/products/shopping cart bar again, we are going to work only with this. And finally we have this module, wsgi, which is short for web server gateway interface. The purpose of this module is to provide a standard interface between applications built with Django and web servers.
This is an advanced topic, so don't worry about it for now. Now, outside of this folder, from this folder you also have this new folder in our Manage.py project. As the name suggests, we use this to manage this Django project. With this we can start our web server, we can work with our database, again, we are going to work with this soon, let's open the terminal window once again, now, type this command, python if you are on Windows or Python 3 if you are on Mac, because as I told you at the beginning of the course, Mac by default comes with a Python installation, that is, Python 2.
But this course is Python 3. So python 3 space manage .py space run server.这里发生了什么? So, with the Python interpreter we are running this program manage.py and passing run server as an argument. This Manage.py is essentially the same program we work with here, Django Admin. But we use django admin before creating a django project, now we have a django project, so now in this project we work with Manage.py, this is a module which contains some python code, so we use this module to manage our Django project.让我们继续吧

If you have any copyright issue, please Contact