Python Tutorials for Beginners – Learn Python Online


In this course you’re going to learn everything You need to get started with Python just be aware that I’ve designed this course for beginners So if you have some programming experience check out my other Python course for developers You can see the link on the top right corner of this video so Python is the world’s fastest-growing and most popular programming language not just amongst software developers, but also amongst mathematicians data analysts scientists accountants network engineers and even kids In fact, it’s the ideal programming language to learn first But what makes Python so special here are six reasons with Python You can solve complex problems in less time with fewer lines of code than many other languages That’s why huge companies like Google Spotify Dropbox and Facebook have embraced this beautiful and powerful language. Here is an example Let’s say we want to extract the first three characters of the text. Hello world This is the code we would have to write in c-sharp This is how we would do this in JavaScript. And here’s how we would do it in Python See how clean and simple the language is and that’s just the beginning Python is a multi-purpose language and you can use it for a wide range of jobs such as data analysis AI and machine learning writing automation scripts building web mobile and desktop applications As well as software testing or even hacking so if you want a high-paying long lasting career in any of these areas Especially AI and machine learning Python is the language to put those opportunities at your fingertips. In fact, according to indeed.com The average salary of a Python developer in the US was over one hundred and fifteen thousand dollars in March 2018 And here are four more reasons that make Python the most desirable language Python is a high-level language so you don’t have to worry about Complex tasks such as memory management as you do in C++ It’s cross platform, which means we can build and run Python apps on Windows Mac and Linux it has a huge community So whenever you get stuck There is someone out there to help and it has a large ecosystem of libraries frameworks and tools Whatever you want to do. It is likely that someone else has done it before because python has been around for over 20 years There are two versions of Python out there Python 2 Which is the legacy version of Python and is going to be supported until year 2020 and Python 3 Which is Python for the future in this course, you’re gonna learn Python 3 Hi, my name is Muhammed Ani, and I’m going to be your instructor in this course I’m a software engineer with 18 years of experience And I’ve taught way over a million people how to code or how to become top professional software engineers To learn more about me and my courses head over to code with mass comm. Alright now, let’s get started All right now we were ready to download and install Python The first thing I want you to do is to open up your browser and head over to python org on This page under the downloads. You can see the latest version of python currently. The latest version is 3.7 Chances are in the future when you’re watching this video. There is a newer version available Don’t worry, all the materials in this course will continue to apply with the future versions of Python. So go ahead and download Python Then run it if you’re on Windows, we’re going to see this checkbox here add Python to path this is very important. Make sure to take it. Otherwise, you’re not going to be able to follow the course So now go ahead and install it Now let’s verify that we have installed Python properly if you’re on Windows here in this search bar type CMD which is short for command prompt Dr. In command prompt type Python You can see we have successfully installed Python version 3.7 now to exit press ctrl-z and then enter If you’re on Mac, press command and space this opens up the spotlight search So here type terminal Terminal and Mac is like command prompt on Windows now Mac and Linux by default come with an older version of Python That is version 2. So if you type Python you can see Python 2 here. Let’s start what we want so press control D to exit and then run Python 3 and This verifies that we have successfully installed Python 3.7 So this environment you see here is what we call Python interpreter Which is basically a program that executes Python code we can type our Python code in a file and give it to this Interpreter or we can type our code directly here in this interactive shell So here we can write an expression like 2+2 in Programming an expression is a piece of code that produces a value So here when we add two plus two we get a value that is why we refer to this piece of code as an expression So enter we get four. Let’s try a different kind of expression Let’s see if two is greater than one We get true, which is an example of a boolean value. You’re gonna learn about these boolean values in the next section Now what if we type 2 is greater than 5 Enter we get false. So in programming, we have true and false which are similar to yes, and no in English Now what if we type 2 is greater than but we don’t add a second value here. Just press Enter We get a syntax error in Programming syntax means grammar. So just like we have the concept of grammar in the languages that we speak We have the exact same concept in programming if we write a sentence that is not grammatically, correct? Chances are some people may not understand that sentence. So in this example, we have this expression, which is incomplete It doesn’t have the right grammar or syntax That is why Python interpreter is complaining by returning an error So this interactive shell is a great way to quickly experiment with a bit of Python code But that’s not how we build real world applications to do that We need a code editor and that’s what I’m gonna show you in the next lecture When it comes to typing Python code you have two options You can use a code editor or an IDE Which is short for integrated Development environment an IDE is basically a code editor with some fancy features like auto completion Which means as you type code this feature helps you complete your code so you don’t have to type every character by hand It’s a productivity boosting feature It also gives you additional features like debugging which means finding and fixing bugs in your programs testing and so on For both code editors and IDs are so many options out there The most popular code editors are vs code atom and sublime You can use the code editor that you prefer in terms of the idea is again There are so many options out there The most popular one is pie chart in this course I’m gonna use vs code or Visual Studio code because that’s my favorite code editor later in the course I will show you how to install a plugin or an extension that will convert vs code to a powerful ID So before going any further head over to code that visual studio comm and download the latest version of vs code Now it vs code open on the top from the file menu go to open And somewhere on your desk create a new folder Let’s call this folder. Hello world and Then open it Beautiful now click this icon on the top this opens up the Explorer panel in this panel You can see all the files and folders in your project. So let’s add a new file and Call that app that PI. So all our Python files should have the PI extension press Enter now, let’s close this and type a bit of Python code in this lecture We’re gonna use one of the built-in functions in Python called print so in Python We have a lot of built-in functions for performing various kinds of tasks For example as a metaphor think of the remote control of your TV on this remote control You have a bunch of functions like turn on turn off change the channel change the volume and so on These are the built-in functions and your TV We have the same concept in Python and many other programming languages so one of these built-in functions that comes with Python is print and We can use this to print something on the screen now whenever you want to use a function you should open and close parenthesis in Programming we say we’re calling the print function calling a function means executing it Now let’s display the hello world message on the screen whenever you want to work with text. You should put your text in between quotes either double quotes or single quotes now I’m gonna go with double quotes and add hello world and Then put a happy Persian cat here Beautiful save the changes with command and s on Mac or ctrl + S on Windows Now to execute this code we need to go back to command prompt on Windows or terminal on Mac But the good news is that we don’t have to switch programs here in vs code We have an integrated terminal. So press ctrl + backtick That is the key before number 1 on your keyboard That is just below the escape button So this is our integrated terminal now you front windows type Python if you’re on Mac or Linux type Python 3 and next to that at the name of our file that is up at PI and Here’s our hello world message in the terminal beautiful Now, let’s take this to the next level and make it a little bit more interesting let’s close this terminal window by pressing ctrl and backtick and Add a second line of code So one more time print This time let’s add quotes with a star in between them Now, let’s see if you want to repeat this star ten times. So here we can multiply this By 10 save the changes open up the terminal and run our program and You can see this star is repeated 10 times So as you see the instructions on our program are executed from top to bottom in order in the next lecture I’m going to show you how to convert this vs code to a powerful IDE for building Python applications In this lecture I’m gonna show you how to convert vs code to a powerful IDE by using an extension called Python with this extension or plugin we get a number of features such as linting which basically means Analyzing our code for potential errors. You also get debugging which involves finding and fixing errors We’ll look at this later in the course We also get auto completion which basically helps us write code faster So we don’t have to type every character we get code formatting which is all about making our code clean and readable Just like how we format our articles newspapers books to make them clean and readable We get unit testing which involves writing a bunch of tests for our code we can run these tests in an automated fashion to make sure our code is behaving correctly and finally we get code snippets which are Reusable code blocks that we can quickly generate so we don’t have to type them all by hand Now don’t worry about memorizing any of these as we go through the course. You’re going to learn about these features Now here in vs code on the left side. Click this icon This opens the extensions tab. So these are the extensions that we can install in vs code to bring in additional Functionality here under the recommend the tab You can see the python extension if you don’t see this simply type Python here on the top and here’s the extension to go ahead and install this and Then you’ll have to reload yes code Now here on the bottom right corner you can see this message Linter pilant is not in stock. So as I told you before linting is about finding potential errors in our code Linter is a program or a tool that analyzes our code and finds these potential problems now for Python There are several interceptor pilant is one of the most popular ones that this Python extension uses by default So we need to go ahead and install pylons as well now to do this first. We need to change our Python environment So if you look here on the bottom left corner, you can see the current python that is used in vs code That is python 2 point 6 point 9 on my machine chances. Are you see a different version here? So click here and In this list, make sure to select python 3 point 7 So this changes our Python environment to Python 3 point 7 and then we can install pilant by clicking this button Ok pilant is installed beautiful in the next lecture. I will show you how linting works In this lecture, I’m gonna show you linting and action so let’s start by writing some invalid code like this print space with no parentheses and Then hello work Earlier, I told you that print is a built-in function and whenever you want to use or call a function You should always use parentheses now to be more precise This is actually valid Python 2 code, but because we’re using Python 3 here This is invalid code from Python 3 point of view So now when I save the changes you can see this red underline here. Let’s hover our mouse Over this underline you can see this tooltip It’s coming from Pyland And here’s the error message missing parentheses in call to print did you mean print with parentheses? So this is the benefit of linting as you’re writing code, you can see potential problems in your code You don’t have to wait to run your program to see these errors so now if we put Parentheses here and save the changes you can see that red underline is gone. Let’s look at another error Let’s type two plus and then save the changes Earlier, we run this code in Python interpreters interactive shell there. We got a syntax or grammar error So if you hover your mouse here one more time You can see pylons is telling us that this is invalid syntax or invalid grammar It’s like an incomplete sentence. So this is linting in action Now let me show you a couple useful shortcuts here on the top. Look at the View menu Here we have this problems menu Look at the shortcut on Mac is shift command and M on windows is probably shift control M So as you’re working with vs code try to memorize these shortcuts because they really help you write code faster Now, let’s take a look At these problems panel. So this problems panel lists all the issues in your code in one place So if you have an application with multiple files, this is really useful because some of those files may not currently be open So this linter Pyland will analyze all your files and if it finds any issues It will list them here in the problems panel. Now, you can also put this on the right side of your screen So let’s put it here So as you write code these problems will appear here. Now. Let’s fix this issue so I’m gonna add three here save the changes and you can see the problem disappear and One last thing before we finish this lecture Once again on the top, let’s go to the View menu. The first item is command palette This is a very important feature in vs code Once again, look at the shortcut that is shift command and P on Mac or shift control P on Windows This command palette you can execute various commands in vs Co if you type lint here you can see all commands related to linting as you can see all these commands are prefixed with Python because these Commands come with a Python extension that we installed earlier So these are additional features available to us in vs code. The first command here is select linter In this list, you can see various linters available for pilot So as you’re reading tutorials or talking to other people You will hear about linters such as flake ate my pie pep 8 and so on Different developers prefer different linters. I personally prefer pilant That is the most popular one and that’s the default linter set and the Python extension of vs code if you’re adventurous You can try using other linters on your own the difference between these linters is in how they find and report errors Some error messages are more meaningful or more friendly the others are more ambiguous So that’s all about linting in the next lecture. We’ll talk about formatting code In Python community we have a bunch of documents called Python enhancement proposals or peps here on Google if you search for Python peps You can see the list of all these paps under python.org slash dev slash paps Let’s have a quick look here So here are the paps you can see each PAP has a number and a title the one that is very popular amongst Python developers is pep 8 which is a style guide for Python code a Style guide is basically a document that defines a bunch of rules for formatting and styling our code if you follow these conventions The code that you write will end up being consistent with other people’s code now if you have time you can go ahead and read this PAP 8 documentation, but if not, Don’t worry because throughout this course I’m gonna explain the key things in pep 8 in this lecture I’m gonna show you a tool that helps you automatically format your code according to pap 8 So back in vs code, let’s write some Python code x Equals one here. I’m declaring a variable and setting it to one if you’re not familiar with variables. Don’t worry in the next section You’re gonna learn about them So according to pep 8 this code is considered ugly Because by convention we should add a space around this equal sign or the assignment operator Now since you’re starting out with Python, you probably don’t know these rules So let me show you a tool that helps you automatically format your code. Let’s revert this back to its original state Now we need to go back to the command palette remember? So it’s right here under view and the shortcut is shift command and P Here if you search for format, you can see this command format document the first time you execute this command You’re going to see this message here Formatter Auto kept 8 is not installed. So there are a bunch of tools for formatting Python code The most popular one is auto kept 8 and this is the tool that this Python extension We installed uses to format our code. So let’s go ahead and install this Good Now one more time, let’s open up the command palette and execute format document See is tool automatically formats our code beautiful. Let’s take a look at another example I’m going to declare another variable Y and set it to two and a variable with a long name like unit Underlined price. I’m set this to 3 Now some developers have this habit of formatting their variable declarations like this So they put all these Equal signs in the same column according to pepp 8 this is considered ugly So once again, let’s format our code That is better beautiful. Now, let me show you a trick Opening up this command palette and searching for format document every time is a little bit time-consuming So I want to show you how to have your file automatically formatted as soon as you save the changes On the top. Let’s go to the code menu preferences and settings Here in the search box search for format on save So we have this option editor format unsaved take this Now back to app top I I’m gonna change the formatting of these lines make them really ugly Now as soon as I save the changes You can see my code is reformatted beautiful So you have learned that in order to run this Python program We’ll have to open up the terminal window and run Python on windows or Python 3 on Mac and an app that pi This is a little bit tedious. So let me show you a shortcut Once again, let’s go to the extensions panel here search for code runner There are multiple code runners out there the one that I’m talking about is this one with the yellow icon So go ahead and install this and then reload yes code Now instead of opening up the terminal and manually typing Python after pi All you have to do is to press ctrl, alt and in You can see the output here beautiful just be aware of that If you make any changes, you’ll have to save the changes before using this shortcut Otherwise you’re going to see the old result now. There is a tiny problem here So you can see this is the command that is executed to run this Python program So by default this command is using Python – U and here is the name of our file if you’re on Windows That’s perfectly fine But if you’re on Mac, you know that Python refers to Python – here we want to change this to Python 3 This is very easy Once again on the top under the code menu, let’s go to preferences settings and then here Under this dot go to open settings that JSON Now here in the search bar type code – runner dot executors map So these are the default settings used by this code runner extension You can see this extension support executing code in a lot of languages like JavaScript Java and so on now if you scroll down Here we can see Python and in front of that you can see the command that is used to execute Python code we need to change this However, we cannot change the default settings. We should change the user settings. So on the right side after the last setting type a comma and then in quotes type code – runner dot executors map and then press enter This will automatically copy all the settings on the left side to the right side Now we can easily Change one of this. So here’s Python. Let’s change the command to Python 3 You only have to do this if you’re on Mac, and by the way Sorry, if I have mentioned Windows and Mac a few times throughout this course, that’s pretty much it We are not going to differentiate between Windows and Mac in the future. So save the changes and we’re done So I’ve got a few questions for you guys I want to see if you have been really paying attention to this video or not You better have so here is the first question for each question. I want you to pause the video Think about the answer for a few seconds when you’re ready continue watching. So here’s the first question. What is an expression? An expression is a piece of code that produces a value Here’s an example of an expression. What do you think is the value of this expression? Well here we have this string. We’re multiplying this by 3 So the result will be a string of three asterisks like this Here’s another question. What is a syntax error a syntax error is a kind of error that is due to bad syntax or bad grammar in the code and Finally the last question. What does a linter do a Linter is a tool that checks our code or potential errors mostly in the category of seen tactical errors So if you have grand medical issues in our code, the linker will tell us before running our program Okay, that’s it for now if you like more quizzes and programming exercises look at the link below this video and if you enjoyed this video I hope you have please support me by giving a thumbs up Please like this video and share it with others in the next section. We’re going to look at the fundamentals of Python You Well, hello Marsh here thank you for watching my Python tutorial I wanted to let you know that this tutorial is the first two hours of my Complete Python course where you will learn how to use Python in real-world scenarios such as data analysis and visualization Automating repetitive boring tasks that involve working with files and folders spreadsheets PDFs data compression sending emails web crawling Consuming API is like Yelp to get information about businesses and much much more. This course comes with a 30 day No questions asked money back guarantee and a certificate of completion If you’re interested, click the link below this video to access the course Let’s start this section by a discussion of variables which are one of the core concepts in programming We use variables to store data in computer’s memory. Here are a few examples I’m gonna define a variable called students under line count and setting it to a Thousand when we run this program Python interpreter will allocate some memory and store this number thousand in that memory space Then it will have this variable reference that memory location So this variable is just like a label for that memory location We can use this variable or this label anywhere in our program to get access to that memory location and the data is stored there so now if we print students count and run our program we will get The number of thousand so this is the basic of variables Now what kind of data can be a store in computer’s memory? Well, we have several different kinds of data in this section We’re going to look at the built-in primitive types in Python primitive types can be numbers boolean and strings Let me show you so here we have a whole number we refer to this as an integer in programming We can also have numbers with a decimal point. Let’s take a look So rating we set this to four point nine nine this is what we call a float Or a floating-point number and this terminology is not specific to Python in the future when you learn a new Programming language. You’re going to hear these terms again Now, let’s take a look at an example of a boolean is Published we set this to true or false These are examples of boolean values in programming So boolean values can either be true or false and these are exactly like yes and no in English Later in the course. You will learn that will use these boolean values to make decisions in our programs For example, if the user is an admin user perhaps we want to give them extra permissions So these are the boolean values now take into account that Python is a case sensitive language Which means lower case and upper case characters have different meanings So boolean values should always start with a capital letter Like what you see here if we type false or false These are not accepted boolean values in Python only what you see here is a valid boolean value so false or true and Finally, let’s take a look at an example of a string. So course under line name We set this to your string like Python Programming so string as I told you before is like text Whenever you want to work with text in your programs, you need to surround your text with quotes So these are the basics of variables So these are the variables from the last lecture Now, I’ve got a question for you. There are four things that have consistently used in this program Can you spot them if you want you can pause the video think about this for a few seconds and then continue watching? So here are those four things the first thing is that all my variable names are descriptive and meaningful So students count represents the number of students for a course, or course name Clearly explains that this variable holds the name of a course One of the issues that I see a lot amongst beginner programmers is that they use mystical names for their variables? Something like this CN has ensured for course name when someone else reads this code They have no idea what CN stands for or they use variable names like c1 when I look at that code I wonder where is c2 and what is the difference between c1 and c2 so these variable names are very mystical That’s a bad practice. Make sure your variable names are always descriptive and meaningful because this makes your code more maintainable now there are times that you can use short variable names like X Y Z if you’re dealing with things like Coordinates, so that’s an exception now The second thing that I have consistently used in this code is that I have used lowercase letters to name my variables So here we don’t have Course name all in capital or in title case all letters are lowercase right Let’s delete this the third thing that I’ve consistently used here is that I have used an underscore to separate multiple words And I’ve done this to make my variable names more readable because in Python we cannot have a space in Variable names so we cannot have course name and if you put these two words together It’s a little bit hard to read That’s why we use an underscore and the fourth thing that I have used consistently here is that I have put a space around this equal sign Again, that’s one of the issues. I see a lot amongst beginners. They write code like this This is a little bit ugly. This is what we call dirty code dirty Stinky smelly you should write code that is clean and beautiful So other people can read it like a story like a newspaper article It should be formatted properly and that’s why we have pep 8 in Python Now the good thing is if you forget these rules when you save the changes Auto-pay 8 kicks in I didn’t automatically reformat your code But that aside you should always give yourself the habit of writing clean code without relying too much on the tooling So these are all the best practices about naming your variables next. We’re going to look at strings in more detail So here we have this course variable set to Python programming as I told you before whenever you work with text You should surround your text with quotes. You can either use double quotes or single quotes That’s more of a personal preference, but quite often we use double quotes You also have triple quotes and we use them to format a long string For example if you have let’s say a variable message That is the message. We want to include in the body of an email You can use triple quotes to format it like this Hi, John This is Marsh from code with marsh comm blah blah blah. So that’s when we use triple quotes Now we don’t need this in this lecture. So delete. Let me show you a few useful things you can do with strings First of all, we have this built-in function in Python for getting the lengths of strings What is a function a function is basically a reusable piece of code that? Carries out a task as a metaphor think of the remote control of your TV On this remote control you have buttons for different functions, like turn on turn off change the channel and so on These are the built-in functions in your TV in Python and many other programming languages We have the exact same concept. So we have functions that are built into the language on the platform You can reuse these functions to perform various tasks So here we can use the built-in Len function to get the length of a string which means the number of characters in that string Now whenever you want to use a function you should use parentheses Now we say we’re calling this function which basically means we are using this function now some functions take Additional data which we refer to as arguments These arguments are inputs to these functions. So this Len function takes an input or an argument Here we pass our course variable and this will return the number of characters in this string so let’s print that and See what we get run the program we get 18 because we have 18 characters here Let’s look at another example If you want to get access to a specific character in this string you use the square bracket notation So here we add course square brackets to get the first character you use the index 0 So in Python like many other languages Strings are 0 index which means the index of the first cat or the first element is zero so now when we print this Will get P. Okay Now you can also use a negative index Like minus one. What does that mean? Well if zero represents the first character here What do you think negative one represents that takes us back to the end of this string? So that returns the first character from the end of this string, let’s run this program. You will see it will get G There you go Using a similar syntax you can slice strings Let me show you so I’m gonna duplicate this line and remove negative one now Let’s say we want to extract the first three characters in this string. So here we need two indexes the start index colon the end index So this will return a new string that contains the first three characters in This course variable that will be P Y and T So the index of these characters are 0 1 and 2 So that means the character at the end index is not included. Ok Let’s run the program and make sure we get the right result. There you go py T Now what if we don’t include the end index? What do you think we’re gonna get? It’s common sense. We start from index 0 and go all the way to the end of this string So this will return a new string that is exactly the same as the original string. Let’s take a look So we get Python programming Now what if we don’t include the start index but include the end index. What do you think? We’re gonna get? Once again, it’s common sense. So by default Python will put 0 here so it will start from the beginning of this string So when I run this program we should get py t one more time. There you go. And Finally as the last example if we don’t include the start And the end index this will return a copy of the original string Let’s look at this. So we get Python programming Now you don’t have to memorize any of these. Just remember we use the Len function to get the length of a string we use bracket notation to get access to a specific element or a specific character and We use this notation to a slice a string So we have this string here Python programming Now, let’s say we want to put a double quote in the middle of this string. There is a problem here Python interpreter Sees this second string as the end of the string So the rest of the code is meaningless and invalid. How do you solve this problem? Well, there are two ways one way is to use single quotes For our string and then we can use a double code in the middle of this string But what if for whatever reason perhaps for being consistent in our code we decided to use double quotes How can we add another double code in the middle of this string? Well, we can prefix this with a backslash Backslash in Python strings is a special character We have a jargon for that called escape character. We use it to escape the character after Let me show you what I mean. So let’s print this course and run this program What’s going on here we don’t have the backslash because we use that to escape this double code and basically Displayed here So backslash is an escape character and backslash double quote is an escape sequence In Python strings. We have a few other escape sequences that you should be aware of Let me show you so in Python We use high sign to indicate a comment a comment is like additional note that we add to our program It’s not executed by Python interpreter Okay. So here are the escape sequences you have seen backslash double quote. We also have backslash single quote So we can use that to add a single code here Let’s run the program Here it is, beautiful We also have double backslash. So if you want to include a backslash in your strings You should prefix it with another backslash let me show you so when we run this we get python one backslash programming and finally we have Backslash n which is short for newline So now if I add a backslash n here see what we get We get a new line after Python so programming will end up on the second line So these are the escape sequences in Python Here we have two variables first and last let’s say we want to print my full name on the console So we can define another variable full Set it to first Then concatenate it with a space and one more time concatenate it with last now when we print full We get my full name on the console beautiful Now this approach are using concatenation to build a string is okay But there is a better and newer approach we can use formatted strings So here we can set full to this string and Prefix it with an F which can be lowercase or uppercase This formatted string doesn’t have a constant value like these two strings here It’s actually an expression that will be evaluated at runtime. So Here we want to add our first name. We use curly braces to print the value of the first variable After that, we had in your space and then we add curly braces one more time to print The last name so at runtime this expression will be evaluated What we have in between curly braces will be replaced at runtime Now, let’s run this program one more time We get the exact same result just be aware that you can put any valid expressions in between curly braces So earlier you learned about the built-in Len function We can call Len here to get the length of this string Let’s run this program one more time. So we get four We can also replace last with an expression like this 2+2 Let’s run this program we get 4 & 4 So when using formatted strings you can put any valid expressions in between curly braces In This lecture we’re going to look at a few useful functions available to work with strings So earlier you learned about this built-in Len function This function is general-purpose. So it’s not limited to strings later I will show you how to use this function with other kind of objects But in Python, we have quite a few functions that are specific to strings. Let me show you so here if we type course dot C all these are functions Available on strings now in precise terms. We refer to these functions as methods This is a term in object-oriented programming that you will learn about later in the course for now what I want you to take away is that everything in Python is an object and Objects have functions we call methods that we can access using the dot notation So here course is an object. We use the dot notation to access its functions or more accurately methods Let’s take a look at a few of these methods. We have upper to convert a string to uppercase now Let’s print this and run the program Here is what we get beautiful now note that the metals that you call here return a new string So the original string is not affected. Let me show you so print course Run the program one more time. Look, this is our original string, right? So course the upper Returns a new string a new value we can store it in a variable like course underlined capital like this Now to keep this demo simple and consistent. I’m gonna revert this back and use a print statement We also have the lower method to convert a string to lowercase. We also have Title which will capitalize the first letter of every word. So if our string was like this When we call the title method we get Python programming as you see here, okay? Another useful method is strip and we use it to trim any white space at the beginning or end of a string This is particularly useful when we receive input from the user. Let me show you so let’s imagine The user entered a couple of white spaces at the beginning of their string When we call course that strip Those white spaces will be removed. Take a look So note that in the first three examples, we have those white spaces, but in the last one it is removed So a strip removed the whitespace from both the beginning and end of a string We also have L strip, which is short for left strip and our strip, which is short for right strip so it will remove the white space from the end of a string if You want to get the index of a character or a sequence of characters in your string? You should use the find method and mosura so course that find so as an argument here, we pass another string we can pass a Character or a series of characters. Let’s find the index of Pro Run the program. So the index of Pro is 9 So if you start from 0 here all the way to 9, this is the index of Pro Ok Now as I told you before python is a case sensitive language So if I pass a capital P here, obviously We don’t have these exact characters in our string. So let’s see what we get We get negative 1 that means this string was not found in the original string Another useful method is replaced so We call replace With this we can replace a character or a sequence of characters with something else so let’s say we want to replace all lowercase Peas with J with this we get jython, Jeremy whatever that means and finally if you want to check for the Existence of a character or a sequence of characters in your string you can use the in operator Let me show you so print rewrite an expression like this pro in chorus So this is an expression as I told you before an expression is a piece of code that produces a value So this expression checks to see if you have Pro in course the difference between this expression and Calling the find method is that the find method returns the index of these characters in our string? But as this expression returns a boolean, so it’s a true or false. Let me show you so run the program we get the boolean true and Finally, we have the not operator and we use that to see if our string does not Contain a character or sequence of characters so Let’s change this to swift not in course When this expression is evaluated, what do you think? We’re gonna get? Well, we don’t have Swift in this string So not in we’ll return true. Let’s take a look. There you go So these are the useful string methods next we’ll look at numbers In Python, we have three types of numbers two of these you have already seen before they are integers and floats we also have Complex numbers so complex numbers in math are in the form a plus bi Where I is the imaginary number now if you’re not familiar with this concept, don’t worry This is something that is used a lot in mathematics and electrical engineering if you want to use Python to build web applications You’re never gonna use complex numbers, but let me quickly show you the syntax for representing complex numbers Instead of I we use J. So here is an example 1 plus 2 J So X now is a complex number and by the way As I told you before this is just a comment or an additional note in our program when we run this program anything after this hash sign will be ignored so These are the three types of numbers we have in Python for all these types of numbers. We have the standard arithmetic operations that we have in math, let me show you so we have addition Subtraction multiplication division But we actually have two different types of divisions, let me show you first let’s run this program so with this division operator Which is a slash we get a floating-point number if you want an integer, you use double slashes Let me show you So double slash run the program We get 3, ok. We also have modulus, which is the remainder of a division and finally Exponent, which is left to the power of right? So 10 to the power of 3 will be a thousand These are the standard arithmetic operators now for all these operators. We have a special operator called augmented Assignment operator, let me show you so let’s imagine We have X set to 10 we want to increment X by let’s say three we can write an expression like this x equals x plus three or we can use an Augmented assignment operator that is a little bit shorter. So we write x plus Equal three these two statements are exactly the same Now here I’m using Addition as an example. You can use any of these operators here Next I’m going to show you some useful functions to work with numbers In this lecture, we’re going to look at a few useful functions to work with numbers so we have this built-in function round For rounding a number. So if we pass 2.9 here and print the result we’ll get 3 We have another useful built-in function called ABS which returns the absolute value of a number. So if you pass negative 2.9 here we’ll get Positive 2.9 Technically we have only a handful of built-in functions to work with numbers if you want to write a program that involves complex Mathematical calculations you need to use the math module a module is like a separate file with some Python code So in Python, we have this math module which includes lots of mathematical functions or working with numbers But we need to import this module so we can use it On the top we type import math now math in this program is an object so we can use the dot notation to see all the functions or more accurately all the methods available in this object as an example we have Math dot seal for getting the sealing of a number. So if you pass 2.2 here and run this program we get 3 Now in this math module, we have lots of functions. Let me show you how to find the conflict list Here on Google search for Python 3, make sure to add the version number math module on this page You can see all the functions in the math module. So in this lecture, we looked at math dot seal We also have math but copy sign fabs and so on as an exercise I encourage you to play with a couple of functions in this module Alright now, let’s take a look at another useful built-in function in Python We use the input function to get input from the user As an argument to pass a string This will be a label that will be displayed in the terminal you will see that in a second. So let’s add X : now this function returns a string So we can store it in this variable now, let’s imagine that Y should be X plus 1 Save the changes now Don’t run this program using the code runner Extension because code Runner by default runs your program in the output window Which is read-only so you won’t be able to enter a value So open up the terminal using ctrl + backspace once again, if you’re on Windows type Python if you’re on Mac or Linux Type Python 3 and then app that PI So here’s our label. Let’s enter a value like fun We got an error type error. What is going on here? well When we receive input from the user this input always comes as a string So this expression at runtime will look like this String 1 plus 1 note that the number 1 is different from string 1 because these are two different types now when Python sees this expression, it doesn’t know what to do because two objects can be Concatenated if there are of the same type So here we need to convert this string 1 to a number in Python We have a few built-in functions for type conversion we have int for converting a number to an integer We have float We have bull and Stir or string? now in this case We don’t need to convert eggs to a string because X is already a string if you don’t believe me Let me show you so I’m gonna comment out these few lines Now let’s print Type of X. So type is another built-in function We pass an object as an argument and it returns its type Also, I’m gonna comment out this line because that’s the bad boy We don’t want to execute this save the changes back in the terminal. Let’s run this program one more time Enter 1 look This is what the type function returns. Don’t worry about the class. We’ll talk about classes later in the course so the type of X is histor or string So let’s delete this line To fix this problem. We need to convert X to an integer and Then we can print both x and y using a formatted string Remember so we had an F close now here. We add a label like X then we’ll add a field So here we want to print the value of X variable after that, we add some more text and Finally, we want to print the value of y Let’s run this program one more time So here in the terminal Let’s enter 1 and here’s the result X is 1 and Y is 2 beautiful Now all these built-in functions are self explanatory The only tricky one is bull because in Python we have this concept of truthy and falsy Values these are values that are not exactly a boolean true or false But they can be interpreted as a boolean true or false So here are the false if values in Python Empty strings are considered false e so they’re interpreted as a boolean false number zero is also false e We have an object called nan which represents the absence of a value. We’ll look at this later in the course So whenever we use these values in a boolean context will get false Anything else will be true. Let me show you a few examples So in this interactive shell in Python, let’s convert Number 0 to bull that’s false II so we get false What about pool of 1 we get true if you pass a negative number will also get true If we pass a number larger than 1 like 5 we still get true so we only get false When we try to convert 0 to a boolean Now it strings. I told you that an empty string is false e so here we’ll get false Anything else is true. So even if I have a string that is false We’ll get true because this is not an empty string. It’s a string with a few characters That’s why it’s evaluated as true All right, once again it’s time for another quiz, let’s see if you have been really paying attention to this tutorial So here’s the first question, what are the built in primitive types in Python? We have strings numbers and boolean Numbers can be integers floats or complex numbers Here’s the second question. You have this variable fruit set to Apple. What do you think? We will see on the terminal when we print fruit of one Well using square brackets we can access individual characters the index of the first character is zero So this expression returns the second character, which is P What if you add a colon and negative one here? Well using the syntax we can slice a string Re stored index is one and our end index is negative one which refers to the first character from the end of the string Now when slicing a string the character at the end index or negative one is not included So with this expression we’ll get all the characters starting from the second character which is P all the way until we get to e so the result of this expression is Ppl Here’s another question. What is the result of this expression? Well, this is what we call the modulus operator and it returns the remainder of a division which is in this case one and Finally the last question. What do you think? We will see when we print wool of FOSS? Well earlier I told you about faulty values in Python so number zero an empty string and the non object These are all false if values anything that is not false is considered true. See here We have a string that has five characters. It doesn’t matter what those characters are This is not an empty string. So it’s not fall. See it’s true See, so when we convert it using the bull function We’ll get a boolean true and this brings us to the end of this section in the next section You’re going to learn the fundamentals of computer programming. I hope you have enjoyed this section and thank you for watching We’re gonna start this section by exploring comparison operators We use comparison operators to compare values. Here are a few examples So 10 is greater than 3 we get true. So what we have here is a boolean expression Because when this expression is evaluated we’ll get a boolean value. That is true or false Here is another example 10 is greater than or equal to 3 once again, we get true We also have less than so 10 is less than 20 we have less than or equal to Here’s the Equality operator. So 10 is equal to 10 What about this expression? What do you think? we’re gonna get we get false because these values have different types and they’re stored differently in the computer’s memory and Finally we have the nut equal operator So now with this expression we should get true beautiful we can also use this comparison operators with strings let me show you so we can check to see if bag is greater than Apple we get true because when we sort these two words bag comes after so it’s considered greater Now what about this one bag? equals capital bag We get false here is the reason Every character you see here has a numeric representation in programming Let me show you so we have this built-in function called Ord Don’t worry about memorizing this because you’re probably never gonna use this in the future But let me show you the numeric representation of the letter P So that is 98 in contrast Capital B is represented as 66 that is the reason these two strings are not equal. So These are the comparison operators in Python next. We’ll look at conditional statements In almost every program there are times you need to make decisions and that’s when you use an if statement Here is an example Let’s say we have a variable called temperature We set it to 35 Now if temperature is greater than 30, perhaps we want to display a message to the user. So we use an if statement if After if we add a condition which is basically a boolean expression an expression that produces a boolean value So if temperature is greater than 30 here We have a boolean expression if this expression evaluates to true the following statements will be executed Let me show you now here is the important part that a lot of beginners miss when you use an if statement, you should always Terminate your statement with a colon Now, let’s see. What happens when I press ENTER Our cursor is indented. So here we have two white spaces This is very important because using these Indentations Python interpreter will know what statements should be executed if this condition is true here, we want to print a message like It’s warm we can print another message as well Drink water so we can have as many statements as we want here as long as they are indented they belong to this if block Now when we finish here We should remove indentation to indicate the end of this if block so here we can add a print statement With a message like done. This statement will always be executed whether this condition is true or not Now note that when I save the changes This indentation you see here is going to be doubled up take a look save. There you go So when we save the changes auto kept eight reformat our code and uses four white spaces for indentation So one two, three four, it uses four white spaces because that’s what pepp eight recommends Alright now let’s run this program so because temperature is greater than 30 we see the first two messages and We see the dawn message regardless So if I change the temperature to let’s say 15 and run the program one more time look this dawn message is Executed whether our condition is true or not. So pay great attention to these indentations That’s one of the issues. I see in beginners code Let’s say they want both these print statements to be executed if the condition is true Accidentally, they remove the indentation on the fourth line and that’s why their program doesn’t work as they expect So be careful about this Now what if you want to have multiple conditions? we use an elephant so L if that is short for LS if Here we can add another condition another expression. So temperature is greater than 20 once again : Enter a by default here vs code is using two white spaces. So don’t worry about this as soon as you save the changes Those two white spaces will be converted to four white spaces So let’s print a different message It’s nice Save the changes now look all these lines are indented consistently you can have as many Elif statements as you want and Optionally you can also have an else statement So if none of the previous conditions are true, then what you have in the else block will be executed once again We add the colon annotation print Here we can add a message like it’s called Saying the changes in this case temperature is 15 So none of these two conditions will be true and we will see it’s called. Let’s run the program There you go In this lecture, I’m going to show you a technique for writing cleaner code So let’s say we’re building an application for University and we want to check to see if the person who’s applying For this university program is eligible or not So we start by defining a variable called age set it to 22 Now if H is greater than or equal to 18 colon print eligible Remove the indentation else colon print Not eligible Let’s run the program Make sure it works Beautiful now there is nothing wrong in this piece of code, but I want to show you a cleaner way to achieve the same result Instead of having a print statement here. We can define a variable like message and set it to this string That is the first step. So Message equals this string and then we will print this message Now when you have an if-else statement with this structure where you’re basically assigning a value to a variable you can rewrite this in a simpler way, so This is how it works. All we want to do over these few lines is to assign a value to this message variable Right, so we start with message We set it to eligible If age is greater than or equal to 18 else we set it to not eligible This statement is almost like plain English. So what we have on line 7 is Exactly equivalent to these four lines of code delete Save the changes run the program you can see this person is eligible if I change the age to 12 And run the program we get not eligible So what we have here is called ternary operator In Python we have three logical operators and we use these operators to model more complex conditions so these operators are and or and not Let’s see a real-world example of using these operators, so imagine we’re building an application for processing loans So we need two variables high income we can set this to true and Good underline credit we set it to true Now here’s the condition We want to implement if the applicant has high income and good credit score Then they are eligible for the loan. So if high income and Good credit, we add the colon and print eligible Now note that here. I have not compared the value of this variable with true that is one of the issues I see in a lot of beginners code. This is redundant and unprofessional Because high income is a boolean, so it’s either true or false. We don’t need to compare true with true so if this condition is true and This second condition is true, then we will print eligible in the terminal So save the changes and run the program obviously this person is eligible However, if one of these conditions is false, we will not see eligible in the terminal. So let’s add an else statement here and print Not eligible run the program We see not eligible So this is how the and operator works with and operator. If both conditions are true. The result will be true in Contrast with the or operator as long as at least one of the conditions is true. The result will be true So if I replace and with or here we should see Eligible in the terminal let’s run it one more time. There you go So these are the and and or operators Now, let’s take a look at an example of the nut operator. So I’m going to define another variable student set it to true Temporarily I’m gonna remove this expression and simplify it. We’ll come back to this later So let’s say if the person is eligible if they are not a student The nut operator basically inverses the value of a boolean. So in this case student is true When we apply the not operator the result will be false So in this case, our condition will be false and that’s why this print statement will not be executed Let me show you so save Run the program they are not eligible if student was false When we apply the nut operator will get true so our condition will be true and we’ll see it eligible Let’s run it one more time. There you go With this operators, we can model even more complex conditions here is an example a person can be eligible if they have either high income or good credit and They should not be used to do that. Let me show you how to implement this condition. So if high income Or good credit we want at least one of these conditions to be true. So we put these in Parentheses. We want to separate these from the other condition Which is not a student now the result of this should be true, which means at least one of these conditions should be true after that, we’ll add and not student and finally caught So with this operators you can model all kinds of real-world scenarios So here’s the example from the last lecture a person is eligible for a loan if they have high income and good credit and They are not a student. Now one thing you need to know about these boolean operators is that they’re a short circuit What do we mean by that? Well when Python interpreter Wants to evaluate this expression it starts from the first argument If this is true, it continues the evaluation to see if the second argument is also true So it continues the evaluation all the way to the end of this expression However, as soon as one of these arguments is false the evaluation stops. Let me show you what I mean So if I change high-income to false when Python interpreter sees this expression It starts here. It knows that high-income is false. So it doesn’t matter what comes after the result of this entire expression will always be false because at least One of the arguments or one of the operands is false. This is what we call Short-circuiting just like the short-circuit concept we have in electronics. So the evaluation stops as soon as one of these arguments evaluates to false We have the same concept with the or operator. So if I change these and operators to or Let’s see what happens With the or operator, we know that at least one of the arguments should be true So the evaluation stops as soon as we find an argument that evaluates to true in this case when Python interpreter Evaluates this expression it sees that high-income is false So it continues the evaluation hoping that the next argument will be true Here good credit is true. So evaluation stops and the result of this entire expression will be true so in Python logical operators are short-circuit In this lecture, I’m gonna show you how to chain comparison operators This is a very powerful technique for writing clean code. Here’s an example let’s say we want to implement a rule that says age should be between 18 and 65 Here’s how we can implement it. So we define a variable like age set it to 22 now if age is greater than or equal to 18 and Age is less than 65 then we print Eligible now, here’s a question for you. How do we write this rule in mass? We can write it like this Well more accurately we shall have an equal sign here, so age should be between 18 and 65. This is how we write this rule in math now. I’ve got some good news for you We can write the exact same expression in Python. So I’m going to move this up put an if statement here Line 4 and line 3 are exactly equivalent but as you can see line 4 is cleaner and easier to read so Let’s get rid of line 3 This is what we call chaining comparison operators All right, here is a little quiz for you I want you to pause the video and think about this quiz for 10 to 20 seconds. What do you think? We’ll see on the terminal when we run this program So pause the video figure out the answer when you’re ready. Come back continue watching All right, let’s see what happens when we run this program First we get this if statement in this case, we’re comparing two different objects for equality And these objects have different types. We have a number compared for this string So number 10 and string 10 are not equal that is why a will not be printed on the terminal So the control moves to the Elif part here. We have two boolean expressions. Here’s the first one here is a second one and They are combined using the logical end. So if both these expressions are evaluated to true Then this entire expression will be true and we will see beyond the terminal Let’s see if both these expressions are evaluated to true Here’s the first part Bag is greater than Apple. That is true. Because when we sort this words bag comes after Apple But look at the second part this expression is evaluated to false because bag is not greater than cat So when we applied the logical end between true and false The result will be false That is why this statement will not be executed. So the control moves to the else part and When we run this program the letter C will be printed on the terminal There are times that we may want to repeat a task a number of times For example, let’s say we send a message to a user if that message cannot be delivered Perhaps we want to retry three times now for simplicity Let’s imagine this print statement is equivalent to sending a Message in a real-world program to send a message to a user we have to write five to ten lines of code Now if you want to retry three times, we don’t want to repeat all that code. That is ugly That’s when we use a loop. We use loops to create Repetition. So here is how it works We start with four Number in we have a built-in function called range Now how many times we want to repeat this task? Let’s say three times. So we call range and pass three as an argument Now similar to our if statements we need to terminate this line with a colon Enter we get indentation. So in this block we can write all the statements that should be repeated three times Let’s do a print a message like attempt Save the changes Run the program so we have attempt printed three times beautiful. Now. What is this number? Let’s take a look It’s a variable of type integer. So let’s pass it as the second argument to the print function number Run the program. This is what we get zero one two So here we have a for loop this for loop is executed three times in each iteration Number will have a different value initially. It will be zero in the second iteration It will be one and finally in the last iteration. It will be two now here we can do something fun we can add one to this Run the program and now the message is that the print are kind of more meaningful or more user-friendly Like attempting number one attempting number two and so on We can take this to the next level so we can pass another argument Here, I’m gonna add an expression one more time number plus one So we’ll get one two three now. I want to put this expression in parentheses. So let’s select this put it in parentheses and then Multiply it by a dot So here we have a string that is multiplied by a number. The result will be that string repeated that number of times Let’s take a look around the program See, that’s pretty cool, isn’t it? now let me show you one more thing before we finish this lecture as You saw this range function generates numbers starting from zero all the way up to this number here But it doesn’t include this number here. We can pass another argument say start from 1 and finish before 4 With this change, we don’t need to add 1 to number every time Because in the first iteration this number variable will be set to 1 So we can simplify our code and make it clean air Let’s run it one more time. We get the exact same result We can also pass a third argument as a step. So I’m going to change the second argument to 10 and Pass two as a step look at the result These are the numbers we get 1 3 5 and so on So pretty useful you’re going to use this function a lot in real-world applications Continuing with the example from the last lecture Let’s imagine the scenario where after the first attempt we can successfully send the message in that case You want to jump out of this loop? We don’t want to repeat this task of sending a message three times Let me show you how to implement this so in this demo I’m gonna simulate the scenario where we can successfully send a message. So we define a variable Successful and set it to true Now here after this print statement We’ll have an if statement If successful : then perhaps we can print successful Now here we want to jump out of this loop for that. We use the break statement Let’s run this program and see what happens So there you go after the first attempt, we are successful and there are no more attempts So once again, I want you to pay great attention to the indentation here because that’s one of the common issues amongst beginners So here’s our for loop These two lines are indented with four spaces and they belong to our for loop in every iteration These two lines will be executed Now when we get to line four if this condition is true Then these two lines will be executed because both these lines are indented below this if statement Now, let’s take this program to the next level What if we attempt three times and we still cannot send an email? Perhaps we want to display a different message to the user we say hey, we tried three times, but it didn’t work. So I’m gonna change successful to false Now at the end here we can add an else statement This is what we call a for else statement What we put under this else statement will only be executed if this loop completes without an early termination So if we never break out of this loop, then the else statement will be executed so here we can print a message like attempt at three times and failed So run the program See what we get three attempts followed by this message attempted three times and failed in Contrast if we change successful to true Because we terminate this loop using this break statement what we have in the else block will not be executed Take a look run the program. We have one attempt successful done In programming we have this concept called nested loops so we can put one loop Inside of another loop and with this we can get some interesting results Let me show you so I’m going to start with this loop for X in range 5 : now inside of this loop I’m gonna add another loop so for Y in range 3 : and Then in our second loop, I’m gonna add a print statement Here we can use formatted strings to display coordinates Remember formatted string so we have F followed by quotes Now here we add parentheses for our coordinate first we want to display X and then comma followed by Y Let’s run this program and see what happens there You go pretty cool, isn’t it? So we get 0 + 0 0 1 0 & 2 then we get 1 & 0 1 & 1 1 & 2 and so on Now let me explain how exactly Python interpreter executes this code. So here we have two loops this is what we call the outer loop and This is the inner loop so the execution of our program starts here in the first iteration of this loop X is 0 now we get to this statement which is a child of This for statement because it’s indented four times. This statement itself is a loop So what we have inside of this loop will be executed three times in the first iteration X is 0 because we’re still in the first iteration of the outer loop and Y is also 0 because we’re in the first iteration of the inner loop that is why we get 0 and 0 now we go to the second iteration of this inner loop in this iteration Y will be 1 whereas X is still 0 that is why we get 0 and 1 and similarly in the third iteration of our inner loop we’ll get 0 and 2 in the turn Now we’re done with the execution of the inner loop. So the control moves back to our outer loop here We’ll be in the second iteration So X will be one and then we start here again So we have to execute this inner loop three times in the first iteration Y will be 0 and X is 1 so here we have 1 and 0 Then we’ll get one on one and one and two you got the point So this is all about nested loops So you have learned how to use four loops to repeat one or more statements in your programs Now let’s dive deeper and see what this range function returns so earlier you learn about The built in type function with this function we can get the type of an object. So if I pass five here and run this program This is what we get. So the type of this number or this object is int or integer now, let’s look at the type of The value that we get from the range function. So as an argument we pass range of a number Let’s run this program So this range function returns an object of type? range, so in Python we have primitive types like numbers strings and boolean But we also have complex types range is an example one of those complex types throughout this course You’re going to learn about a lot of other complex types now What is interesting about this range object is? That it’s iterable which means we can iterate over it or use it in a for loop That is why we can write code like this So this range function returns a range object, which is interval Which means we can iterate over it in each iteration X will have a different value Now range objects are not the only iterable objects in Python Strings are also iterable. So here we can add a string like Python Now in each iteration X will hold one character in this string. Let me show you so print Peg’s And I’m gonna delete these two lines here Let’s run this program So in each iteration, we’ll get one character and print it We have another complex type called list which we use to store a list of objects So we add square brackets this indicates a list Now we can add a list of numbers or a list of strings like a list of names You will learn about lists later in the course so let’s run this one more time as We can see we can iterate over lists in each iteration. We’ll get one object in this list now Later in the course. I will show you how to create your own custom objects that are eatable For example, you will learn how to write code like this for item in shopping cart Print item. So shopping cart is going to be custom object that you will create It’s not going to be an integer or a string or boolean. It’s a custom object It has a different structure and we’ll make it eatable so we can use it in a for loop and in each iteration we can get one item in the shopping cart and Print it on a terminal So you have learned that we use for loops to iterate over each ruble objects in Python We have another kind of loop that is a while loop and we use that to repeat something as long as a condition is true Here’s an example. So let’s define a variable number and set it to a hundred Now we use while and here we add a condition as long as number is greater than zero. We add a colon Once again, we have indentation so we can repeat one or more statements we can print this number and Then we can divide it by half so number equals number Use the integer division To divide it by two or we can use the augment and assignment operator to shorten this code like this Now let’s run this program So here is what we get initially. Our number is a hundred we divide it by half We get 50 then 25 and so on So as you can see in this example We are not iterating over an iterable like a range object or a string or a list We are evaluating a condition and repeating a task Let me show you a real world example of a while loop in this interactive shell Python is waiting for an input We can type something like 2 plus 2 it will evaluate it and ask for the next input we can add another expression like 10 is greater than 2 so these steps will continue until We press control-d So behind the scene we have a while loop that continuous execution until we press control-d That is the condition that causes the while loop to terminate. Let me show you how to build something like this in Python. So Let’s define a variable And set it to an empty string Now here we need a while loop. We want this while loop to execute as long as command does not equal to quit So command does not equal to quit : In this loop, we want to continuously get input from the user So we use the built-in input function. We add a label like this Get the result and store it in the command variable Now at this point python interactive shell will evaluate this command We are not going to do that in this lecture because that’s way too complex for simplicity We can just echo back what the user entered so print Echo and as the second argument we pass this command So this is our while loop it will execute until we type quit Now as I told you before don’t run this program using the code runner Extension because by default it will run your program in the output window, which is read-only so open up a terminal using ctrl + back take and run Python or Python 3 AB dot pi So here’s our command prompt. Let’s type 2 + 2 it it goes back Let’s type 3 times 2. There you go if we type quit our Program terminates now. Let’s try it one more time What if we type quit an upper case? The program doesn’t terminate because as you learned before lower case and upper case characters have different numeric representations So quit in lower case is different from quit in upper case now to solve this problem an amateur programmer may do something like this and Command does not equal to Capital quit so while command does not equal Quit in lower case and quit in upper case continue getting input from the user Let’s run this program in terminal and see what happens. So one more time Python after pie Which I’ve quit Beautiful it works. We type quit an uppercase that would work too. But what if I type quit with an uppercase Q and lowercase uit our program doesn’t terminate So this is a poor way of checking for the quit command. What is a better way? let me show you so we don’t need this and operator here instead Because command is a string we can call the lower method So whatever the user types in first We’ll convert it to lowercase and then compare it with quit in lower case with this change It doesn’t matter how the user types the word quit will always terminate the program Now the last thing I want to discuss in this section is the concept of infinite loops an Infinite loop is a loop that runs forever so if I change this condition to true Because true is always true this while loop will run forever So to jump out of this we need a break statement. So after we get the input from the user We can get the command Convert it to lowercase and see if it equals to quit if that’s the case. We want to break Now with this change, we no longer need to initialize command to an empty string Previously we needed this because we had a wild statement like this while command does not equal quit So we had to define this command variable and that’s why we have set it to an empty string without this line when Python interpreter Tries to execute this code. It doesn’t know what command is So now that we have an infinite loop we no longer need to define command and set it to an empty string So in terms of functionality, this program is exactly the same as the program We wrote in the last lecture just be aware of these infinite loops because they run forever You should always have a way to jump out of them otherwise your program will run forever and this can sometimes cause issues because if you’re executing Operations that consume memory at some point your program may run out of memory and crash Alright time for an exercise. I want you to write a program to display the even numbers between 1 to 10 So when you run this program? You should see 2 4 6 and 8 and after these I want you to print this message. We have 4 even numbers Now here is a quick hint before you get started. You should call the range function with 1 and 10 Do not use this third argument, which is called step so basically I want you to iterate over all the numbers we can want to tab Check if each number is an even number and then print it on the terminal So pause the video spend two minutes on this exercise when you’re done come back continue watching So it started with a four loop for a number in range one to ten : We check to see if the remainder of division of this number by two equals zero so if number modulus two equals zero then We print this number Now let’s run this program So we get two four six eight beautiful now to count the even numbers We need a separate variable. So let’s call that count Initially, we set it to zero now in this if block every time we find an even number we need to increment count so we set count plus equals one and finally after our for loop we can print a formatted string we have count even numbers let’s run the program and Here’s the result So that brings us to the end of this section in the next section. You’re going to learn how to create your own functions I hope you enjoyed the section and thank you for watching So far you have learned how to use some of the built-in functions in Python such as print Round and so on in this section, you’re gonna learn how to write your own functions Now you might ask but why do you even need to write our own functions? well When you build a real program that program is going to consist hundreds or thousands of lines of code You shouldn’t write all that code in one file like we have done so far You should break that code into smaller more maintainable and potentially more reusable chunks We refer to these chunks as functions So let me show you how to create your own custom functions. We start with the DEF keyword, which is short for define Next we need to give our function and name So let’s call this greet all the best practices. You’ll learn about naming your variables also apply to naming your functions So make sure your function names are meaningful Descriptive use lowercase letters to name your functions and an underscore to separate multiple words Now after the name we need to add parentheses you will see why shortly and then we’ll add a colon Now what is going to happen? You know it you’re gonna get indentation which means the following statements will belong to this function So here I’m gonna add two statements Hi there and welcome aboard Both designs belong to this function because they’re indented Now we’re done with this function. We need to call it. So we remove the indentation and we add two line breaks after this function This is what Papp 8 recommends to keep our code clean and maintainable now if you forget to add two line breaks Don’t worry. As soon as you save the changes auto-pay of eight will automatically add these line breaks for you let me show you so I’m gonna remove these line breaks and Call this function create with parentheses Just like how we call the built-in functions now save the changes. There you go So we two line breaks after our function Now let’s run this program So we get these two messages on a terminal Now here’s a question for you, what is the difference between the greed and Trent functions the difference is that this print function takes an input Whereas our greet function doesn’t take any inputs So let me show you how to pass inputs like first name and last name to this function When defining a function in between parentheses will list our parameters So here we add two parameters like first underline name and last underline name Now when calling this function we need to supply two values for those parameters. We refer to them as arguments, so maash Madani these are the arguments to the greet function. That’s one of the terms that a lot of developers out there Don’t know. They don’t know the difference between parameters and arguments a Parameter is the input that you define for your function Where as an argument is the actual value for a given parameter? Okay Now, let’s change line two and instead of saying hi there we can greet a person by their full name so we can convert this to a formatted string and Pass two fields here. First name as well as last name Save the changes run the program and this is what we get in terminal now This function is more useful. We can reuse it and call it with different arguments. So let’s create John Smith as well Run the program so we get hi Muhammad on e and hi John Smith Now note that by default all the parameters that you define for a function are required So here our greet function takes two parameters if I exclude one of these arguments and save the changes You can see we have this red underline. So pilant is complaining and saying there is no value for argument last name Also, if we run the program we get this type error greet missing one required positional argument So let’s put this back now later. I will show you how to define optional parameters So this is the simplified version of this greet function we created earlier Now in programming we have two types of functions functions that perform a task and Functions that calculate and return a value here are some examples both the print and greet functions are examples of type 1 the Performing a task, which is printing something on the terminal in contrast the brown function is An example of a function that calculates and returns a value so the functions that you create fall into these two categories Now let me show you how to rewrite this greet function but in the second form, so instead of printing this string on the terminal We simply return it. Let me show you so I’m going to delete all this code Define a new function But call it get underline greeting we add the name parameter and simply return this formatted string high name That’s all we have to do. So we use the return statement to return a value from this function now we can call this function Get underlined greeting has a name Like Maj because it returns a value we can store that value in a separate variable like message Now you might be curious which form of these greeting functions is better well with this first implementation We are locked to printing something in the terminal in the future if you want to write that Message in a file or send it in an email You have to create another function so we cannot reuse this greet function in other scenarios in Contrast this second form is not tied to printing something on the terminal it simply returns a value Now we get this value and we can do whatever we want with it. We can print it on the terminal or We can use the built-in open function To write this message to a file so we can create a like content Txt Openings for writing this returns a file object and then we can call file the right message Now don’t worry about these two lines later in the course I’m gonna talk about working with files But what I want you to take away here is that we have this message variable and we can do whatever we want with it we can print it on the terminal write it to a file send it in an email and so on and One more thing before we finish this lecture. So here’s our greet function And as you can see, we’re simply printing a string now if we call greet Give it a name run the program we get this message. Hi, Maj, but what if we put this? inside of a call to the print function Let’s see what we get We get high Marsh followed by not. What is this? None is the return value of the greet function So in Python all functions by default return the non value non is an object that represents The absence of a value later in the course you’re gonna learn more about not what matters now is that all functions return non by default unless You specifically return a value So here if we return Some string None will no longer be returned now. I just want to clarify something Earlier, I told you that we have two types of functions in programming functions that carry out the tasks or functions that calculate and return a value So back to the code we previously had So even though this function returns none by default, it is still classified as a function that carries out a task Let’s create another function We call it increment you want to use this function to increment a number by a given value So here we simply return number plus by Now we can call this function like this increment two and one this returns a value so we can store it in a variable Like result and then print it on the terminal Let’s run the program. We get three beautiful now we can simplify this code We have used this result variable only in a single place that is line six, so we don’t really need it So on line six, we can replace result with a call to increment function like this so When python interpreter executes this code first It will call the increment function. It will get the result and temporary store it in a variable for us We don’t see that variable and then it will pass that variable as an argument to the print function Now if we run this program we get the exact same result beautiful Now we can make this code more readable. If someone else looks at line five, they may not know exactly what These arguments are for we can use a keyword argument to make this code more readable So this one here is the value of this by parameter we can prefix it with The name of the parameter like this Now we can read this code almost like playing English increment two by one So if you’re calling a function with multiple arguments, and it’s not quite clear What is arguments are for you can make your code more readable by using keyword arguments So here y equals one is a keyword argument Earlier I told you that all the parameters that you define for a function are required by default in this lecture I’m gonna show you how to make the by parameter optional. So let’s say we don’t want to explicitly Pass y equals 1 every time we want to call this increment function we want to use this function to increment a value by 1 so We remove the second argument Now we need to give this parameter a default value. So we set it to 1 Now if we call this function and don’t supply the second argument this default value will be used Otherwise the value that we specify here will be used. Let me show you so we’ve run this program The result is 3 but if we pass the second argument here We’ll increment 2 by 5. So we’ll get 7 So you can see it’s pretty easy to make a parameter optional just be aware that all these optional parameters should come after the Required parameters in other words. I cannot add another required parameter here Let’s call that another. I cannot add that here. If I save the changes you can see we get a red underline here So all the optional parameters should come after the required parameters Now obviously in this case, we don’t need the second parameter. So let’s delete it There are times that you may want to create a function that takes a variable number of arguments here is an example Let’s define this function multiplied That takes two parameters x and y and simply returns x times y now We can call this function like this So far so good, but what if you want to pass one or two more arguments here that doesn’t work because our multiply function takes only two parameters to Solve this problem. We need to replace these two parameters with a single parameter we use a plural name here to indicate that this is a collection of Arguments and then we prefix it with an asterisk. This is the magical part Let me show you what happens when you use an asterisk here. So temporarily let’s delete this line and simply print Numbers, let’s see what we get here So run the program You can see all our arguments and they’re packed in parentheses. What is this? Well earlier you learned about lists I briefly mentioned that you can use square brackets to create a list of objects like 2 3 4 5 now Later in the course. We have a comprehensive section about lists. So don’t worry about the details of lists and how they work But what I want you to note here is that the only difference between this list and what we have here is in the notation so use square brackets to create lists and Parentheses to create tuples some people call it two poles or two poles. So a top pole is similar to a list in that it’s a collection of objects the Difference is that we cannot modify this collection. We cannot add a new object to this topple once again later in the course We’re going to have a comprehensive section about lists tuples and other data structures What matters now is that? These topples just like lists are iterable so we can each raid over them Which means we can use them in loops. Let me show you so That’s right for number in numbers : let’s just print one number at a time Actually, we don’t need this line. So delete and run the program So we iterate over this topple and in each iteration we get one number and print it on the terminal So now with a simple change we can calculate the product of all these numbers All we have to do is to define a variable like total initially, we set it to one and then in each iteration we get total and Multiplied by the current number or we can rewrite this statement Using an Augmented assignment operator. So total times equal number Line five and four are exactly identical. So I’m gonna use line five because it’s shorter and cleaner delete and Finally, we’ll return the total now One of the issues I see often in beginners code is that they don’t use this indentation Properly so they put the return statement here and then they wonder why their function doesn’t work properly if you put the return statement Here it will be part of the for loop. So It will be executed in each iteration in this case after the first iteration Because of this return statement, we’ll return from this multiply function. So the total will not be calculated properly We need to put this at the same level of indentation as other statements in this function So here we have our for statement. We loop over all the numbers We calculate the total and then finally return it So with this implementation we can get the result and printed on the terminal let’s run the program and you can see the product of these numbers is 120 So in the last lecture, you learned the syntax to pass a variable number of arguments to a function We have a variation of this syntax with double asterisk. And that’s what I’m gonna show you in this lecture So for this demo, let’s rename this function to save underline user and Rename the argument to user. So let’s imagine we’re gonna use this function to save information about a user Now in this function, let’s just print this user argument. We’re done with our function Let’s call it save underline user Now instead of passing arbitrary arguments here. We can pass arbitrary keyword arguments Remember keyword arguments so we have name equals value So here we can add multiple keyword arguments like ID equals 1 name equals John Age equals 22 and so on so we are passing 3 keyword arguments to this function Now let’s run this program This is what we get. Look at the syntax. We have these curly braces and in between them we have multiple key value pairs so key colon value Comma here’s another key value pair and here is the last one This object you see here is called a dictionary It’s another complex type or a data structure in Python, and I’m going to talk about that in detail later in the course for now All I want you to take away is that when we use double asterisk here we can pass multiple key value pairs or multiple keyword arguments to a function and Python will automatically package them into a dictionary. So this user object here is a dictionary now using the bracket notation We can get the value of various keys in this dictionary so we can print user Square brackets we pass a string and this is the name of our key like ID. Let’s run the program We get 1 or we can access the value of Name key Run program so name is John. So this is how deeksha Mary’s work In programming we have a very important concept called scope which refers to the region of the code Where a variable is defined so in this example? We have this message variable The scope of this variable is the greet function it only exists inside of this function so if we go outside of this function and try to print Message see what happens. As soon as I save the change as we get this red underlined undefined variable message and If we run our program We get this name error named message is not defined the same rule applies to the parameters of our functions So if we add a name parameter here and then try to print it outside of the greet function we get the same error so the scope of the name and message variables are the greet function and we refer to these variables as Local variables in this function. They’re local in this function, which means they don’t exist anywhere else and That means we can have another function. Let’s say send email With a parameter with the same name here. We can have a message variable But this message variable is completely different from the message variable we have in the greet function And of course the same rule applies to the named parameters in these functions They’re completely separate these local variables have a short lifetime. So when we call Let’s say the greet function and pass a name Python interpreter will allocate some memory and have the name and message variables Reference those memory locations when we finish executing the greet function Because these variables are not referenced or used anywhere else Eventually, they get garbage collector Which means Python interpreter will release the memory that allocated for these variables So these are the local variables in Contrast to local variables we have global variables So if we move this message variable outside of the great function now, it’s a global variable Which means it’s accessible anywhere in this file So the scope of this variable is this file we can use it anywhere in this file in any functions or outside of a function now for this reason Global variables stay in memory for a longer period of time until they are garbage collected and you should not use them that often In fact global variables are really evil. So as a best practice Create functions with parameters and local variables. Now what if here in the greet function? We set message to let’s say B Now let’s delete this second function. We don’t really need it for now. So we call the greet function in this function We assign a new value to the message variable now, let’s print This message and see what we get What do you think? We’re gonna get? Well, let’s take a look We get a but didn’t we change the value of message variable to be? Not really because by default python interpreter treats this message variable as a local variable in the greet function Even though it has the same name as the global variable that we have on line one So these two variables are separate now I’ve seen some tutorials or even books teaching you bad practices, for example They show you how to modify the value of this global message variable Inside of a function. Let me show you how to do that But remember this is a bad practice and you should avoid it at all times. I will explain the reason in a second so these tutorials or books teach you to use the global keyword here and Reference the message variable when python interpreter sees this line it will realize that in this function We want to use the global message variable. So it will not define a local variable in this function Now with this change if we run our program You can see we get beyond the terminal because in this function we are Modifying the value of the global message variable. Why is this bad? Because it is possible that you might have multiple functions that rely on the of this global variable If you’re accidentally or deliberately change the value of this global variable in one function This might have a side effect in other functions Those functions may not behave properly and this way we can create a bug in our program. So Global variables have always been bad. This is not a Python thing. This is a discussion that’s been going on for decades Avoid them as much as you can or if there are situations that you really need to define a variable globally in a file That’s okay, but do not modify it in a function as you see here. This is a really bad practice So that’s all about local and global variables In this lecture, I’m going to show you how to find and fix bugs in your programs. So here’s the multiply function we wrote earlier Let’s add a couple of statements after this function. So print start and Then we’ll call the multiply function give it three arguments one two and three so the result should be six and Here we print the result on the terminal now To create a bug in this program. I’m going to deliberately indent this return statement so now when we run this program Instead of six we get one So we’re gonna use a technique called debugging to find and fix this bug Alright first we need to open the debugging panel The first time you want to use debugging in a Python project you need to click this icon This would generate a new file called launch the JSON in this file We have a bunch of debugging configuration. You never have to touch any of this, so don’t worry about it Close it you can see this file is placed Inside of this vs code folder. It’s right here. Launched a JSON Now when we have this file, we can go to the debugging panel and from this list We can select a debug in configuration Some of these configurations are useful for more complex applications For example, we use Python Django to debug a web application built with Python for this course We’re going to use Python current file with integrated terminal. So select this now to start debugging First we need to add a breakpoint on one of these statements. So I’m going to put the cursor on line 8 and insert a breakpoint by pressing f9 So this is a breakpoint we can press f9 one more time to remove it If you’re on a Mac keyboard, you should press the function key Which is on the bottom left corner of your keyboard, and then press f9 So here we have a breakpoint now we can press f5 to run the application up to this point so f5 So this automatically opens the integrated terminal here don’t worry about this I’m going to close it So you can see our program is running up to this point. This line is highlighted now we can execute this program line by line and see exactly what happens at runtime, so To execute one statement at a time, press f10 Okay, we are done now we are on line 9 However on line 9 you are calling the multiply function if we press f10 again The execution stops, so we couldn’t figure out why we got one as the result of multiplying these numbers So let’s start debugging one more time. We press f5 So once again, we are on line 8, let’s step over this line with f10 Now this time we want to step into this multiply function. So we see exactly what is going on here so instead of f10, press f11 Now we are on line 2 So if you’re calling a function that you have to find you can step into that function using f11 Now here we are in the multiply function on the left side inside the variables panel You can see all the variables that are meaningful in this function. So hungry. Locals we have numbers So this is our numbers argument you can see this is set to a topple with 3 numbers 1 2 3 Right now our total variable is not in this list because it’s not defined yet The moment we step over this line with f10 total comes to existence and you can see initially is set to 1 Now we are at the beginning of our for loop. Let’s press f10 one more time Here we are we’re going to multiply total by number so let’s step over this line as well Now at this point we have a new variable called number That is our loop variable Initially, it’s set to 1 Now here we are on line 5 if you press f10 We can see we jump out of this function So our loop did not execute to completion and that is the reason our program has a bug So to fix this I’m gonna stop the debugger with Shift + f5 Now back here let’s remove the indentation Save the changes run the program in debug mode one more time. So we press f5 Here we are let’s step over this with f10 now step into this with f11 and step over these lines with f10 a few more times, so f10 one more time Total it’s set. Now. We are in the second iteration Let’s press f10 one more time in this iteration You can see number is set to two our total is still one. So let’s step over this line as well Now total is updated to two Here we are at the beginning of the third iteration Let’s step over this line in this iteration number is three So after we execute this line because total is currently two when we multiply it by three We’ll get 6 so f10 one more time Now we only have three iterations in this loop so if you press f10 one more time our loop completes now, we are ready to return total which is currently six so f10 we are on line nine and We’re done Now one more tip in this demo. I put the breakpoint on the first line of the program You don’t always have to do this. For example here. We know that our multiply function has a bug So instead of putting the breakpoint on line eight we could put it on line two so when we start the program in debug mode with f5 We immediately start in the multiply function And one more tip before we finish this lecture if you step into a function and you know that that function works properly We can immediately step out of that function with Shift + f11 So you don’t have to execute the entire function line by line You can press shift and f11 to step out of that function Alright, let’s finish up this section by looking at a few very useful shortcuts for writing code fast first I’m going to show you the shortcuts for Windows users. And in the next lecture. We will look at the shortcuts for Mac So if you’re a Mac user feel free to skip this lecture So here we are on line 9 and my cursor is right at the beginning of the line Let’s say you want to move the cursor to the end of the line Instead of pressing the right arrow to go all the way to the end we can simply press the end key and here is the cursor or If you want to move the cursor to the beginning of the line simply, press the HOME key. There you go Similarly, if you want to move the cursor to the beginning of the file, press ctrl + home Here it is or ctrl + end/2 go to the end of the file now, let’s say we want to move this line up instead of cutting it from here and then copying it somewhere else we can simply move it up by pressing Alt + The up or down arrows or If you want to move these two lines up and down simply select them then hold alt and then up or down very easy Now if you want to duplicate a line or multiple lines simply select them now hold down shift Alt and then press the down key. We can duplicate it as many times as you want. There you go Here’s another useful shortcut. If you want to convert this line, or maybe these two lines into a comment simply hold down control and press Slash using the same shortcut. You can remove the comment so you can toggle it very easy and Finally if you want to type the name of a variable or a function like multiplied You don’t have to type all characters. Here are a few ways to type this quickly We can just type the first few characters and here in the intellisense. You can see that so if you press ENTER This is what we call auto-completion Here’s another way. So instead of writing the first few letters You can just pick any letters in sequence and type them so I can type mty or I can just type mpy or Why there you go, here it is. So I hope you enjoyed these shortcuts and thank you for watching Alright now, let’s take a look at the shortcuts for a Mac keyboard So here we are on line 9 and my cursor is right at the beginning of the line if you want to move the cursor To the end of the line instead of using the right arrow to go all the way Simply hold down the function key and press right? Here it is. Or you can press function and left to jump to the beginning of the line Similarly, you can press function and up To go to the top of the file or function and down to jump to the end of the file Pretty useful now. Let’s say you want to move this line up Instead of cutting it from here and then copying it somewhere else You can simply move it up by holding down alt or option and then pressing the up arrow or down Very easy, or we can select these two lines hold down the alt or option key Move it up or down Here’s another useful shortcut we can convert these two lines into a comment by pressing command and slash and Then we can remove the comment using the same shortcut so we can toggle it and finally if you want to type the name of a variable or a function like multiply you don’t have to type all the letters like Multiply that is very slow You can type the first few letters like mult and here in the intellisense. You can see it’s selected, so press Enter or You can pick any characters in sequence and type them like mty here it is, or we can type an py or M TP so you can abbreviate it any way you want. I hope you enjoyed these shortcuts and thank you for watching One of the questions that often comes in programming interviews is the fizzbuzz Algorithm you might be surprised that there are a lot of developers out there with even years of experience But they don’t know how to solve this simple programming problem. That’s why I decided to include this in my course So, let’s see how this algorithm works and then you can spend 10 to 15 minutes on this exercise on your own So here we have a function Fizz buzz that takes an input and depending on the input we give it it returns Different results here are the rules if the input that we give it is divisible by 3 It will return the string fizz. Let me show you so we run this program we get fizz If the input is divisible by 5, it will return buzz take a look Here’s buzz Now the third rule if the input is divisible by both 3 & 5 it will return Fizzbuzz, so let’s pass 15 here We’ll get fizzbuzz For any other numbers it will return the same input. So if I pass 7 it’s not divisible by 3 or 5. It will return 7 itself, so spend 10 to 15 minutes on this exercise. You will see my solution next All right, let’s see how we can solve this problem so we get the input and check to see if input is divisible by 3 Then we can set a variable like result to phase Now let me temporarily Simplify these rules because I want to show you a really cool technique So let’s imagine if the input is divisible by 3. We’ll return fizz Otherwise, we’ll return bus, so LS : we set the result to buzz and finally we’ll return this resolved variable This is one way to implement these rules, but it’s not the best way there is a better and cleaner way Let me show you so instead of defining this result variable and then returning it we can simply return this string here and also here and Then we can get rid of line six. So we remove one unnecessary line of code this was one technique the other technique I want to show you is when you have an if statement and In your if flock you’re returning a value. You don’t really need an else clause because if this condition is evaluated to false the control moves to the else clause and all we’re doing here is Returning a different value. So this is the only possible outcome so here we can remove this else clause and simply return bus So with this technique I remove an unnecessary Indentation as well. I’ve made our code more linear. Okay. Now, let’s go back to our original algorithm So if the input is divisible by three, we’ll return fizz Now we check to see if the input is divisible by five. We’ll return buzz So here we don’t really need an Elif because if this condition is false we’ll get here anyway, so we can check if Input is divisible by five We will return buzz once again if this condition is false the control moves here now we check the same if the input is divisible by three and It is also divisible by five then we will return Fizz buzz Now this expression is a little bit long I would prefer to make it more readable by putting parentheses around the first and second parts like this That is cleaner. Now if this condition is also false the control moves here That means our number is not divisible by three or five so we should simply return the input Once again, we don’t need an else or another if we simply return the input Now, let’s run this program and see if it’s working properly or not so we call our function with three and We get fizz beautiful. Let’s call it with five We get Buzz perfect. What if we call it with 15 we should get fizz bus However, we get fizz what is going on here? The reason this happened was because when we pass 15 here line two is executed Obviously 15 is divisible by three. So that is why we immediately return fizz to solve this problem We need to move this condition, which is more specific to the top So I’ve selected these two lines using alt + up. I Move these lines up beautiful. All right. Now, let’s run the program one more time So we get fizzbuzz. Once again, let’s test it with three Now we get fares. Let’s test it with five when writing functions don’t assume that your function is working Make sure to test it with all different kinds of values Let’s test it but 5 we get Buzz beautiful. What if you pass? 7 which is not divisible by 3 or 5 we get 7 beautiful so what you see here is the simplest and most elegant implementation of the fizzbuzz algorithm and that Brings us to the end of this section in the next lecture. We’re going to explore data structures in Python You’re going to learn about lists tuples sets and dictionaries. I hope you enjoyed this section and thank you for watching You You made it this far and that makes me think that you’re really enthusiastic about learning Python So I highly encourage you to enroll in my complete Python course where we go way beyond this crash course You will learn how to use Python in real-world scenarios such as data analysis and visualization automating repetitive boring tasks that involve working with files and folders spreadsheets PDFs data compression Sending emails web crawling consuming api’s and much much more. This course comes with a 30 day No questions asked money back guarantee and a certificate of completion if you’re interested click the link below this video to access the course Once again, thank you for watching Please support me by liking and sharing this video and also subscribe to my channel to get free new videos every week Thank you, and have a great day

100 thoughts on “Python Tutorials for Beginners – Learn Python Online”

  1. def fizz_buzz(input):

    return "FizzBuzz" if input % 15 == 0 else "Buzz" if input % 5 == 0 else "Fizz" if input % 3 == 0 else input

  2. At the start of the course once you installed Code runner we can see that each time you run code it also shows "[Done] exited with code=0….." but later on that doesn't show anymore. How to get rid of it?

  3. This is my code for 1:41:20 xD

    a = 2

    b = 4

    c = 6

    d = 8

    for num in range(1):

    num = a

    print(a)

    if num == a:

    num = b

    print(num)

    if num == b:

    num = c

    print(num)

    if num == c:

    num = d

    print(num)

    print("We have 4 even numbers")

  4. Im torn between computer science and computer engineering. Can anybody suggest what's practically better? Or which of them is the most hired? Please I badly need help. 🙁

  5. Hi, when i am trying do the exercise on the minute 45:00 and it show this message, could you help me ?

    File "/Users/augustoenriquez/Desktop/prueba1/app.py", line 8
    full_name = f'{first} {last}'
    ^
    SyntaxError: invalid syntax

  6. Why does my output look like this in the terminal after I hit run??

    [Running] python -u "c:Userswrigh_000OneDriveDocumentsWhatsUpWorldapp.py"

    4

    [Done] exited with code=0 in 0.09 seconds

    I would rather it look clean and concise like how he has his in the video. Can anyone help?

  7. Need help, whenever I try to install the linter pylint i get this message on the terminal: Could not find a version that satisfies the requirement pylint (from versions: )

    No matching distribution found for pylint.

    I got the latest version of phyton 3 64 bits.

  8. Hi. Is there another variant of this tutorial on a Windows Computer? You are clearly using a Mac and there seem to be LOADS of variations between using a Mac and using a PC.
    These little differences make your tutorial very distracting because i spend so much time stopping and starting the video trying to work out why MY screen isn't working.
    Sometimes it is little things like.. after Hello World you instantly plonked a cat emoji, but that facility is not available on my PC. It didn't add anything to the tutorial and wasted 10 minutes of my time trying to find it. The CTRL + ' on a UK keyboard is in a different place. The ' symbol is to the left of the Enter key above the #. Again, more wasted time.
    So, is there a PC version?

  9. Mosh you are actually the God Gifted person. Best Programming teacher I have ever met. Just wanna know will there be a C++ course either on youtube or at programmingwithmosh.com? If yes I beg you to reply I am dying to learn C++ from you. Hop you will reply.

  10. I don't know why I watch all ads on your videos completely and also click them. Maybe I want to give you some profit and it is the only way I have.?!

  11. Thank you for this easy to follow lecture lesson.
    But I see this PYTHON very similar to QBASIC programming, even the qbasic is more understandable language . So, I wish they had improved qbasic for me to continue with the programming I was doing in the 80'S and 90's
    😐

  12. can u show it in windows because difference between mac and windows make beginner like me easily give up and frustrated

  13. Hi Mosh,
    I like your way teaching…its nice, short, sweet.
    I am requesting you to make tutorial for RHCSA.
    Thank you
    Ranjeet

  14. Can anyone tell me how to get rid of file address that is displayed in the terminal after I run my code? I would rather it look short and clean next to the results so it not such a big mess. Thanks.

  15. Why would you need to download a code editor? I've been using the IDLE that came with the python download. Should I keep using it? Or is it a personal preference?

  16. Trying to run code in terminal @1:37:00, but keep getting syntax error.
    Can anyone tell me what this means:

    >>> python app.py

    File "<stdin>", line 1

    python app.py

    ^

    SyntaxError: invalid syntax

    This is how I have my code typed:

    command = ""

    while command != "stop":

    command = input(">")

    print("ECHO", command)

  17. Wow you're amazing. My professor tried to teach the class how to install python and failed miserably because everybody was lost.

  18. Hey guys. I installed Python package but dont manage to make pylint works. Any idea? I tried pylint enable, linter run, linter enable…

  19. Sir i have a found a error after type python in comand promt and error is like
    PYTHON. exe-application error
    The application was unable to start correctly (0*000007b).Click OK to close the application

  20. Hi Mosh, thanks for the good intro to Python programming.

    In your FizzBuzz example, would this alternative use of truthy/falsy values be considered more efficient since it eliminates an equality test?

    "if (not input % 3) and (not input % 5):"
    as opposed to
    "if (input % 3 == 0) and (input % 5 == 0)"

  21. You are the most incedible teacher who I`ve ever seen in my whole life . thamks a bunch frim Iran, Tehran. You are amazing Moshfegh jane azize khodemoooni

  22. I don't know English very much but I watch your videos with the help of caption
    You are to good
    Love you from India

  23. Please help me. For some reason, my mac does not have three dots next to the user and workspace settings.

  24. Thank you for this very well-made, clear & interesting video. A quick question or 2: At 1:35:40 Why doesn’t Python display a float & why does Python round the integers down instead of up? For example: According to Python 25/2 = 12
    Thanks in advance.

  25. Hi…. This is Sanjay Modasia… Senior software developer…. I was professional lecturer same like you but it was only 1 year. You are representing things in precious manner because I know how much hard work it takes to make students clear concept about programming. You are doing great job…..I really appreciate your efforts….I observe each and everything about your lecturer and it make me remember moments when worked as tutor to solve error in programming of final year student projects in JAVA. I have handled errors about 200-250 students in their last year project. Your lecture draw direct line to my that work.

  26. Dear Mosh Hamedani a special thanks from a Indian viewer I Subscribed also and want deeply learn python ,I enjoying your video please email me if you have material on python , you are a tourch bearer for me as I am feeling dark in life and having strong zeal ready to break all the barrier please help if you able to do .
    Email:- [email protected]@gmail.com
    Thanks again

  27. For my mac users…when changing the code-runner.executor map setting from "python -u" be sure to use "python3 -u".

  28. Do other things rather than simple "hello World " shit. Show how to install packages and all those stuffs. I am sick and tired of all these trifle bullshits, total time waster.

  29. Hey guys, do not buy any course from @t . I bought all courses from @t. But when I try to log in it says you don't have an account with this email. Don't buy. And mosh do not give response also.

  30. i am getting error when i will run my App.py file
    "At line:1 char:10

    + $python3 app.py

    + ~~~~~~

    Unexpected token 'app.py' in expression or statement.

    + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

    + FullyQualifiedErrorId : UnexpectedToken" Pls suggest

  31. Your tutorial is very easy to follow and understand. Thank you for your time and effort! I feel confident studying Python because of this. I was kind of hesitant starting to learn Python.

  32. I had forgot how to execute current file.py to the output, what's the VScode hotkey? I can't find it from the video

  33. C:UsersHPAppDataLocalProgramsPythonPython37-32python.exe: can't open file 'C:/Users/HP/PycharmProjects/untitledHello world/app.py': [Errno 2] No such file or directory i get this report when i run. am new to it and am ready to learn to become good

  34. How do you insert the above text in the next line? The UP arrow is not displaying what i typed above. How do you enable or make this work? I can do it on the RUN CODE screen but not when i am typing the syntax…

  35. Mosh I installed Python and VS coder today and I have been following the tutorial but for some reason it won't format on save. The formatter works with the format on type option but not with the on save. Due to this it won't give me the formatted 2 lines after I create a function

  36. You lost me at 8:42 in my ver 1.36.1 2019-0708 there is no such thing as open an than new folder. Can I still follow you?

  37. This was a beautiful tutorial. Everything was explained explicitly and in the simplest way. It really helped me a lot. Thanks for the help Mosh

  38. mosh i love u……i used to talk to u via mail when i saw ur at udemy ….when i wanted to learn c# but online payment is headache so i catch u here again trying to learn python for ML…….thanks so much

  39. I'm trying to "open settings.json" from the 3 dots to change python -u to python3 but don't seem to find "open settings.json". Does anyone know how to do that on a Mac? Video minutes where Mosh does it is at 24:55. Thanks in advance

  40. Would be much better if you did a separate Windows and Mac tutorial. Those three little dots you speak of to modify Code Runner from 'python -u' don;t exist on Windows. Doing my head in. R Studio was much less hassle to setup than this

  41. I am moderately good at "python" or at least good enough to know that at 58:47 this person who claims to be a "python person" is so unclear. this is very unclear and not "concise" this was the most unhelpful video ever 0.3 ratings out of 10.0

  42. I have share small python projects in my channel which will help the beginners
    https://youtu.be/R95l5ttnV_k

  43. Is there a way to enter another input command into the powershell without the need to keep entering "&python app.py" to restart?

  44. Thank you Mosh, I love your tutorials and after starting your free ones I passed immediately passed to your beginner's course on your website that I bought for a very good price. However, I think your paid beginners course is much more advanced than the free ones and I have difficulties to follow. so I have to go back to these youtube videos.would you be so kind to make the free course videos available split in sections for easy consultation? Thanks for your consideration

  45. Hello, Guys. I'm introducing new video course on Python! It's a new channel and you can win 1000$ dollars.

    Terms and conditions to win a reward:

    1)Like this comment
    2)Subscribe the channel

    3)Like this video

    https://www.youtube.com/watch?v=YGLGNuU8Ki8
    4)Write a comment with your opinion about this lesson

    Details – on the video

  46. Hello Moshfegh. I just started to learn programming and I'm a total beginner in python. I am watching your tutorials and I found them really interesting. Thanks a lot man.

  47. Mosh we windows people are having problems with getting the terminal window to print “Hello World”
    It comes up with windows powershell
    Try the new cross platform power shell https://aka.ms/pscore6

    This very annoying please help us.we are stuck

  48. thanks a lot for this amazing tutorial Mosh. This was the first tutorial I have seen entirely haha. Could you please recommend me what shall I see next?

  49. For the last quiz I wrote below code:
    def fizz_buzz(number):
    result = ""
    if number % 3 == 0:
    result = "Fizz"
    if number % 5 == 0:
    result = result+"Buzz"
    if result == "":
    result = number
    return result

  50. Thank you Mosh for this tutorial. Excellent. A question: You, as a software engineering, shouldn't be using Linux instead OS?… I mean, because stability, security, no virus, performance, speed, etc…

  51. what do i do after watching this video @Programming with Mosh.
    I don't know how to make a interface. Display graphics…
    Please Explain where i go after this.

  52. Excellent tutorial Mosh! Many thanks for all the time you put into this. This was very helpful and I really appreciated your friendly tone. As noted in the thread for NGBlue, below, I also had trouble in Windows 10 executing Python from the Visual Studio Code terminal. I noted my workaround as follows to run the app.py file:

    In the terminal in VS Code, at the command prompt C:HelloWorld> type this:

    C:/Full/Path/To/python.exe c:/HelloWorld/app.py

    Once again, awesome work and many thanks!

  53. I have a probelm.. as I run the program on terminal and write python app.py, i dont see the output..why is it happening? what should i do? anyone please help. Thanks

  54. Python Basics – Python for Absolute Beginner: Getting Started with Python in 10 Minutes https://youtu.be/J2dq9s3NGXA

  55. Love your tutorial and info your sharing. I am a new mum, giving my self a new challenge to learn coding. Your videos are making it flow with ease however I am not sure if it's normal to have my name and IMac details come up with in the print when I go into terminal? So stuck on this I can't go any further and figure out if those details should be there or it should just say hello world etc . I'm not tech savvy but giving it a massive go 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *