【YouTube百万粉丝大神 Mosh】Python系列完整教程(中英文字幕)
Nội dung video gốcMở rộng video
> **Key Points:**
>
> - Introduction to Python programming with Mosh as the instructor.
> - Comprehensive learning of Python, including projects and automation.
> - Overview of setting up Python and code editors like PyCharm.
> - Core concepts, variable types, and functions in Python.
> - Creation of a Django web application and its administrative features.
> - Implementation of machine learning concepts and models.
Hi, my name is Mosh, and I'm going to be your instructor in this Python course. In this course, you're going to learn everything you need to get started programming in Python. Python is one of the most popular programming languages, and every day people use it to do cool things like automation. They use it in AI, as well as building applications and websites like Instagram and Dropbox. So if you're looking for a job, Python is for you.
In this course, I'm going to teach you everything you need to get started with Python. We're gonna talk about all the core concepts in Python and then we're going to build three Python projects together. Here's the first project we're gonna build. You're gonna learn how to create this beautiful website for an imaginary grocery store. Here on the homepage, we can see all the products in the shop and we also have an admin area for managing the stock.
We're going to build this using a popular Python framework called Django. Now, if you have never built a website before, don't worry, I will teach you everything from scratch. You're also going to learn how to use Python in machine learning or artificial intelligence. So, you will learn how to write a Python program that will predict the kind of music that people like based on their profile. Just like how YouTube recommends videos based on the videos you have watched before.
I'll also teach you how to use Python to automate boring, repetitive tasks that waste your time. You will write a Python program that will process thousands of spreadsheets in under a second. I've designed this Python course for anyone who wants to learn Python. If you're a beginner, don't worry, I will hold your hands through this entire course. You're not too old or too young, and Python is super easy to learn.
You can write your first Python program in literally seconds. Plus, I'm gonna give you plenty of exercises to help you build your confidence writing cool Python programs. My name is Marsh. I'm a software engineer with two decades of experience and I've taught over 3 million people how to code. I'm super excited to be teaching you Python in this course.
So I hope you stick around and learn this beautiful and powerful programming language. In this tutorial, I'm going to show you how to download and install Python on your computer. So the first thing I want you to do is open up your browser and head over to Python.org. On this page, click on downloads. Here you can see the latest version of Python currently at the time of recording this video. The latest version is Python 3.7.2. Chances are in the future, when you're watching this tutorial, there is a newer version of Python available. Don't worry, all the materials you're going to learn in this course will apply to the latest version of Python as well.
So let's go ahead and download Python 3. Alright, now look at your downloads folder. Here we should have Python 3 installer. Simply double-click that. If you're on Windows, you're going to see this checkbox here. Add Python to path. This is really important. Make sure to tick this box, otherwise you're not going to be able to follow this tutorial. If you're on a Mac, you're going to see an installer like this. With this set of wizard, we can install Python 3 on our computer.
So simply click Continue and again and again agree with the license agreement and install it. This is going to take a few seconds, so I'm going to pause the recording. Alright, we have successfully installed Python 3 on our computer. Let's close this all. Next, we need to install a code editor. We use a code editor to write our code. Just like how we use Microsoft Word to write documents, we use a code editor to write code.
Now, there are so many code editors out there. The one that I'm going to show you in this tutorial is PyCharm. That is one of the most popular code editors for writing Python code. You can get it from jetbrains.com. PyCharm now, more accurately, PyCharm is considered an IDE, which is short for Integrated Development Environment. And that's basically a code editor on steroids. It has some additional features that make it really easy to write code.
So let's go ahead and download PyCharm. Now here on the download page, you can see two versions of PyCharm. One is the Professional Edition, which has additional features and you'll have to pay for them. The other is the Community Edition that is absolutely free. And that's what we're going to use in this tutorial. So go ahead and download this as well. Now, once again, look at your downloads folder. You should have PyCharm, so double-click this.
Now, if you're on Windows, you're going to see an installation wizard. Simply click Next, Next, Next until you install PyCharm. If you're on Mac, you need to drag and drop this icon onto the Applications folder. So drag and drop. Alright, now let's double-click this to run it the first time you run PyCharm. We're going to get this warning because this is an application that you download from the Internet. So let's go ahead and open it. Next, you're going to see this dialog box for importing some settings. Leave this to do not import settings. It doesn't really matter.
On this page, select I have never used PyCharm. You can see some keyboard shortcuts that might be useful in the future. Just accept this and down the bottom, click the next button and then next again and one more time and finally start using PyCharm. So here's the main page of PyCharm that you're going to see every time you open it. Click on Create New Project. This is the location for our project. Let's call this project hello.
Now, before clicking Create, expand this item here. Make sure that base interpreter is set to Python 3. Python interpreter is basically a program that knows how to execute Python code. It will interpret or translate Python instructions into instructions that a computer can understand. Now, Mac computers by default come with an older installation of Python that is Python 2. It's considered legacy, which means it's no longer maintained or supported. So earlier we downloaded Python 3. Make sure that this is set to Python 3. If not from this list, select Python 3.7. Alright, now let's go ahead and create this project.
Now here, right-click on hello World folder and go to New Python File. Call this file app.py. So by convention, all Python files should have this PY extension. Alright, let's go ahead. Now let's collapse this project panel by clicking here and write our first Python program. Simply type print. Print all in lowercase open and close parentheses. And inside this parentheses add quotations. You can either use single quotes or double quotes. Now, in between the quotes, write your name. I am Mosh Hamadani.
So let's write that here. So this is your first Python program. With this piece of code you can print your name on the screen. Now, to run this, go on the top, under the Run menu, click Run. Also note that there is a shortcut associated with this command. When I program, I always use shortcuts because that increases my productivity. So here on a Mac computer, the shortcut is Control Option and R. On Windows, it's different. So let's go ahead with that. Now it's asking where you want to run this. Click on app.
Now down below, you should see this little terminal window. This is like a little window into our program. So here we can see the results or output of our program. In the future, as you learn more Python, you'll be able to build applications that have a graphical user interface or GUI that is a little bit complicated. So for now, we're going to use this little terminal window to see the results of our program. So, as you can see, my name is printed here. As you write code, this window might get in the way, so you can always resize it or minimize it by clicking this icon here. So this was our first Python program.
Now, if you didn't see the results I showed you in this video, use the comment box below and tell me what error you encountered. I'll do my best to help you move forward. In this Python tutorial, we're going to take this program to the next level. We're going to make it more interesting.
So I'm going to show you how to draw a dog here. As part of this tutorial, you will learn how Python code gets executed, and you will also learn about a few programming terms. So, press enter and align to write another print statement. So print, open and close parentheses, add a quotation. Now, here we want to draw a dog. So we add simple characters, like a head of our dog, followed by four hyphens.
Now, one more time, another print statement with quotations. Now, we need to draw the legs. So add a space followed by four vertical bars, like this. So here's a little imaginary dog. Now, let's run this program and see what we get. So in the top right corner, you should see this play button, click that. There you go.
So we have our name, and right below that, we have our imaginary dog. Now, what you need to understand here is that our Python code gets executed line by line from the top. So, earlier I told you about Python Interpreter. That is the program that knows how to translate or interpret Python code into instructions that a computer can understand.
So, first it executes line one, then moves on to line two, and so on. So this is how Python programs get executed. Now, let me show you something cool. Let's add another print statement with quotations. Now, in between the quotations, add a star or an asterisk, like this. Now, after the quotation and before the parentheses, add a space. Once again, add an asterisk space 10.
What is going on here? Well, anywhere we have quotations like here or here, we're defining a string. A string is a programming term, which means a series of characters. So here we have a string. We also have a string in line three as well as line two and line one. Now here we are multiplying the string by the number 10. So this is the multiplication operator, just like the multiplication operator we have in math.
So with this piece of code, we can draw 10 asterisks in the terminal. Let me show you. So let's run this program one more time. There you go. So we have 10. Now, what we have here, this piece of code here is called an expression. An expression is a piece of code that produces a value.
So when Python interpreter tries to execute line four, first it will evaluate the code that we put in between parentheses. So it will evaluate our expression. Our expression will produce 10 asterisks and then those asterisks will be printed on the terminal. As an exercise, you can use these print statements to draw another shape. You can draw a heart, a ball, whatever you like. I will see you in the next tutorial.
One of the questions I get a lot on my channel is how long does it take to learn Python and become job ready? Well, there is no single answer. It really depends on you and how much effort and commitment you want to put into this. But I would say if you spent two hours every day consistently after about three months, you should be able to write basic Python programs.
But quite honestly, that doesn't get you a job. In order to get a job, you need to specialize in one area. What do you want to use Python for? Do you want to use it to build web applications or desktop applications? Or do you want to use it in machine learning and artificial intelligence? So whatever you want to do, you need to take additional courses.
For example, if you want to become a web developer, in addition to learning Python, you should also learn about HTML, CSS, some JavaScript and Django, which is a popular Python framework for building web applications. Learning all these things would take you another six months. So in total, you need nine to 12 months to become job ready. At that point, you can get a junior developer job with a salary of about $50,000 to $60,000 a year. Now, as you work more, as you do more Python projects, your resume starts to build and you can ask for $100,000 a year or $120,000 a year, depending on where you are, what company, what geographical area, it really depends.
So there is no single answer. So are you excited to learn Python and get started on this career path? If you are, I would encourage you to make a commitment and spend two hours every day practicing Python. And use the comment box below and let me know why you're learning Python, what do you want to do with it? What's your dream job? I would love to hear your story.
In this Python tutorial, you're going to learn about variables, which are one of the most fundamental concepts in programming. They're not specific to Python. They exist in pretty much every programming language out there. We use variables to temporarily store data in a computer's memory. Here's an example. Let's type price = 10. When Python interpreter executes this code, it will allocate some memory, then it will store the number 10 in that memory, and finally it will attach this price label to that memory location.
As a metaphor, imagine we have a box. In that box, we have the number 10, and price is the label that we put on the box. Now, we can use this label anywhere in our program to access the value that we have in that box. This is a very simplified explanation. So now let's print price on the terminal. Print. Now, this time we're not going to add quotations, because if we put quotations here, we will see the text price on the terminal, not the value of the price variable.
So delete quotations and type price. Now, let's run this program one more time. There you go. So we see 10 on the terminal. So this is how we define variables. We start with an identifier which is the name of our variable, then an equal sign, and finally a value. Now, more accurately, when this number 10 is about to be stored in the memory, first it will get converted to its binary representation.
So this number 10 that we have is in decimal system, which has all the digits from 0 to 9. Computers don't understand all these digits, they only understand zeros and ones. So when we store the number 10 in the computer's memory, first it will get converted to its binary representation, which will be a bunch of zeros and ones like 00011010, whatever.
Then it will get stored in the computer's memory. So let's take this program to the next level. On the second line, we can update the value of this price variable so we can reset it to a new value like 20. Now, when we run our program, we should see 20 because as I told you before, Python interpreter executes our code line by line from the top.
So first we set price to 10, then we reset it to 20, and finally we print it on the terminal. Let's run the program. There you go. So we see 20 here.
Okay, now these numbers that we have here are whole numbers without a decimal point. In programming, we refer to these numbers as integers. We can also use numbers with a decimal point. For example, here on line two, we can define another variable called rating, and we set it to 4.9. Now in programming, we refer to this kind of number as a floating point number or float for short. So we have integers and floats.
We can also define a variable and set it to a string. For example, name = 'Mosh'. We also have another kind of value which is called boolean, which can be true or false. They are like yes and no in English.
Here's an example I'm going to define a variable is_new_published. So we use an underscore to separate multiple words in our variable name. We set this to true or false. These are the boolean values. Now note that Python is a case sensitive language, which means it's sensitive to lowercase and uppercase characters. So when defining variables, we should always use lowercase letters.
But here, false and true are special keywords in the language. So if we spell it with a lowercase 'f', Python doesn't understand it. You can see we have a red underline here, which indicates an error. So make sure to spell this with a capital 'F', or if you want to set this to true, make sure 'T' is capital. So in this program, we are storing simple values in our computer's memory. Simple values can be numbers, which can be integers or floats, or they can be strings or booleans.
But in Python, we can also store complex values like lists and objects, and that's what I'm going to show you in the future. So before going any further, I want you to do a little exercise. Imagine we're going to write a program for a hospital. So we check in a patient named John Smith. He's 20 years old and is a new patient. I want you to define three variables here for his name, his age, and another variable to tell if this is a new or existing patient. So pause the video and spend one minute on this exercise. When you're done, come back, continue see my solution.
Alright, so here we need three variables. The first one is the patient's name. We set that to John Smith. We can also call this full name. These are both valid names for our variables. The second variable is for the age of our patient. So age = 20. And finally, we need a variable to tell if this is a new or an existing patient. That's where we can use a boolean value. So we define a variable is_new and we set it to true.
So, you have learned how to print messages on the terminal window. In this tutorial, I'm going to show you how to receive input from the user. So we're going to write a small program that asks the user's name, and then it will print a greeting message customized for that user. So instead of print, we're going to use input. Now, both this input and print are functions that are built into Python. As a metaphor, think of the remote control of your TV. On this remote control, we have a bunch of buttons. These are the functions built into your TV. You can turn it on, turn it off, change the volume, and so on.
In Python, we also have a bunch of functions for common tasks, such as printing messages, receiving input and so on. So we're going to use the input function. Now whenever we have this parentheses, we say we're calling or executing that function. It's like pressing a button on the remote control.
So we're going to call the input function, and in between parentheses, we want to add a string to print something on the terminal. What is your name? With a question mark followed by a space. You'll see why in a second. So this input function will print this message on the terminal and then it will wait for the user to enter a value. Whatever the user enters, this input function will return. So now we can get that value and store it in the memory using a variable. So we get the result and put it in a variable called name.
Okay, now on the second line, we want to print a message like hi, John or hi, Mosh, whatever. So print, quotations, hi with a space. Now, after the quotation, we want to dynamically print what we have in the name variable. So we add a plus sign and then name.
So here we have hi, which is a string. We're concatenating or combining this string with another string. That is what we have in the name variable. So here's another example of an expression. Remember, what is an expression? It's a piece of code that produces a value. So this expression concatenates or combines two strings. Let's run this program and see what happens. So run.
Okay, here's the question. What is your name? Mosh. Now, note that earlier we added a space after the question mark. We did this. So here in the terminal window, the cursor is separated from the question mark. Otherwise, it would be so close. So let's type whatever. Here, press enter. Now we get this message, hi, Mosh.
Now, here's a little exercise for you. I want you to extend this program and ask two questions. First, ask the person's name and then their favorite color. Then print a message like Mosh likes blue. So pause the video, do this exercise and then come back. Continue watching.
Alright, so here's the first question. Right after that we're going to call the input function one more time. This time we're going to ask a different question. What is your favorite color? Now we get the new value and store it in a variable called color. Or we could call it favorite underscore color either works. And finally, we're going to change what we pass to the print function.
So first we print the name. Then we concatenate this with a string. Here we're going to type likes. We also put one space before and after likes. And once again, we concatenate this with the favorite color. So, favorite color. Now let's run this program.
So what is your name? Mosh. Enter favorite color, blue. Enter. We get this message, Mosh likes blue. Hey guys, Mosh here. I just want to let you know that you really don't have to memorize anything in this course because I put together a cheat sheet with summary notes so you can quickly review the materials in this course. The link is below this video.
So I have done my best to create the best possible python course on YouTube and I really appreciate it if you support my hard work by liking this video and sharing it with others so they can learn as well. And be sure to subscribe to my channel for more tutorials like this. Alright, now let's move on to the next tutorial.
In this Python tutorial, we're going to write a program that will ask the year we were born in and then it will calculate our age and print it on the terminal. So let's start with our input function. Input. Let's print birth year followed by a colon and a space. Now, let's get the return value and store it in a variable called birth on the line.
So as I told you before, we use an underscore to separate multiple words. Next we need to calculate the age. So we define another variable called age. And here we do some basic math. Currently we are in 2019, so let's write an expression like this, 2019 minus birth year. Now finally, let's print age on a terminal.
Let's run our program and see what happens. So my birth here is 1982. Enter. Oops, we got an error. What is going on here? So whenever you see this red message, that means there is something wrong in your program. With the information here, we can find exactly where the error occurred. So next to the file you can see the file that generated this error.
In this case, that is app. So currently our program has only a single file. But real complex programs often have hundreds or even thousands of files. So in this file on line two, this is where we got this error. And right below that you can see the piece of code that generated this error. So that is where we're calculating the age.
And right below that, you can see the type of the error. In this case we have a type error. And here's the message. Unsupported operand types for subtraction int and stir. So int is short for integer and that represents a whole number, and stir is short for string. So here we're subtracting a string from an integer and Python doesn't know what to do with it.
Let me explain. So I'm going to close the terminal window. So after the first line is executed, we have this birth year variable set to a string. So whatever we type in the terminal is always treated as a string, even if you type a number. In other words, when we run this program, this birth year variable will be set to your string with four characters 1982 this string is different from the actual number 1982. One is an integer, the other is a string. Right?
So back to line two where this error occurred at runtime. Which means when we run our program, this expression on the right side of the assignment operator is going to look like this, 2019 minus string 1982 Python doesn't know how to interpret or how to evaluate this expression.JavaScript.
To fix this problem, we need to convert this 1982 into an integer, and then we'll be able to subtract it from 2019. And that is very easy. So far you have learned about two built in functions. One is print, the other is input. We have a few more functions for converting values into different types. So we have int for converting a string into an integer.
We also have float for converting a string into a float or a number with a decimal point. And we also have bool for converting a string into a boolean value. So to fix this problem, we need to go back on line two and pass this birth year variable to the int function, like this int parenthesis like this. So we pass this string to the int function, int will convert it to an integer, and then Python interpreter will be able to evaluate this expression.
Now, let's run this program one more time. So birth year is 1982, enter. So I am 37 years old. In Python, we have a useful function for getting the type of variables. For example, let's print the type of birth year. So right after line one, let's print. Now here we're going to call another built in function called type.
And now let's pass birth year. Okay, now similarly after line three, let's also print the type of age. So print type of age. Okay, let's run our program. So birth here one more time. 1982. OK, here's the result. So the type of birth year, as you can see, is a class of stir or string. We'll look at classes in the future, so for now don't worry about them.
And also below that, you can see that the type of the age variable is int or integer. So here's what you need to take away. Whenever you use the input function, you always get a string. So if you're expecting a numerical value, you should always convert that string into either an integer or a float.Here's a little exercise for you. I want you to write a program, ask the user their weight and then convert it to kilograms and print it on a terminal. So pause the video, do the exercise and when you're ready, come back. Continue watching.
Alright, so let's use our input function and ask for the weight in pounds. Here we get the weight in LBs or LBs. Now we need to convert this into kilograms. That is very easy. So we define another variable, weight underscore kilogram or kam. We set this to weight underscore lbs times 0.45.
And finally let's print weight under kilogram. Let's run this Python program and see what happens. So my weight is 160. Alright. Once again, we got an error. Can't multiply sequence by non int of type float. So as I told you before, this input function returns a string, so we cannot multiply a string by a float. Python doesn't know what to do with it.
So in this case we should convert this number to an integer or a float, and then multiply it by 0.45. So let's call the int function and pass weight under lbs and run our program one more time. 160. Okay, so I am 72 kilograms.
In this tutorial, you're going to learn more about Python strings. So I've defined this course variable and set it to Python for beginners. Earlier I told you that you can use both single and double quotes to define a string, but there are times that you have to use a specific form, otherwise you're going to run into issues. Here's an example. Imagine we want to change this string into Python's course for beginners.
So we want to add an apostrophe like this. Python course for beginners. You can immediately see this is going crazy because our string starts here and then terminates here. All these characters that we have after the second apostrophe, Python interpreter doesn't know what they are. So to solve this problem, we need to use double quotes to define our string.
So we can have a single quote in the middle of the string. So let's change this to double quotes. Now you can see it adds another double quote. To close it, we have to manually remove this. And also one more time, at the beginning of the string, we need to add another double quote. Now you can see the error is gone. So if we print coursears, we see Python for beginners. Beautiful.
Now let's say we don't want this apostrophe here. So we have Python for beginners, but we want to put beginners in double quotes. Once again, if you add a double quote here, Python interpreter gets confused because it assumes the second double quote indicates the end of our string, so it doesn't know what these characters are. So to solve this, we need to change our double quotes to single quotes, like this, and then we can add double quotes in the middle of the string.
Now let's run this program. There you go. So we get Python for beginners. So these are the cases for using single or double quotes. Now, in all the examples I've shown you so far, we only deal with short strings. But what if you want to define a string that is multiple lines? For example, what if you want to define a string for the message that we sent an email? In that case, we need to use triple quotes.
So let me delete this. Now we add three quotes. So 1, 2, and 3. There you go. So we have three quotes to start our string and three to terminate it. Again, these quotes can be single or double quotes. Ok, now with this we can define a string that spans multiple lines.
For example, we can say. Hi, John. Here is our first email to you. Thank you, the support team. Like that. Now let's run this program and here's the result. So we get this beautiful multi line string.
Now let's change this back to something simple so we can look at other characteristics of strings in Python. So I'm going to use single quote and set the course name to Python for beginners. Here we can use square brackets to get a character and a given index in this string.
Let me show you. So, to get the first character, we use square brackets and type 0. So the index of the first character in this string is zero. In other words, this is how Python strings are indexed 0, 1, 2, 3, 4, and so on. So the index of the first character is zero, the second character is one, and so on. So let me delete this and run this program.
We get P. We can also use a negative index here, and this is one of the features that we don't have in other programming languages, as far as I know. So with a negative index, we can get the characters starting from the end. So if I pass negative one here, assuming that 0 is the index of the first character, negative one is the index of the last character. So when we run this program, we should see S. Let's run it.
There you go. We get S. If we pass -2, this will return the second character from the end. Let's run it one more time. Now we get R because that is the second character from the end.
Okay, pay close attention to this square bracket syntax because quite often, it's the topic for online Python tests or university exams. So if you're preparing for a Python test, make sure to watch this tutorial one more time and understand exactly how this square bracket syntax works. We can also use a similar syntax to extract a few characters instead of just one character. For example, if we type 0:3, Python interpreter will return all the characters starting from this index all the way to the second index, but it does not return the character at this index.
In other words, back to these indexes. So we have 0, 1, 2, 3 and so on. When we run this program, Python interpreter will return the characters starting from index 0 all the way to index 3, but excludes the character at index 3. So when we run this Python program, we're going to see py. Let me show you.
So I'm going to delete this line. Run this program. There you go. We get py. Now, here we also have default values for the start and end index. So if we don't supply the end index, Python will return all the characters to the end of the string. Let's take a look. So run this program. There you go. We get Python for beginners, but if you change the start index to 1, this will exclude the first character.
So when we run this program, we see ython. So P is removed. Okay? Now, similarly we have a default value for the start index. So if we don't supply the start index but add an end index like 5. Python interpreter will assume 0 as the start index. So let's run this program. There you go. We get pytho.
Now, what if we leave both the start and end index? Well, I told you that in this case, zero will be assumed as the start index and the length of the string will be assumed as the end index. So with this syntax, we can basically copy or clone your string. In other words, if I define another variable here, let's call it another and set it to course square brackets with just a colon. Now, this expression will return all the characters in the course variable.
So this second variable will be a copy of our first variable. Let's take a look. So let's print another and run our program. There you go. We get Python for beginners. So, once again, the square bracket syntax is pretty important.
If you're preparing for online Python tests or college exams, make sure to watch this tutorial again. Now, here's a little exercise for you. I'm going to delete all this code, define a variable called name and set it to Jennifer. Now, when we print name of [1:-1], what do you think we're going to see on the terminal? I want you to use your knowledge to tell what we're going to see on the terminal without running this program.
So pause the video, think about it for a few seconds, and then come back. Continue watching. So this expression will return the characters starting from index 1, which is the second character, all the way to the first character from the end, but excluding the character at this index. In this case, the first character from the end is R. So R will be excluded. In other words, we're going to see all the characters starting from e all the way to the second E.
Let's take a look. So I'm going to run this program. There you go. This is what we get, and I hope you guessed it. Great.
In this tutorial, we're going to look at formatted strings in Python programming language. Formatted strings are particularly useful in situations where you want to dynamically generate some text with your variables. Let me show you. Let’s say we have two variables, first name and last name.
So first, we set this to John, and last, we set this to Smith. Now, it's better to call these variables first name and last name because they're more descriptive. But here I'm using shorter names because I want you to see the entire code on the screen. So let's say with these two variables, we want to generate some text like this: John in Square brackets. Smith is a coder.
Let’s say we want to print this on a terminal. How do we do this? Well, we define another variable like message. Here we add the first name. Now we need to concatenate this with a string that contains a space and a square bracket. Next we need to add the last name. Then we need to add a string that contains the closing square bracket, followed by "is a coder." So then if we print the message and run this program, we see John Smith is a coder.
Right. Now, while this approach perfectly works, it's not ideal because as our text gets more complicated, it becomes harder to visualize the output. So someone else who reads this code, they have to visualize all these string concatenations in their head. This is where we use formatted strings.
They make it easier for us to visualize the output. So I'm going to define another variable. Let's say msg, short for message, and set this to a formatted string. A formatted string is one that is prefixed with an F.
So F quotes. Now, in between the quotes, first we want to add the value of the first first name variable. So we add curly braces. And here we type first. Next, we add a space. We add our square brackets. In between the square brackets, we want to display the last name. So once again we add curly braces and type last. And finally here we type "is a coder." So this is what we call a formatted string.
With these curly braces, we're defining placeholders or holes in our string. And when we run our program, these holes will be filled with the value of our variables. So here we have two placeholders or two holes in our string. One is for the value of our first name variable and the other is for the value of the last name variable.
Now compare this formatted string with string concatenation. With this formatted string, we can easily visualize what the output looks like. Right. Now let’s print this on the terminal to make sure we get the exact same output.
So let’s print the message. There you go. So John Smith is a coder. So to define formatted strings, prefix your strings with an F and use curly braces to dynamically insert values into your strings.
In this Python tutorial, I'm going to show you some really cool things you can do with Python strings. So let's start by defining a variable course, and we set that to Python for beginners. Now, to calculate the number of characters in this string, we can use a built in function called len. So len, we give it this course variable, and then we can print the result.
Let's run this program. So as you can see, we have 20 characters in this string. This is particularly useful when we receive input from the user. For example, you have noticed that when you fill out a form online, each input field quite often has a limit. For example, you might have 50 characters for your name.
So using this len function, we can enforce a limit on the number of characters in an input field. If the user types in more characters than we allow them, we can display an error.
Okay, now this len function is another function built into Python. It's a general purpose function, so it's not limited to counting the number of characters in a string. In the future, when we look at lists, I'm going to show you that we can use this function to count the number of items in the list. So it's a general purpose function.
Now we also have functions specific to strings. For example, we have functions for converting all these characters to uppercase or lowercase. To access these functions, we use the dot operator. Let me show you.
So first we type course, then dot. Look, these are all the functions that are specific to strings. Now in more accurate terms, we refer to these functions as methods. This is a term in object-oriented programming that we'll look at in the future. But for now, what I want you to take away is that when a function belongs to something else or is specific to some kind of object, we refer to that function as a method.
For example, here we have this function upper for converting the string into uppercase. Now, more accurately, because this function is specific to strings, we refer to this as a method. In contrast, len and print are general-purpose functions. They don't belong to strings or numbers or other kinds of objects.
Okay, so this is the difference between functions and methods. Now, let's look at this upper method. So let's print the result and run our program. There you go. We get all these characters displayed in uppercase. Now, note that this method does not change or modify our original string.
In fact, it creates a new string and returns it. So if we print our course variable right after we call the upper method, you can see that our course variable still has its original form. So let's run this program one more time.
There you go. Look, this is our original course variable. It's not modified. Now, similar to the upper method, we have another method for converting a string into lowercase. So let me show you.
Print course.lower(). Now let's run the program. So, on the second line, you can see all characters are in lowercase. Now, there are times that you want to find a character or a sequence of characters in a string. In those situations, you can use the find method.
So let me delete this few lines. We call course.find. Here we pass a character, let's say p, and this will return the index of the first occurrence of that character. Let me show you. So let's print the result. We get zero because the index of the first capital P in our string is zero.
As another example, if we pass a lowercase o here, let's see what we get. We get four because the index of this o here is 4. Now note that the find method is case sensitive, so it's sensitive to lowercase and uppercase characters.
As an example, if we pass an uppercase o here and run this program, we get minus one because we don't have an uppercase o anywhere in the string. Okay?
We can also pass a sequence of characters. For example, we can pass beginners with a capital B. Let's run this program. We get 11 because the word beginners starts at index 11.
Now, we also have a method for replacing a character or a sequence of characters, and that is called replace. So let's change find to replace. Let's say we want to replace beginners with absolute beginners.
So we add a comma to pass a second value to this function, or more accurately, this method. We add a string. Here, I'm going to pass absolute beginners. Okay, now let's run this program.
So we get Python for absolute beginners. Again, this method, like the find method, is case sensitive. So if we pass beginners all in lowercase, this method is not going to find this exact word in our string, so it's not going to replace it with absolute beginners.
Let's take a look. So I'm going to run the program one more time. Look, we still get Python for beginners. We can also replace a single character. For example, we can replace capital P with, let's say capital J. Now, when we run this program, we get jython for beginners.
So these are defined and replace methods. And one last thing I want to show you. In this tutorial, there are times that you want to check the existence of a character or a sequence of characters in your string. In those situations, you use the 'in' operator.
So let's say we want to know if this string contains the word Python. We can write an expression like this, string Python space in space course. So we're checking to see if Python is in the course variable.
Now, this is an expression that produces a boolean value, like a true or false. So we refer to this expression as a boolean expression. Now if we print this on the terminal, we should get true.
And by the way, let me delete the second line. We don't need it anymore. So run the program, we get true. But if I change this capital P to a lowercase p and run the program, we get false because we don't have this exact sequence of characters in our string.
Now note that the difference between the 'in' operator and the find method is that our find method returns the index of that character or sequence of characters. But the 'in' operator produces a boolean value. Do we have this or not? So that's the difference.
Now, let's quickly recap all the cool things you learned to do with strings in this tutorial. We can use the len function to count the number of characters in a string. This is a general-purpose function built into Python.
We also have specific functions for strings, which we refer to as methods. These include upper for converting a string into uppercase. We also have lower and title methods. You learn about the find method which returns the index of a character or sequence of characters.
We have the replace method for replacing characters and words in a string. And finally, you learned about the 'in' operator. So some characters in a string.
So you have learned that in Python programming language, we have two types of numbers: integers, which are whole numbers, like 10, they don't have a decimal point, and floating point numbers or floats, which are numbers with a decimal point.
Now in this tutorial, we're going to look at the arithmetic operations supported in Python language. These are the same arithmetic operations that we have in math. We can add numbers, multiply them, and so on. So let's look at a few examples. We can print 10 +3.
So this is the addition operator. We also have subtraction, we have multiplication. We have two kinds of division. Here's one with a forward slash. Let's run this program and see what we get. We get a floating point number. But we also have another division operator for getting an integer. So if we add another slash here and run this program, we get an integer.
We have another operator called modulus, which is a percent sign, and this returns the remainder of the division. So when we run this program, we should get one. There you go. And one last operator we have here is exponent, which is the power. So that is indicated with two asterisks, and this will return 10 to the power of three.
So let's run this program. We get 1,000. So these are the arithmetic operators in Python programming language. Now, for all these operators that you learned, we have an augmented assignment operator that is very useful. Let me show you.
So let's say we have a variable called x. We set it to 10. Now we want to increment this by three. We'll have to write code like this, x = x +3. So Python interpreter will add 10 to 3. The result is 13, and then it gets stored into x again. So when we print x, we should see 13.
There you go. So this is how we can increment a number. Right? Now, the augmented assignment operator is a way to write the same code but in a shorter form. This is how it works. We type x += 3.
What we have on line 3 is exactly like what we have on line 2. So this is what we call the augmented assignment operator. We have augmented or enhanced the assignment operator. Now, in this particular case, we are incrementing a number using the augmented assignment operator.
But we can also subtract or multiply a number by a given value. For example, let's delete what we have on line 2. We can type x -= 3. So here we're subtracting three from x. When we run this program, we should see 7.
There you go. Now, let me ask you a question. I'm going to clear all this code here. Define x and set it to 10 +3 times 2. What do you think is the result of this expression? This is a very basic math question that unfortunately a lot of people fail to answer. The answer is 16, because in math, we have this concept called operator precedence, which means the order of operations.
So the multiplication operator has a higher precedence, so it's applied first, which means 3 by 2 is executed first. The result is 6 and then it's added to 10. That is why x should be 16. After we run this code, let's verify that. So print x, run the program.
There you go. x is 16. So this is what we call operator precedence. It's just a basic math concept. It's not about Python programming language. So all the other programming languages behave the same way. So here's the order. First, we have the exponentiation which is the power, like 2 to the power of 3. Then we have multiplication or division.
And finally, we have addition or subtraction. This is the order of operations. Let me show you another example. Here I'm going to add the exponentiation operator, so 2 to the power of 2. Once again, what do you think is the result of this expression? Pause the video and think about it for a few seconds.
The answer is 22 because the exponentiation operator takes precedence. So first, 2 to the power of 2 is executed. The result is 4, then 4 is multiplied by 3, that is 12, and finally, 12 is added to 10. So x should be 22. So let's run this program and verify this. So I'm going to delete these lines here. Run the program.
There you go. x is 22. Now let me bring back these rules here. We can also use parentheses to change the order of operations. So if we have parentheses, it always takes priority. In this case, we can add parentheses around 10 +3. So this piece of code will be executed first. The result is 13.
Then the exponentiation operator will be executed. So 2 to the power of 2 is 4. And finally, 4 is multiplied by 13. Now here is a little exercise for you. I'm going to set x to parentheses 2*3*10 -3. What is the result of this? Pause the video and think about it for a few seconds.
You learn that parentheses always overwrite the order. So this piece of code is executed first. The result is 5. Then between the multiplication and subtraction, you know that multiplication takes precedence. So next 5 will be multiplied by 10. The result is 50. And finally, we have the subtraction. So 50 -3 will be 47.
Let's verify this. Print x, run the program. There you go. I hope you guessed it right. So this is all about operator precedence. It's a very important topic, and I see it quite often in Python tests. So if you're preparing for a Python test, make sure to watch this tutorial one more time.
In this tutorial, we're going to look at a few useful functions for working with numbers. Let's start by defining a variable like x and set it to 2.9. Now, to round this number, we can use the built in round function. So we call the round function, give it x, and then print the result.
Let's run this program. So we get 3. We have another useful built in function called abs, which is short for absolute. And this is the absolute function that we have in math. We give it a value and it always returns the positive representation of that value, even if that value is negative. Here's an example.
Let's call the abs function and give it negative 20. Let's see what we get. So we print the result. There you go. So, absolute always returns a positive number. Now, technically in Python, we have a handful of built-in functions for performing mathematical operations. If you want to write a program that involves complex mathematical calculations, you need to import the math module.
A module in Python is a separate file with some reusable code. We use these modules to organize our code into different files. As a metaphor, think of a supermarket. When you go to a supermarket, you see different sections for fruits and vegetables, cleaning products, junk food and so on. Each section in a supermarket is like a module in Python.
So in Python, we have this math module which contains a bunch of reusable functions for performing mathematical calculations. So let me show you how to use this module. On the top we type import math all in lowerc case. With this we can import the math module. Now, math is an object like a string, so we can access its functions or more accurately, its methods using the dot operator.
So if you type math, look, these are all the mathematical functions available in this module. For example, we can call the ceil method to get the ceiling of a number. So, if we pass 2.9 here and then print the result, we should see 3. Let me delete all this other code here. Alright, let's run this program. There you go. So we get 3.
Another useful method is the floor method. So let's give that a try. Floor of 2.9. What do you think we're going to get? We get 2. Now, there are so many functions built in this module, and we don't really have time to go through all of them. But let me show you how you can learn about them on your own. Open up your browser and search for Python 3.7 math module.
Make sure to add the version Python 3 because the math module in Python 2 is slightly different from the math module in Python 3. So Python 3 math module. Now, here you can see the documentation for this module. Let's go, let's have a look. If you scroll down, you can see the list of all the functions and their explanation.
So as an exercise, I encourage you to spend five minutes, have a quick look at this documentation and see what functions are there for you in case you need them. In this tutorial, I'm going to talk to you guys about if statements in Python. If statements are extremely important in programming and they allow us to build programs that can make decisions based on some conditions.
So if some condition is true, we're going to do certain things, otherwise we're going to do other things. Here's an example. Over here I've got this text file with a bunch of rules for our program. If it's a hot day, perhaps we want to tell the user it's a hot day, so make sure to drink plenty of water. Otherwise, if it's cold. So here's another condition. If this condition is true, we're going to tell the user it's a cold day, so wear warm clothes.
And otherwise, if it's neither hot or cold, we want to tell the user it's a lovely day. So let me show you how to write a program that simulates these rules. So, back to our program. Here we start by defining a boolean variable is hot. We set this to true. Next, we add an if statement. So if here we need to add a condition. In this case, we're going to use our boolean variable IS hot.
Now, if this eval is true, then we’re going to do certain things. In this case, we want to tell the user, hey, it's a hot day. Drink plenty of water. So back to our program. After our condition, we add a colon. Now, note that when I press enter, PyCharm automatically indents our cursor. Now, any code that we write here will be executed if this condition is true. Otherwise, it will be ignored.
Here's an example. Let's write a print statement. Here I'm going to use double quotes because I want to use an apostrophe in our string. So it's a hot day. Now let's press enter. You can see the cursor is still indented. That means we can write more code that will be executed if this condition is true. In this case, let's say we don't want to write any extra code.
So to terminate this block, we need to press shift and tab. Now, the cursor is at the beginning of the line. So let's write a print statement. What a message like enjoy your day. Now, when we run this program, because this condition is true, we're going to say this message followed by the second message. Take a look. So run. There you go.
It's a hot day. Enjoy your day. But if I go over here and change this boolean value to false and run the program again, our first message disappears and we only see the second message. Enjoy your day. So this is how if statements work. Now back here, we can add another print statement. Let's say drink plenty of water.
Now because this print statement is also indented, it will be executed if this condition is true. So I'm going to revert is hot to true and run the program one more time. There you go. So it's a hot Day, drink plenty of water and enjoy your day.
Alright, now let's add a second rule here. If it's hot, we're going to execute these two lines. Otherwise, if it's not hot, we want to print a different message. So here we remove the indentation and type else colon now when we press enter once again our cursor is indented. So the code that we write here will be executed if this condition is not true.
So here we can print It's a cold day. Print, wear warm clothes. Now let's run our program one more time. So we get the messages about a hot day followed by enjoy your day. We don't see any messages about a cold day. Now if we go back here on the top and change this boolean value to false and run our program, we see a different set of messages. It's a cold day, wear warm clothes, and enjoy your day.
But there's a problem with our program. If it's not hot, it doesn't necessarily mean that it's cold. Maybe it's a lovely day. So the absence of heat doesn't mean it's cold. Back to our conditions here on line four we have this rule that says if it's a cold day, then print this messages.
Otherwise, if it's neither hot nor cold, then say it's a lovely day. So to implement this rule we need to go back to app py and define another variable. So let's say is cold. We set this to true. Now here we need to add a second condition. So after our first if statement, we can use an elif statement to define a second condition. Here's how it works.
So el if, which is short for else if or otherwise if. Now here we add another condition, so is cold. So if it's cold, we want to execute these two lines. So let's cut these from here and move them under our second condition.
And finally, if none of these conditions are true, we want to print a different message. It's a lovely day. So right now is hot, is false, is called is true. So when we run this program, Python interpreter is going to execute the first if statement.
In this case, because our condition is false, these two lines will be ignored. Then Python interpreter will look at line seven, it will evaluate this condition. In this case, it’s true. So we're going to see these two messages on the terminal. Now, in this case, because one of these conditions was true, this else statement will be ignored. So we are not going to see this message.
And finally, as before, we are always going to see this message. So let's run our program. There you go. It's a cold day, wear warm clothes and enjoy your day. Now back to the top. If we change is cold to false, it's neither hot nor cold. So it's going to be a lovely day. Let's run the program.
And here you go. It's a lovely day, enjoy your day. So this is the basic of using if statements. As you can see, they're very useful in programming and with this we can build all kinds of rules into our programs.
Okay, here's an exercise for you. Imagine the price of a house million. Now, if the buyer has good credit, they need to put down 10% of the price of this property. Otherwise they need to put down 20%. Write your program with these rules and display the down payment required for a buyer with good credit. You will see my solution next.
Alright, let's define a variable for the price of this house. So price. We set this to 1 million. So 1 with 6, 0. Next we need a variable to tell if this buyer has good credit. So has good credit. And we set this to true. Now we need an if statement. So if has good credit.
It's true on. Here we need to calculate the down payment. So down payment should be equal to 0.1 times the price that is 10% of the price of this property. Otherwise the down payment should be 0.2 times price. Finally, we remove the indentation and print. Here we can use a formatted string.
First we add a label down payment. And right after that we add a placeholder or a hole for our down payment variable. So curly braces, down payment. Let's run this program. So 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 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 is better.
In this tutorial, I'm going to talk to you guys about the logical operators. In Python, we use these operators in situations where we have multiple conditions. Here's an example. Let's say we're building an application for processing loans. If an applicant has income and good credit, then they're eligible for a loan.
So in this example we have two conditions. One is having high income and the other is having good credit. So if both these conditions are true, then the applicant is eligible for a loan. So 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 Python programming language.
Pretty much any programming language that supports if statements also supports the logical operators. So back to our program. Let's define two variables. Has high income, we set this to true. And another one has good credit, we also set this to true.
Now our if statement, if has high income is true and has good credit is also true, then we're going to print eligible for loan. So this is where we are using the AND operator. So if both these conditions are true, then this message will be printed. If one of them is false, we're not going to see this message. Let's try this out.
So I'm going to run this program. So we see eligible for loan. But if we change either of these conditions to false and run the program again, look, the message disappears. So this is the logical AND operator. We also have the logical OR, and we use that in situations where we want to do certain things if at least one of the conditions is true.
For example, let's change the rule for this program such that if the applicant has high income or good credit, then they're eligible for a loan. So if either or both these conditions are true, then the applicant is eligible. Now back to our program. We can implement this rule by using the logical OR operator. So we simply replace AND with OR.
Now when we run this program, we're going to see this message because at least one of our conditions is true. Let's take a look. So the applicant is eligible for loan because they have good credit. If we change this to false but set the other condition to true and run the program, we still see the same result. But if both these conditions are false, then we're not going to see this message anymore.
So this is the difference between these operators. With the logical AND operator, both conditions should be true. With the logical OR operator, at least one condition should be true. We also have another logical operator called NOT, and that basically inverses any boolean value we give it. If we give it a true boolean value, it converts it to false.
For example, let's make up a new rule. If an applicant has good credit and doesn't have a criminal record, then they're eligible for a loan. Let me show you how to implement this. So we go back to our program. In this example we don't need the first variable, so let's delete that.
Let's set this variable to true. We also define another variable like has criminal record. And we set this to false. Now we want to check to see if this applicant has good credit and not a criminal record. This is where we use the NOT operator.
So if they have good credit and not a criminal record, so in this example has criminal record is set to false. When we use the NOT operator, this basically gets changed to true. So we'll have two conditions that are true.
Here's one and here's another one. So our applicant is eligible for loan. And when we run this program, we see this familiar message. However, if an applicant has a criminal record, so let's change this to true. Now, when we run this program, we can see our applicant is not eligible because when we apply the NOT operator on this variable, we'll get false.
So true changes to false and we'll end up with two conditions, one true and the other is false. So, the result is false. And that's why this message is not printed.
So this is all about the logical operators in Python. In this tutorial, I'm going to talk to you guys about the comparison operators. In Python, we use comparison operators in situations where we want to compare a variable with a value. For example, if temperature is greater than 30, then we want to print it's a hot day.
Otherwise, if it's less than 10, it's a cold day. Otherwise, it's neither hot nor cold. And by the way, here I'm talking about Celsius, not Fahrenheit. So to build these rules into our program, we need to use comparison operators. Back to app py I've defined this temperature variable. Let's write an if statement, if temperature.
Now we want to check to see if this is greater than 30. So we use the greater than operator. If this is greater than 30, we want to print it's a hot day. Otherwise let's just print it's not a hot day. Now, when we run this program, we're going to see the second message because 30 is not greater than 30. So our first condition evaluates to false.
Let's verify that, run it's not a hot day. Now, if we change the temperature to 35 and run this again, we're going to 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's a piece of code that produces a value. So more accurately, 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's the equality operator.
So if the temperature equals to 30, then we can say it's a hot day. Note that this is different from the assignment operator that has only one equal sign. You can see, if we use one equal sign here, we immediately get this red underline. Because this is simply an assignment statement, we're changing the value of the temperature. We're setting the value of the temperature variable to 30.
We are not comparing it with something else. So we don't have a Boolean expression. We are not producing a Boolean value. Okay, so our equality operator has two equal signs. And finally, we have not equal, which is an exclamation followed by an equal sign.
Now here's an exercise for you. You have probably seen that when you fill out a form online, sometimes the input fields have validation messages. For example, let's say we have an input field for the user to enter their name. Now, if the name is less than three characters long, we want to display a validation error like name must be at least three characters.
Otherwise, if the name is more than 50 characters long, then we want to display a different validation error like name can be a maximum of 50 characters. Otherwise, if the name is between 3 and 50 characters, then we just want to tell the user that name looks good. So go ahead and write a program to implement these rules.
Alright, let's define a variable called name and set it to, let's say, J. So we're assuming this is what the user types into an input field. Now we want to get the number of characters in this string. So we use the len function, right? Len(name). When we print this, we get one, right? You have seen this before.
Now here we want to use an if statement. So if len of name is less than three, then we want to print name must be at least 3 characters. Now here we need a second condition to check the upper limit. So el if len of name is greater than 50, then we want to print a different message.
Name must be a maximum of 50 characters, okay? And otherwise, so else if none of these conditions is true, that means the name looks good. So print 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 go back here and type something really long and then run our program, we're going to see a different message. Name must be a maximum of 50 characters.
And finally, if we type a proper name here, like John Smith and run our program, we get name looks good. Here's another good exercise that combines many of the materials you have learned so far. So earlier you built a program to convert someone's weight from pounds to kilograms. Now we want to extend this program and allow the user to enter their weight in either kilograms or pounds, and then we'll convert it to the other unit. Here's how our program is going to work.
So I enter my weight in pounds, so 160. Now it's telling me is this in pounds or kilograms? So here I need to enter L for pounds or K for kilograms. And by the way, this program is not K sensitive. So whether I enter a capital L or a lowercase L, it takes it as pounds. Now it tells me you are 72 kilos.Let's run this program one more time. This time I'm going to enter my weight in kilos. So 72 is the weight, and the unit is kilograms. OK? And it says you are 160 pounds.
So go ahead and spend a few minutes on this exercise. You will see my solution next. Alright, so first let's ask the user to weight. So we use the input function weight colon. We get the return value and store it in a variable called weight. Now the second question. So one more time, we use the input function L for pound, lbs 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 unit equals L, then we need to convert this weight into kilograms.
However, with this implementation we are only allowing the user to enter a capital l if they enter a lowercase l. This code is not going to work. So this is where we use the upper 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 upper method. This will convert whatever the user enters to uppercase and then we'll compare it with a capital L.
Now, if this condition is true, then we need to get the weight and multiply it by 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.
So right here, when we call the input function, we can get the return value and pass it to the int function. So we call the int function and give it the return value of the input function. Now the int function will return an integer so we can store it in this weight variable.
So here's the converted weight. Let's store it in a variable called converted. Then we print here. We can use a formatted string. So we prefix this string with f. You are, we add curly braces to dynamically insert the value of converted variable. And finally we add kilos.
Otherwise, if the unit is kilogram, we need to divide the weight by 0.45. So once again, we type converted = weight / 0.45. And just to refresh our memory, this division operator returns a floating point number. But if we use double slashes, we’ll get an integer. In this case, I want to get a floating point number.
So finally, let's print a formatted string. You are curly braces converted pounds. Okay, now let's run this program and see what happens. So weight is 160 in pounds and that equals 72 kilos. Perfect. If we run it one more time and enter 72 kilos, we get 160 pounds.
In this tutorial, I'm going to show you how to use while loops. In Python, we use while loops to execute a block of code multiple times, and they are often useful in building interactive programs and games. In a future tutorial, I'm going to show you how to build a simple game using a while loop. So let's get started with the basics. We write a while statement, and right after that, we type a condition followed by a colon.
As long as this condition is true, the code that we write in this block will be repeatedly executed. Here is an example. We can define a variable like I, as in short for index and set it to one. Now, we set our condition to I less than or equal to 5. So as long as I is less than or equal to 5, we can print I on the terminal, and then we need to increment I by one.
So we set I to I + 1. The reason we do this is that if we don't do this, I will be one forever. So we'll end up with an infinite loop because this condition will always be true, one is always less than five. So in every iteration of this loop, we increment I by 1. So at some point, I is going to be 6, and then that is 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'm going to add a print statement, say done. So note that these two lines are indented, so they're part of the while block. Let's go ahead and run this program to see what happens.
So take a look. We get the numbers 1 to 5, followed by Done. So here's how this program gets executed. First we set I to 1. Now Python interpreter executes line 2. This condition is true because I is less than 5. So I is printed on the terminal and then incremented by one.
Then the control moves back to the beginning of the while loop so it doesn't go to the next statement. So we come back here. Now we are in the second iteration. In the second iteration, I is 2, and because 2 is less than 5, our condition is still true. So I will be printed on a terminal, and once again, it will be incremented by one.
So at some point, I is going to be six, and that's when this condition will be false. So our loop be terminated and then this done message will be printed on the terminal. So this is the basics of while loops.
Now let's make this program a little bit more interesting here. We can write an expression like this. We add a string, and in this string we add an asterisk, and then we multiply this string by I. So with this expression we can repeat a string. When we multiply a string by a number, that string will be repeated.
For example, if I is 2, this expression will produce a string with two asterisks. Okay, now let's run the program and see what we get. So we get this little triangle shape here, because in the first iteration I is 1. So one times an asterisk produces one asterisk. In the second iteration, I is 2.
So when we multiply two by one asterisk, we'll get two asterisks.
In this tutorial, I'm going to show you how to use a while loop to build a guessing game like this. So we have this secret number which is currently set to 9. Now the computer is asking me to make a guess. So let's say one. It's not right because the secret number is 9. I can try again to no, it's not right. Let's try again. So I only have three chances to make a guess. If I can't guess the number, the program tells me that I failed.
Let's




