In this Python tutorial, you're going to learn everything you need to know to start programming in Python. If you want to learn Python programming for data science, machine learning, or web development, this Python tutorial is the perfect place to learn Python. You don't need any prior knowledge in Python or programming in general.
I'm going to teach you everything from scratch. I'm Mosh Hamadani, and I've taught millions of people how to code through this channel. If you're new here, make sure to subscribe as I upload new videos every week. Now, let's jump in and get started.
Before we get started, let me give you some ideas about what you can do with Python. That's a very common question. Python is a multi-purpose programming language, so you can use it for a variety of different tasks. You can use Python for machine learning and AI. In fact, Python is the number one language for machine learning and data science projects.
Python is also very popular in web development. Using Python and a framework called Django, you can build amazing websites. Here are five websites powered with Python and Django.
YouTube, Instagram, Spotify, Dropbox. and Pinterest. You can also use Python in automation.
With Python, you can save your time and increase your productivity by automating repetitive tasks. So, why are you learning Python? Are you learning it for automation, for data science, or web development?
Let me know in the comments section below. Alright, the first thing I want you to do is to head over to python.org to download the latest version of Python. So, you go to downloads and select the latest version of Python. here in your downloads folder, you should see this package, simply double click it, you're going to see this python installer, if you're on windows, you will see this check box over here, add python to path, make sure to check it, it's really important, otherwise you're not going to be able to follow this tutorial.
Simply click on continue, again, one more time, I agree with the terms, and install the latest version of python. now here you need to enter the username password of your computer, so let's do that real quick, next you need to install a code editor, we use a code editor to write our code and execute it, the most popular code editor for python is pycharm, you can get it from jetbrains.com slash pycharm, so on this page, click on download, you should see two different editions, one is the professional edition which is commercial and we also have this community edition which is free and open source. So we're going to download the community edition.
Now in your downloads folder, you should have this package let's double click it. If you're on windows, you're going to see an installation wizard. So simply click on the next button until you install PyCharm. If you're on a Mac, you need to drag this PyCharm and drop it onto the applications folder.
Now, let's open it, the first time you open pycharm, you have to configure a few settings, we don't want to spend time on this, so over here you're going to click on skip remaining and set defaults. Now let's create a new project, over here we can specify the location and the name of our python project. So let's append hello world to this path, this is where our python project is going to be saved.
So let's click on create, In this window you can see the content of our project, so here's our hello world project, currently we have only one folder inside this project, that is vn, which is short for virtual environment, we'll talk about virtual environments in the future. So currently we don't have any python files inside this project. A real application can consist of tens or hundreds or even thousands of python files. So let's right click on the project name and go to new python file, we're going to call this file app.
Now we can collapse this project window by clicking on this icon. So now we have more space, let's write our first python code. We're going to write print all in lowercase, then add parenthesis, then add quotes, either single quotes or double quotes.
And inside these quotes we're going to write hello world. So this is what we call a string. A string means a string or sequence of characters.
In simple words, that means textual data. So in python, and many other programming languages, whenever we're dealing with textual data, we should always surround our text with quotes. In python we can use single or double quotes.
Now this print you see here is a function built into python, and we can use it to print a message on our application window. So let me show you how to run this code. On the top, we go to the run menu, and then select run.
Note that there is a shortcut associated with this command, I always use shortcuts because they increase my productivity. So, let's click on this, now select app, and over here, you can see this little window, this is what we call the terminal window, and it shows the output of our program. So here's the hello world message printed in the terminal window.
Now as you learn more python you will learn how to build applications that have a graphical user interface. That's an advanced topic, so for now, let's not worry about it. Alright, now let's talk about variables.
We use variables to temporarily store data in a computer's memory. For example, we can store the price of a product, or someone's name, their email, their age, and so on. Let me show you. So, to declare a variable, we start by typing a name for that variable. Let's say age.
then we add an equal sign, and then we type a value, let's say 20. So with this we're storing the number 20 somewhere in our computer's memory, and we're attaching this age as a label for that memory location. So now we can read the value at this memory location and print it on the terminal. So instead of printing hello world, we want to print the value of the age variable. So I'm going to delete what we have inside parenthesis and type age.
Note that I'm not adding quotes, because if I run this program, we'll see the text age on the terminal. We don't want that, we want the value of the age variable. So, let's remove the quotes, and print the value of the age variable.
Now here on the toolbar, you can click on this play icon to run your program, or you can use the shortcut that I showed you in the last video. So, the shortcut is over here. On a Mac, that's control, shift, and r.
So, there you go, now you can see the value of the age variable. Now we can also change the value of a variable, for example, on line 2, we can set age to 30, now when we run our program, we see 30. So as you can see, our program gets executed from top to bottom. So this is how we can declare and use a variable.
Now let's look at a few more examples. So I'm going to declare another variable called price, and set it to 19. 95. So in python we can use numbers with a decimal point or whole numbers. We can also declare a variable and assign it a string value.
So let's say first underline name. So if you want to use multiple words in the name of a variable we should separate them using an underscore. This makes our code more readable.
See what would happen if I didn't use this underline. This is not easily readable. So we always separate multiple words by an underscore.
Now we set this to a string. So we can use single quotes or double quotes. Let's say mosh. We also have a special type of value called a boolean value which can be true or false.
That is like yes or no in English. Let me show you. So I'm going to declare another variable called is online and set it to true. We could also set it to false.
What we have here is called a Now note that python is a case sensitive language, so it's sensitive to lower case and upper case letters. In this case, if I use a lower case f, you can see an error over here, because this is not recognized in python. So false with a capital f is a special keyword in python that represents the boolean false value. So this is how we can declare and use variables in python. Alright, now here's a little exercise for you.
Imagine you want to write a program for a hospital. So we're going to check in a patient named John Smith, he's 20 years old, and he's a new patient. I want you to declare a few variables to store these values. Use the comment box below to share your code with others.
In this tutorial, I'm going to show you how to receive input from the user. So in Python we have another built in function called input. we use this to read a value from the terminal window, let me show you. So, we add parenthesis, then we type a string, here we can type a message like what is your name?
We add a question mark, followed by a space. You will see why we need this space in a second. So, let's run this program, we get this message, now we have to enter a value. So, we click over here, now you can see that the caret is separated from the question mark, this is because of the white space that we added over here.
So now, we have to type a value, let's say john, when we press enter, this function will return the value that we entered in the terminal window. So we can get that value and store it in a variable. So let's declare a variable called name and set it to the return value of the input function. Now we can print a greeting message for this user. So we use the print function, we say hello, we add a space, now after the string, we want to add the value of the name variable.
So we use a plus sign and then type name. What we are doing here is called string concatenation. So we are combining this string with another string.
Now let's run our program and see what happens. So what is your name? Mosh, now we get this message, hello mosh.
So this is how we can use the input function in python. You have learned about the three types of data in python. We have numbers, strings and bullions.
Now there are times you want to convert the value of a variable from one type to another Let me show you so we're gonna use our input function to read the users birth here So enter your birth here now this input function is going to return a value so we can store it in a variable called birth Underline here. Okay. Now, let's write code to calculate the age of this user.
So we write an expression like this, currently we are in the year 2020, so 2020 minus birth year, this expression or piece of code is going to produce a value, so once again we can store that value in a variable, let's call that variable age, now let's print age on the terminal, let's run our program and see what happens, so my birth year is 1982, enter, oops, our program crashed. So whenever you see this red message, that indicates an error, so this error occurred in this file, that is our app.py, on line 2, right below that you can see the piece of code that generated this error. So that is this expression, 2020 minus birth year.
Now below that you can see the type of error, so here we have unsupported types for subtraction, we have int and stir, what are these? this int is short for integer, and that represents a whole number in programming. So, 2020 is an example of an integer. Now, birth year is an example of a string, because whenever we call the input function, this function will return a value as a string.
Even if we enter a number, in other words, when I entered 1982, this input function returned a string with this characters, 1982. So this string is different from the number 1982, they're completely different types, so in this case, let me delete these lines, the reason we got this error is that we tried to subtract a string from an integer, so our code looks like this, 1982, now python doesn't know how to subtract a string from an integer, so to solve this problem, we need to convert this string to an integer, now in python we have a bunch of built in functions for converting the types of our variables, so we have this int function, we can pass our birth year to it, and this will return the numeric representation of the birth year. So, to solve this problem, we need to replace the string with the int function. So let's see what's going on here.
On the first line, we call the input function, this returns a string, on the second line, we pass the string, to our int function, the int function will return the numeric representation of the birth year. Then, we subtract it from 2020, we get the age, and store it in the age variable. Now let's run our program, so 1982, and there you go, I'm 38 years old. So this is how the int function works. Now we also have another built in function called float, that is for converting a value to a floating point number.
floating point number in python and other programming languages is a number with a decimal point so 10 is an integer and 10.1 is a float so we have int we have float and you also have bool for converting a value to a boolean and Finally we have stir for converting a value to a string So these are the built-in functions for converting the type of our variables. Now, here's a little exercise for you I want you to write a basic calculator program. So here we have to enter two numbers we can type a whole number or a number with a decimal point, and then our program will print the sum of these two numbers.
So pause the video, spend two minutes on this exercise, and then see my solution. Alright, first we're going to call our input function to read the first number, we get the result and store it in a variable called first. Now, let's declare another variable called second, and read the second number. Now, we calculate the sum, so that is first plus second, now let's see what happens when we print sum on the terminal.
So I enter 10 and 20, but instead of 30 we get 10 20. This is because we're combining or concatenating two strings. So, as I told you before, the input function returns a string, so this line will be equivalent to first equals 10. dealing with a string, not an integer. Similarly, second is going to be 20 as a string, so when we combine two strings, 10 plus 20, we'll get 10, 20, because we're dealing with textual data.
So to solve this problem, we need to convert the values we read to their numeric representation. So over here, we're going to pass first to our int function, and here as well, now let's run our program, so we enter 10 and 20, we get 30. What if we enter a floating point number? So 10.1 and 20, we got an error. So to solve this problem, we need to treat both these values as floats.
So instead of the int function, we're going to use the float function. Now, let's run our program one more time, we enter number and a floating point number. So the result is correct, now let's add a label over here, so sum is plus sum. Let's run our program one more time, 10 and 20 once again we got an error, the error is saying that python can only concatenate strings, not floats to strings.
So on line 4 we have a string, we are concatenating this with a float. because the result of this expression is a floating point number, we're adding two floats, so the result is a float as well. So python doesn't know how to evaluate code like this. It doesn't know how to concatenate a float to a string. To solve this problem, we need to convert sum to a string.
So this is where we use the stir function. Now, let's run the program again, so 10 20.1, and here's the result. And one last thing, in this example, I'm calling the float function, at the time we want to calculate the sum of these two numbers, but this is not a requirement. We can call the float function over here. So this input function returns a string, we can pass that string to our float function.
Take a look. So float, parenthesis, like this. So the value that we're passing to the float function, is the value that is returned from the input function.
Similarly, we call the float function over here, now we can change this expression to first plus second. That is another way to write this piece of code. So type conversion is important in python and other programming languages, there are times you need to convert the type of variable to a different type.
In this tutorial, I'm going to show you a bunch of cool things you can do with strings in Python. So let's start by declaring a variable called course, and set it to Python for beginners. Now this string that we have over here is technically an object. An object in Python is like an object in the real world.
As a metaphor, think of the remote control of your TV. This remote control is an object, and it has a bunch of capabilities. It has a bunch of buttons for turning your TV on, turning it off, change in the volume and so on.
Now in this program, this course variable is storing a string object. This string object has a bunch of capabilities. So if you type course dot, you can see all the capabilities available in a string object. These are basically functions that you can call. Just like the print or input functions.
The difference is that the print and input functions are general purpose functions. They don't belong to a particular object. But the functions you see over here are specific to strings.
Now more accurately, we refer to these as methods. So when a function is part of an object, we refer to that function as a method. So, let's look at a few examples. Here we have a function or a method called upper, and we use that to convert a string to uppercase.
So if we print course.upper and run this program you can see our course in uppercase. Pretty useful. Now what you need to understand here is that this upper method does not change our original string, it will return a new string.
So right after this, if we print course, you can see that our course variable is not affected. So the upper method returns a new string. Similarly we have another method called lower for converting a string to lower case.
We have a method called find to see if our string contains a character or a sequence of characters. For example, here we can pass y, and this will return the index of the first occurrence of in our string. So in python, the index of the first character in our string is 0, so here we have 0, 1, 2, 3, 4, and so on. So when we run this program, you're going to see 1 on the terminal, because the index of y is 1, take a look.
First I'm going to delete this line, you don't need it anymore, also, let's delete this line, let's run the program, there you go. Now as I told you before, python is sensitive to lower case and uppercase letters, so if I pass an uppercase y here, this find method returns negative 1, because we don't have an uppercase y in this string. We can also pass a sequence of characters, for example 4, so this will return the index of the word 4. Take a look.
So it's 7. Now, there are times you want to replace something in a string with something else. To do that, we use the replace method. Replace.
so we can replace 4 with a string containing the number 4. Take a look. So python for beginners. Obviously, if you look for a character or a sequence of characters that don't exist in our string, nothing is going to happen. For example, if you try to replace x with 4, obviously we don't have x here, so nothing is going to happen. Also, just like the upper method, the replace method is not going to modify our original string.
so it's going to return a new string, this is because strings in python and many other programming languages are immutable, we cannot change them once we create them, whenever we want to change a string, we'll end up with a new string object in memory, now one last thing I want to cover in this tutorial, there are times you want to see if your string contains a character or a sequence of characters, one way to do that is using the find method that we talked about, so let's see if our string contains python Now when we run this program, that is the index of the first occurrence of the word python in our string. Now in python we can also use the in operator. So we can write an expression like this. We type a string, python, then we type in, this is a special keyword in python, this is what we call the in operator, so after that we type the name of our variable.
So with this expression, we're checking to see if we have Python in course. As you can see, Python code is very readable, it's like plain English. So when we run this program, instead of seeing the index of the first occurrence of Python, we see a Boolean value.
This is more desirable in a lot of cases. Next we're going to look at arithmetic operations. In this tutorial, I'm going to show you the arithmetic operators that we have in Python.
These are the same arithmetic operators that we have in math. For example, we can add numbers, we can subtract them, multiply them, and so on. So let's print 10 plus 3, when we run this program, we have 13. So this is the addition operator.
We also have subtraction, we have multiplication, and division. Now technically we have two different types of division operators. We have a division with one slash and another with two slashes.
Let's look at the differences. if you use a single slash, we get a floating point number that is a number with a decimal point, but if you use double slashes, we get an integer, a whole number. We also have the modulus operator that is indicated by a percent sign, and this returns the remainder of the division of 10 by 3, so that is 1. And finally we have the exponent operator that is indicated by 2 asterisks, so this is 10 to the power of 3. So when we run this, we get 1000. Now, for all these operators that you saw, we have an augmented assignment operator.
Let me explain what it means. So let's say we have a variable called x, and we set it to 10. Now we want to increment the value of x by 3. So we have to write code like this, x equals x plus 3. When python executes this code, it's going to evaluate this expression or this piece of code, the result of this expression is 10 plus 3, which is 13. Then it will store 13 in the x. Now there is another way to achieve the same result using less code. We can type x plus equal 3. What we have on line 3 is exactly identical to what we have on line 2. So what we have here is called the augmented assignment operator. So we have this assignment operator, but we have augmented or enhanced it.
Now here we can also use subtraction to decrease the value of x by 3, we can use multiplication and so on. So these are the arithmetic operators in python. Alright, let me ask you a question. I'm going to declare a variable called x, and set it to 10 plus 3 times 2. What do you think is the result of this expression? This is a basic math question that unfortunately a lot of people fail to answer.
The answer is 16. Here's the reason. In math we have this concept called operator precedence, and that determines the order in which these operators are applied. So multiplication and division have a higher order so this part of the expression gets evaluated first, so 2 times 3 is 6, and then the result is added to 10. That is why the result of this expression is 16. Now in python operator precedence is exactly like math, but we can always change it using parentheses.
For example, in this expression, if you want 10 plus 3 to be evaluated first, we can wrap it in parenthesis. So, like this. Now when we execute this code, we're going to see 26, because 10 plus 3 is 13, and that divided by 2 is 26. Let's verify this. So print x, and we get 26. So you learn about the arithmetic operators in Python. Now in Python we have another set of operators called comparison operators.
We use this operators to compare values Let me show you so I'm going to declare a variable called X and set it to an expression like this 3 is Greater than 2 so what we have here this piece of code this expression is called a boolean expression Because it produces a boolean value So in this case because 3 is greater than 2 the result of this expression is the boolean true so if we print X get true on the terminal. So here is the greater than operator. We also have greater than or equal to, we have less than, we have less than or equal to, here is the equality operator which is indicated by two equal signs, do not confuse this with assignment operator.
So here we are comparing 3 and 2 for equality. So if we run our program, we see false because 3 does not equal to 2. So here is the equality operator, we also have the not equality operator, that is indicated by an exclamation mark, followed by an equal sign. So, let's quickly recap. Here are the comparison operators we have in python.
Greater than, greater than or equal to, less than, less than or equal to, equal and not equal. These operators are extremely important in real python programs, because quite often we have to compare values to evaluate certain conditions. You're going to see that soon. In Python we have another set of operators called logical operators. We use these operators to build complex rules and conditions.
Let me show you. So I'm going to declare a variable called price and set it to 25. Now let's print a Boolean expression like this. Price is greater than 10. Now let's say we want to check to see if the price is between 10 and 30. This is where we use the logical and operator. So we type and and right after that we type another boolean expression, so price less than 30. So with this and operator, if both these boolean expressions return true, the result of this entire expression will be true.
Take a look. So, in this case we get true, because the price is between 10 and 30 dollars. We also have the or operator. With the or operator, if at least one of these boolean expressions returns true, then the result of this entire expression will be true. To demonstrate this, I'm going to change price to 5. Let's see how Python is going to execute this code.
So first it's going to look at this Boolean expression. Is price greater than 10? No it's not, so it will keep going.
Then it will look at the second Boolean expression. Is price less than 30? It sure is, so the result of this entire expression will be true.
Take a look. There you go. We also have not operator which basically inverses any values that you give it.
Let me show you. So we're going to have one boolean expression price greater than 10 the result of this expression is false now if I apply the not operator This will inverse false to true. So when we run the program we get true So let's quickly recap in Python.
We have three logical operators. We have logical and which returns true if both expressions return true, we have logical or, which returns true, if at least one expression returns true, and we have not, which inverses any value that we give it. In this tutorial, we're going to talk about if statements in Python. We use if statements to make decisions in our programs.
For example, we can declare a variable called temperature, and depending on the value of this variable, we can print different messages on the terminal. Let me show you. So, here's our temperature variable, we set it to 35. Now let's say if temperature is greater than 30, we want to print a message saying it's a hot day.
So we type if, then we type a condition, and this is where we use our comparison operators. So we type temperature greater than 30. Then, so we add a colon, and see what happens when I press enter now. the carrot is indented, and this represents a block of code.
So the code that we write over here will be executed if this condition is true. Otherwise, it's not going to be executed. Let me show you. So, we're going to print, it's a hot day, and by the way, note that here I've surrounded the string with double quotes, because here we have a single quote as an apostrophe. So I couldn't declare a string like this with single quotes.
If I type, it's a hot day, look, python gets confused, because it thinks this single code represents the end of our string, so it doesn't recognize the subsequent characters, okay? So that's why we use double quotes here, so we can have an apostrophe in our string. So it's a hot day.
Now, if I press enter again, the character is indented, so the code that we write here will be part of our if block, and it will get executed if this condition is true. so here we can print a second message, drink plenty of water. Now to terminate this block, we press enter, and then press shift and tab.
The caret is no longer indented, so the code that we write here will always get executed no matter what. Whether this condition is true or not. Now in C based programming languages like C++, C sharp, Java and JavaScript, we represent a block of code using curly braces.
So you start a block of code using a left brace, and then end it using a right brace. In python we don't have curly braces. So we use indentation to represent a block of code. Okay?
So in this case, these two lines are indented, and that means they are part of this block of code. Now, let's run the program and see what happens. So we see these two messages because the temperature is greater than 30. Now, if I change the temperature, to 25, and run the program again, we don't see anything, okay?
Now, after this block, let's print done. Because this code is not indented, it will always get executed. It's not part of our if block, okay?
So take a look. Here's the done message. Now, let's add a second condition.
So if temperature is not greater than 30, that means it's less than or equal to 30. So, I'm going to add a second condition, so if the temperature is between 20 and 30, I want to print it's a nice day. So here we type l if, that is short for else if, and here we type a second condition. So temperature greater than 20. We add a colon, press enter, now we have a new block. So here we can print it's a nice day.
So if this condition is true, that means the temperature is greater than 20 and less than or equal to 30. now what we have here is called a comment, that is why it's grayed out it's not real code, it's just some note that we add to our program, python is not going to execute this, so whenever we type a pound sign, what we have after is treated as a comment, ok, so if this condition is true, then we're going to see this message on the terminal, let's run our program and verify this, there you go, the temperature is 25, that's why we see this message, now we can have as many conditions as we want there are no limitations, okay? So let's add another condition, elif temperature is greater than 10, then we're going to print it's a bit cold. Now in this case, if this condition is true that means the temperature is greater than 10 and less than or equal to 20. Now finally if the temperature is less than 10, let's print a message saying it's a cold day. So here we type else then we add a colon, and now we have a new block. So this code will get executed if none of the above conditions are true.
So here we can print it's called. So this is how we use if statements to make decisions in our programs. Here's a great exercise for you to practice what you have learned so far.
I want you to write weight converter program like this. So this program is asking me my weight, I enter 170. Next it's asking me if the weight is in kilograms or pounds. So I can type k for kilograms or l for pounds. I can type a lowercase l or an uppercase l, it doesn't matter. So let's go with a lowercase l.
Now it tells me weight in kilogram is 76.5. So go ahead and spend 5 minutes on this exercise. You can use the comment box below to share your code with others, and then when you're done come back and see my solution.
So first we call our input function to ask the first question, weight. We get the result and store it in a variable called weight. Next we call the input function one more time to ask the second question, is this in kilogram or pounds?
we get the result and store it in a variable called unit, this is where we're going to use an if statement. So, we want to check to see if unit equals k. Then, we should convert the weight to pounds and print it on a terminal. However, with this code, if I type a lowercase k, this condition is not going to be true.
Because earlier I told you that python is a case sensitive language. So, we need to convert this string to uppercase. earlier we talked about string methods, so if you type dot, we can see all the functions or methods available in a string object, so we use the upper method, and this returns a new string in upper case, now if this condition is true, first we need to convert the weight to pounds, so we declare a new variable called converted, get the weight, and divide it by 0.45, and then we can print this on a terminal, so we say weight in pounds is, then we append converted. Now, to terminate this block, we press shift and tab, else colon, so if this condition is not true, that means the weight was entered in pounds, so we need to convert it to kilograms.
Once again, we declare a variable, converted, and set it to weight times 0.45. And then we print weight in kilograms, and here we concatenate the string with converted. Alright, now we need to terminate this block, so we press enter, then shift and tab, good.
Now if you run this program, we're going to see an error, let me show you. So, let's run it, here I'm going to enter 170, then I type a lowercase l, okay, here's an error, can't multiply sequence by non int of type float, so this is where we got this error. when we try to multiply the weight by 0.45. So, that is line 7 in our code.
Now the reason this is happening is because the weight variable is storing a string object. Because earlier I told you, the input function always returns a string. So here we need to convert the weight to a number.
We can either use the int or the float function. Let's run the program one more time. So, 170, In Pound, here's a second error, can only concatenate strings. not float to string. And that error occurred over here.
When we try to print the weight in kilograms. So, look at line 7. In this case, weight is an integer, we are multiplying an integer by a float, and the result of this operation is going to be a float. Now on line 8, we are trying to concatenate or combine a string with a float.
And python doesn't know how to execute this code. To solve this problem, we need to convert this flow to a string. So here we use the built in stir function.
Let's run the program and see what happens. So 170 in pounds, and here's my weight in kilograms. Now let's try entering a weight in kilograms.
So run it one more time, let's say 76 kilos, here we get a familiar error. Can only concatenate string to string, not float. So this error occurred on line 5, where we tried to concatenate a string to a float.
So once again, we need to convert this to a string object. Now, let's run the program one more time, 76 kilos is equal to 168 pounds. Hey guys, I just wanted to let you know that I have an online coding school at codewithmarsh.com, where you can find plenty of courses on web and mobile development.
In fact, I have a comprehensive Python course that teaches you everything about Python from the basics to more advanced concepts So after you watch this tutorial if you want to learn more you may want to look at my Python course It comes with a 30-day money-back guarantee and a certificate of completion You can add to your resume in case you're interested. The link is below this video In this tutorial, we're going to talk about why loops in Python. We use why loops to repeat a block of code multiple times example, let's say we want to print the numbers 1 to 5, a poor way of doing this is writing code like this, print 1, then print 2, print 3, print 4, and print 5. Now why is this a bad approach?
Well, what if we wanted to print the numbers 1 to 1 million? We don't want to write 1 million lines of code, each line printing a number. This is where use while loops.
So we start off by declaring a variable like i, and set it to our initial number, let's say 1. then we type while, and here we type a condition, so once again we can use our comparison operators, let's say i less than 5 less than or equal to 5, as long as this condition is true then the code that we write inside of the while block will get executed so here we type a colon and press enter, now we have a block of code, in this block we can print i, and then we need to increment i by 1, so we set i to i plus 1 If you don't do this, i will always be 1, and this block of code will get executed indefinitely. It will never terminate. Basically our program will continue running until it runs out of memory. So, in the first iteration, i is 1, is less than 5, so python is going to execute this block of code.
It will print 1 on the terminal, and then i becomes 2. Then the control moves back over here, so python evaluates this condition. 2 is less than or equal to 5, so the condition is true, and once again python is going to execute this block one more time. In the second iteration, we're going to see 2 on the terminal, and then i will become 3. So this will continue until this condition is no longer true.
Let me show you. So, let's run this program, now we see the numbers 1 to 5. So this is the beauty of while loops. I can easily change 5 to 1,000 and by the way, I'm separating these three using an underscore, this makes my number more readable, we don't have to add this, but it just makes our code more readable.
So let's run the program, now we see the numbers, 1 to 1000, it's much easier than 1000 lines of code each printing a number, okay? Now let me show you something really cool, so I'm going to change this to 10, now instead of printing i, I want to print an expression, so I'm going to multiply i by a string, an asterisk. Now, you might be confused here, because earlier I told you that in python we cannot concatenate a number to a string, but here I'm using the multiplication operator, well, this is different, we can multiply a number by a string, and this will repeat that string based on the value of that number.
So if i is 1, we're going to see 1 asterisk, if i is 5, we're going to see 5 asterisks. Let me show you. So, when we run this program, we see this triangle shape, because in the first iteration, i is 1 so we see one asterisk, in every iteration i is incremented by one, so we see one extra asterisk, and finally in the last iteration, i is 10, and we see 10 asterisks on the terminal.
So you have learned about three types of data in python. We have numbers, which can be integers or floats, we have booleans, and strings. These are what we refer to as primitive or basic types in python. Now in python we have a bunch of complex types as well.
These complex types are very useful in building real applications. In this tutorial we're going to talk about lists. We use lists whenever we want to represent a list of objects.
Like a list of numbers, or a list of names. Let me show you. So, I'm going to declare a variable called names and set it to a list of names. So here we add square brackets to represent a list.
and now we can add one or more objects inside this list. In this list we add a bunch of names. Like John, Bob, Mosh, Sam, and Mary. So we separate these elements, these items using a comma.
Okay? Now, let's print our list, so print names, take a look, it comes out exactly like how we wrote it. Now we can also get individual elements in this list.
For example, if you want to get the first element in this list, here we type a pair of square brackets, and inside the square brackets, we type an index. The index of the first element in this list is 0, so now when we run this program we're going to see john on the terminal. There you go. Now, in python we can also use a negative index.
This is a feature that I personally have not seen in other programming languages. So, if 0 represents the first element in this list, what do you think represents. It represents the last element in this list.
Let's verify it. So, let's run the program and here's Mary. What about negative 2?
Well, that represents the second element from the end of the list. So, let's run the program and here is Sam. Now we can also change an object at a given index. For example, let's say here we made a mistake, and this John should not be spelled with an h.
So we need to reset it, we type names of 0, now we treat this like a regular variable, so we set it to a new value, we set it to john without an h. Now let's print our list and here's our updated list, beautiful. We can also select a range of values, for example, let's say we're only interested in the first three names.
So over here, we type square brackets, and here we need to type indexes, a start index and an end index. Our start index is a 0, because we want to start from here, and our end index is going to be 0, 1, 2, plus 1 that's going to be 3, so we add a colon 3. So python is going to return all the elements from the start index up to the end index, but excluding the end index. So it's going to return the elements at index 0, 1, and 2. take a look, here are the first three names.
And by the way, this expression does not modify our original list, it returns a new list. So right after this print statement, if we print our original list, you can see that it's not changed. So this is how we use lists in python. Earlier I told you that strings in python are objects.
Objects in programming are kind of like objects in the real world. Like your mobile phone, your bicycle, the remote control of your TV and so on. They have certain capabilities.
So if you type a string here and then press dot, we can see all the functions or methods available in a string object in python. Now, lists are also objects. So they have a bunch of methods for adding items or removing them and so on. Let me show you. So I'm going to declare a list of numbers, let's say 1, 2, 3, 4, and 5. Now, to add a new element at the end of this list, we can use the append method.
So we type numbers.append, and here we type 6. Now, let's print our list, so here's our updated list. Beautiful. Now what if you want to insert a number somewhere in the middle or at the beginning.
For that, use the insert method. So, we're going to call the insert method, now on the top, go to the view menu, and look at parameter info, look at the shortcut, on a mac computer it's command and p, on windows it's probably control and p. If we use this shortcut, we can see the values that this method expects.
So the first value that this method expects is an index value and the type of this value is an integer. So if I want to insert a value at the beginning of this list, I should pass 0 as the index of the first element, right? So let's pass 0. Now, the second value is highlighted, so the second value is an object, and the type of this is t. That basically means this can be any type, we can pass a number, we can pass a boolean, we can pass a string, we can pass a list, or any type of objects in python. So, I'm going to pass negative 1, now let's run our program, you can see negative 1 appeared at the beginning of our list.
We also have a method for removing items, so let's call remove, 3, let's run the program, 3 is gone, we only have 1, 2, 4, and 5. Now if you want to remove all the items in the list, we call the clear method. So clear, this method doesn't expect any values. So let's run our program, our list is empty. Now sometimes you want to know if a given item exists in our list or not.
To do that, we use the in operator. So let's remove this line, instead of printing our numbers list, I'm going to print an expression, 1 in numbers. So here we're using the in operator, we're checking to see if 1 is in the numbers list.
So this is a boolean expression, it returns a boolean value. Take a look. So we get true.
Obviously if we search for a value that doesn't exist in this list, like 10, we get false. Now finally there are times you want to know how many items you have in the list. To do that, you can use the built in len function, so let's print len of numbers, so len is a built in function just like the print function, that is why it's highlighted as purple it returns the number of elements in a list, take a look, so we have 5 elements in this list, when writing python programs, there are times you want to iterate over a list, and access each item individually.
Let me show you. So I'm going to declare a list of numbers, 1, 2, 3, 4, 5, now, if we print this list, it comes out exactly like how we wrote it, using the square bracket notation. But what if we wanted to print each item on a separate line? That is where we use the for loop, let me show you. So, we're not going to print the entire list, instead we're going to type for, now we declare a variable which is called a loop variable.
Let's call it item, then we type in numbers, next we add a colon to start a block of code. So this is what we call a for loop. With this for loop we can iterate over all the items in this list.
In each iteration, this item variable is going to hold one value. So in the first iteration, item is going to be equal to 1, and the second iteration is going to be equal to 2 and so on. So now if we print item and run our program, we see each item on a new line.
So this is how we use a for loop. Now we could also achieve the same thing using a while loop, but our code would be a little bit longer. Let me show you.
So we would have to start by declaring a loop variable outside of our while loop. Let's say i, we set it to 0. Now we say while i is less than, here we need to find out how many items we have in this list. So we use the len function, len of numbers.
So as long as i is less than the length of the list, print, now we can use the square bracket notation to get the element at this index. So numbers of i. Now we need to increment i by 1. So i equals i plus 1. Let's run the program and see what we get. So we get the numbers 1 to 5, these are coming out from our for loop, and then we get the numbers 1 to 5 one more time, these are coming out from our while loop.
Now if you compare these two approaches, you can definitely see that the implementation using the for loop is shorter and easier to understand. We don't have to use the square bracket notation, we don't have to call the length function, we don't have to declare a variable, a loop variable, and then increment it explicitly, so with the for loop, in each iteration, the item variable will automatically hold one value in this list. In this tutorial, we're going to talk about the range function in python.
We use the range function to generate a sequence of numbers. Let me show you. So, type range, this is a built in function, just like the print and input functions.
Here we can pass a value like 5, and this will return a range object. A range object is an object that can store a sequence of numbers. Let me show you. So, let's call that numbers, so this is a range object, In this object we're going to have the numbers 0 to 5, but excluding 5. Now, if we print numbers, we're going to see this message, range of 0 to 5, not the actual numbers because this is the default representation of a range object. To see the actual numbers, we need to iterate over this range object using a for loop.
In the last video you learned how to iterate over a list using a for loop, but we can also iterate over a range object using a for loop. Basically we can use the for loop with any object that represents a sequence of objects. So instead of printing numbers we're going to use a for loop for number in numbers colon, we're going to print number.
Take a look. Now we see the numbers 0 to 4. So range of 5 generates a sequence of numbers starting from 0 up to the number we specify here. Now if we supply two values, the first value is going to be considered the starting value, and the second value is going to be considered the ending value, and it's going to be excluded. So range of 5 to 10 is going to generate the numbers 5 to 9. Take a look. There you go.
Now we can also supply a third value, and that will be used as a step. So let's say, instead of having a sequence of numbers like 5, 6, 7, 8, we want to jump two numbers at a time. So 5, 7, 9, and so on. So here we pass 2 as the step, take a look. So we get these odd numbers, 5, 7, and 9. So this is the range function in python.
Now quite often you see the range function used as part of a for loop, because we don't really need to store the result in a separate variable, we can call the range function right here. Where we are using the numbers variable. So we can type range of 5, and this will return a range object holding the numbers 0 to 4. Take a look.
There you go. So we don't really need to store the result in a separate variable like numbers. There you go. In this tutorial, we're going to talk about tuples in Python. Tuples are kind of like lists, we use them to store a sequence of objects, but tuples are immutable, which means we cannot change them once we create them.
Let me show you. So I'm going to start by defining a list of numbers, 1, 2, 3, now we use square brackets to define a list and parenthesis to define a tuple. So now this numbers variable is storing a tuple. If we try to reassign, let's say the first element, we're going to get an error, tuple object does not support item assignment. So this is what I meant by tuples are immutable, they're unchangeable.
Also, if you type numbers dot, you don't see any methods like append, insert, remove and so on. We only have count and index. Count returns the number of occurrences of an element for example, if we have let's say two 3's in this tuple and call count of 3, this will return 2. The other method we have here is index and this returns the index of the first occurrence of the given element. Now, these other methods you see here that start with an underscore, they're called magic methods. It's an advanced topic, and I've covered it in detail in my complete Python programming course.
If you're interested, the link is down below this video. So, tuples are immutable, we cannot change them once we create them. Now practically speaking, most of the time you would be using lists, but there are times that once you create a list of objects, You want to make sure that somewhere in your program you or someone else is not going to accidentally modify that list.
If that's the case, then you should use a tuple. Hey guys, I just wanted to let you know that I have an online coding school at codewithmosh.com where you can find plenty of courses on web and mobile development. In fact, I have a comprehensive Python course that teaches you everything about Python from the basics to more advanced concepts. So after you watch this tutorial, if you want to learn more, you may want to look at my Python course. It comes with a 30-day money-back guarantee and a certificate of completion you can add to your resume.
In case you're interested, the link is below this video. Hey, Mosh.