Python Programming Bootcamp | Learn to Code in Python [Tutorial and Exercises]

Python Programming Bootcamp | Learn to Code in Python [Tutorial and Exercises]

Views:698|Rating:5.00|View Time:1:5:4Minutes|Likes:38|Dislikes:0
In this Python Programming Bootcamp, you will be introduced to all concepts you need to learn how to code in Python. We will also give you practical examples so you can best understand each new skill you gain! Click here: to download the exercises (with solutions).

In our previous tutorial ( we provided an introduction to programming for those of you who have not used Python or another coding language so far. In this video, we will continue expanding our knowledge in Python by covering the most important concepts that will help you start off your programming journey. In other words, this Python Programming Bootcamp is for those who are already familiar with Python.

The concepts we will cover:
0:01 Introduction to the If Statement
2:56 Add an Else Statement
5:28 Else if, for Brief- Elif
10:59 A note on Boolean Values
12:57 Defining a Function in Python
14:56 Creating a Function with a Parameter
21:17 Using a Function in another Function
22:58 Combining Conditional Statements and Functions
26:03 Creating Functions Containing a Few Arguments
27:17 Notable Built-In Functions in Python
31:05 Lists
34:39 Help Yourself with Methods
37:59 List Slicing
42:24 Tuples
45:35 Dictionaries
49:32 For Loops
51:55 While Loops and Incrementing
54:19 Create Lists with the range() Function
56:32 Use Conditional Statements and Loops Together
59:29 All In
1:01:56 Iterating over Dictionaries


Link to our WEBINAR: Data Science for Beginners- How to Get Started

Link to Introduction to Python for Absolute Beginners

Follow us on YouTube:

Connect with us on our social media platforms:

Prepare yourself for a career in data science with our comprehensive program:

Get in touch about the training at:
[email protected]

Comment, like, share, and subscribe! We will be happy to hear from you and will get back to you!

in this lecture you will see values act as the most basic or primitive data elements necessary to form not only variables but any expressions a prominent example of conditional statements in Python is the if statement what you can use it for is intuitive but it is very important to learn the syntax think of the following if v equals 15 divided by 3 then print hooray first don't forget we should use the double equality sign here because we are checking whether five is equal to 15 divided by three and we are not assigning the value of 15 divided by 3 to be 5 5 is not a variable name it is a number good now it is crucial to place a colon the colon will tell the computer what to do if the condition we just wrote has been satisfied for achieving good legibility we advise you to write the print statement on a new line please remember it should be indented otherwise you will run into an error all right now this should work correctly yes 5 is equal to 15 divided by 3 ray will it work if we check for five being equal to 18 divided by three it is not supposed to since five differs from six we got nothing because we have not told the Machine what to do if the provided condition is not satisfied so there is no reason for the machine to print out her Rea the graph could help you imagine the process of the conditionals before it displays the outcome of the operation the Machine follows these logical steps if the conditional code is not to be executed because of the if condition is not true our program will directly lead us to some other output or as it is in this case – nothing after any of the two situations the machine will go to the next black point and will progress from there on let's try with an inequality sign which can be written with an exclamation mark and an equal sign isn't five different from three times six yes it is it is true that it is different hence we have her ray as an output this was a brief introduction to if statements this logic will help you proceed to the next lecture where we will complicate things a little bit but not too much let's assign the value of 1 to X we can ask the computer to display case 1 if X is greater than 3 in case 2 if it is less than or equal to 3 okay we could write two if statements one after the other let's see if we get the correct outcome yes we are in case two there is a shorter and better way to express ourselves here in the second part instead of saying if X is smaller than or equal to 3 we could write directly else and insert a colon else will tell the computer to execute the successive command in all other cases in our little program that would mean in all cases when X is not greater than three that translates into when X is less than or equal to three let's verify if what we did was correct bingo case number two this picture adds up to the one we saw in the previous lesson instead of leading to no output if the condition is false we will get to an else code in our case this is the command print case two regardless whether the initial condition is satisfied we will get to the end point so the computer has concluded the entire operation and is ready to execute a new one wonderful now please allow me to share two notes on the subject don't fall into the trap of organizing your code on a whim there is a strict manner to do that and indentation plays a key role again should you put the else keyword just underneath the first print word nothing will happen remember to place the if and the else keywords on the same vertical line the if-statement meaning the condition plus the relevant print command form the first block of code the entire else statement forms another block of code on its own in a long sheet with much code you'll have a whole lot of blocks and larger programs are constructed on a block by block basis in this lesson we'll learn an elegant way of adding a second if statement to one of our expressions this is done with the help of the Elif kit as shown in this example if Y is not greater than 5 the computer will think else if Y is less than 5 written Elif Y is less than 5 then I will print out less and the else statement follows as they tell with the respective block that says return equal let's confirm we wrote the code correctly we can print out the compare to 5 function with a value of y equal to 10 in the following way then we'll expect to see a statement that says greater because 10 is greater than 5 correct okay perfect what if we carry out this operation for the number two the Machine tells us that two is less than five and that's what we expected to obtain the third outcome we must compare the number five with a number that is not greater or smaller than five this will happen only if the argument of the function is five right shall we try this one great we obtained equal as expected know that you can add as many Elif statements as you need let's provide an example if y is less than zero the string negative should be displayed I will place the block between the if and the other Elif statement you let's see what happens the function with an argument of minus three shows negative just as it should let me just control whether our little program will run properly if I asked it to compare to five a value that lies in the range between zero and five say three yes we see less so everything is okay a very important detail you should try to remember is the computer always reads your commands from top to bottom regardless of the speed at which it works it executes only one command at a time scientifically speaking the instructions we give to the machine are part of a control flow this is something like the flow of the logical thought of the computer the way the computer thinks step-by-step executing the steps in a rigid order when it works with a conditional statement the computer's task will be to execute a specific command once a certain condition has been satisfied it will read your commands from the if statement at the top through the Elif statements in the middle to the else statement at the end the first moment the machine finds a satisfied condition it will print the respective output and will execute no other part of the code from this conditional in our example if the first statement is correct we will see the corresponding output number one which is printing the string greater the computer will disregard the Elif in the else statements and will proceed with the rest of the code if the first statement is not correct we will move forward and the computer will check whether our second statement is true if yes we will see output number two which is printing the string negative if not we will get to statement number three and so on until the computer finds a satisfactory outcome to print out now I will switch the order of the two Elif statements to prove that the order of instructions matters okay let me print compared to five of – three ha instead of negative we obtained less this is how the computer reasons assume y equals -3 printout greater if y is greater than 5 is it greater than 5 no so the computer continues and checks if there are any other statements in our code given we have other statements it moves forward so is y less than 5 yes it is at this moment the computer thinks lovely I got it my number is less than 5 i satisfy what my programmer asked me to do I print out less and I am fine and the machine stops there and does not execute a single letter of the code that follows in this block the fact that you examine the cases when y is less than 0 or equal precisely to 5 have no application they become useless whether you ask for the output of minus 3 or 3 you will still have to be satisfied with the less label you found this interesting didn't you stay focused for the next lecture when we will share something more about computational logic you probably noticed we talked about boolean values a few times here we would like to provide a short video that aims to explain their application let X be equal to 2 what you see next is the following if else construction if the value of the X variable is greater than four print out correct in all other cases print in correct so which is the boolean element we have in this computational logic basically after you insert your if statement the computer will attach a boolean value to it depending on the value of its outcome true or false it will produce one of the suggested outputs correct or incorrect if the first statement is true that is if X is greater than four the machine will print the corresponding statement correct else which means if the statement X greater than four is untrue or more precisely false the statement incorrect will be printed from a certain perspective everything in a computer system is boolean comprising sequences of zeros and ones false and true this is why we are paying attention to the boolean value it helps us understand general computational logic and the way conditionals work in Python ok excellent now you know more about conditionals in Python and you understand the control flow of if Elif and else statements in addition you saw once more complying with the pythonic syntax is crucial for the execution of your code where you type the colon sign and indentation matters last you saw the order in which you declare your commands leads to a specific outcome if you change the order of your commands the outcome could change and this may take you to undesired results wonderful great let's step it up a notch starting from this lesson we'll deal with pythons functions as an invaluable tool for programmers the best way of learning is by doing so let's create a function and see how it can be applied to tell the computer you are about to create a function just write def at the beginning of the line death is neither a command nor a function it is a keyword to indicate this Jupiter will automatically change its font color to green then you can type the name of the function you will use for instance simple as we will create a very simple function then we can add a pair of parentheses technically within these parentheses you could place the parameters of the function if it requires you to have any it is no problem to have a function with zero parameters this is the case with the function we are creating right now to proceed don't miss to put a colon after the name of the function since it is inconvenient to continue on the same line when the function becomes longer it is much better to build the habit of laying the instructions on a new line with an indent again good legibility counts for a good style of coding alright let's see what will happen when we ask the machine to print a sentence not much at least for now the computer created the function simple that can print out my first function but that was all to apply the function we must call it we must ask the function to do its job so we will obtain its result once we type its name simple and parenthesis see great okay good our next task will be to create a function with a parameter let it be plus ten with a parameter a that gives us the sum of a and ten as a result always begin with the DEF keyword then type the name of the function +10 and in parentheses designate the parameter a the last thing to write on this line would be the colon sign good what comes next is very important don't forget to return a value from the function if we look at the function we wrote in the previous lesson there was no value to return it printed a certain statement things are different here we will need this function to do a specific calculation for us and not just print something type return a +10 this will be the body of this function now let's call +10 with an argument to specified in parentheses amazing it works once we've created a function we can run it repeatedly changing its argument I could run plus 10 with an argument of 5 and this time the answer will be 15 great pay attention to the following when we define a function we specify in parentheses a parameter in the +10 function a is a parameter later when we call this function it is correct to say we provide an argument not a parameter so we can say call +10 with an argument of to call +10 with an argument of 5 people often confuse print and return and the type of situations when we can apply them to understand the concept better try to imagine the following there is an argument X which serves as an input in a function like the one we have here the function in this case is X plus 10 given that X is an input we can think of it as a value we already know so the combination of X and the function will give us the output value Y well in programing return regards the value of Y it just says to the machine after the operations executed by the function f return to me the value of y return plays a connection between the second and the third step of the process in other words a function can take an input of one or more variables and return a single output composed of one or more values this is why return can be used only once in a function therefore we can say the concept of a function applies to programming almost perfectly there are some extra advantages to consider you could also assign a more intuitive name to a function plus 10 or addition of 10 and the function will still run correctly this is a sign of good design on a sheet with 1000 lines of code if you call all your functions x1 x2 x3 and so on your colleagues will be confused and utterly unhappy naming functions clearly and concisely makes your programming code easy to understand and it will be accepted as one of good style there is another way in which you could organize the definition of your function start by defining plus 10 with an argument of a and a colon on the next line instead of directly returning the value of a +10 another variable can be created inside the function to carry that value I will use the name result here I will assign it with the desired value of a plus 10 let's check what we just did if I execute the code in the cell I will get nothing why because of this moment I have only declared the variable result in the body of our function naturally to obtain the desired outcome I will also have to return that variable see when I call +10 with an argument of 2 I obtain 12 it is all fine again print takes a statement or better an object and provides it printed representation in the output cell it just makes a certain statement visible to the programmer a good reason to do that would be when you have a huge amount of code and you want to see the intermediary steps of your program printed out so you can follow the control flow otherwise print does not affect the calculation of the output differently return does not visualize the output it specifies what a certain function is supposed to give back it's important you understand what each of the two key words does this will help you a great deal when working with functions the following could be helpful let the same function also print out the statement outcome if we put down only return outcome and then return result what will we get when we call the function just the first object to return the statement outcome if instead we print the statement and then return result we will get what we wanted the outcome statement and the result of the calculation 12 this was to show you we can return only a single result out of a function it isn't a secret we can have a function within the function for instance let's define a function called wage that calculates your daily wage say you use working hours as a parameter and you are paid $25 per hour so this should work okay good notice I don't technically need the print command here I could print out the wage afterwards but I don't really need to so I'll proceed this way just returning the value I need when you do well in a day your boss will be very happy to give a bonus of $50 added to your salary hence I'll define a with bonus function for you and as a parameter I will take again the working hours but this time I will allow myself to return directly the wage with working hours as an output which would be the value obtained after the wage function has been run plus the extra $50 you've earned this is how the first function is involved in the output of the second one a function within the function let's see what the output will be if you worked eight hours today and the boss was very happy with your performance wage with an argument 8 and with bonus with an argument of 8 great 200 of base compensation and 250 with the bonus we know how to work with if statements and we know how to work with functions in this lesson we'll learn how to combine the two this is a fundamental concept in programming so please pay attention you'll encounter it quite regularly when coding Johnny's mom told him that by the end of the week if he has saved at least 100 dollars she would give him an extra $10 if he did not manage to save at least $100 though she would prefer not to give him the extra cash clear now let's define a function called add tin which takes as a parameter the unknown M that represents the money Johnny saved by the end of the week what should we tell the computer to do if M is greater than or equal to 100 then add tin to the saved amount if it is not return a statement that lets us know Johnny should save more that is if M is greater than or equal to a hundred let M assume the value of M plus 10 yes it is what you saw we have em on both sides of the equation and that is perfectly fine as a matter of fact it is not an equation remember that the Equality sign stands for assigning the expression on the right side to what is written on the left side let's complete the if part with return M to sum up logically we mention M as a parameter then we substitute its value with a greater value than M with tin at the end we say from now on return a value equal to the new M finally in all other cases for instance save more Johnny should learn it is a good habit to have some cash on the side right let's see if our intuition was correct add 10 of 110 good 120 and if M was equal to 50 amazing everything is correct when you think of it from a logical perspective it makes sense doesn't it what would you use a computer for to solve problems for you and it can do that through functions you'll most probably need to ask the machine to execute something if a given parameter is within certain limits and ask it to execute another thing if the parameter is beyond these limits therefore combining your knowledge about conditionals and functions in Python comes right on the money great just keep the pace for our next video we are almost there in this lesson we'll learn how to work with more than one parameter in a function the way this is done in Python is by enlisting all the arguments within the parentheses separated by a comma shall I call the function we have here for say 10 3 & 2 I get four seems easy to add a few parameters right and it is just be careful with the order in which you state their values in our case I assigned tin to the variable a3 to be and to to see otherwise the order won't matter if and only if you specify the names of the variables within the parentheses like this B equals 3 equals 10 and C equals 2 and of course we could obtain the same answer for this is how we can work with functions that have multiple arguments awesome let's see what's next when you install Python on your computer you are also installing some of its built-in functions this means you won't need to type their code every time you use them these functions are already on your computer and can be applied directly the function type allows you to obtain the type of variable you use as an argument like in this cell type of tin gives int for integer the int float and string functions transform their arguments in an integer float and string datatype respectively this is why 5.0 was converted to 5 three was converted to 3.0 and the number 500 became text great now let me show you a few other built-in functions that are quite useful max returns the highest value from a sequence of numbers this is why max returned a value of 30 as an output in his cell good men does just the opposite it returns the lowest value from a sequence so we get tin in that cell over here it is the smallest among 10 20 and 30 another built-in function abs allows you to obtain the absolute value of its argument let Z be equal to minus 20 if we apply the ABS function to Z the result will be its absolute value of 20 see perfect an essential function that can help you a great deal is sum it will calculate the sum of all the elements in a list designated as an argument consider the following list made of 1 2 3 & 4 as its data when I type some list one my output will be equal to 1 plus 2 Plus 3 plus 4 the sum of these numbers equals Tim round returns the float of its argument rounded to a specified number of digits after the decimal point round 3 point 5 5 5 with 2 digits after the decimal point will turn into 3 point 5 6 if the number of digits is not indicated it defaults to zero three point two is rounded down to three point zero great if you are interested in elevating 2 to the power of 10 you know you could type to double start in you can get the same result if you use the pal function which stands for power right pal and in the parentheses specify the base and the power separated by a comma in our case 2 comma 10 execute with Shift + Enter and voila 1024 and what if you wanted to see how many elements there are in an object the Len function as in length is going to help you do that if you choose a string as an argument the Len function will tell you how many characters there are in a word for instance in the word mathematics we have 11 characters there are many other built-in functions in Python but these are a few examples you will often need to use when programming list is a type of sequence of data points such as floats integers or strings therefore understanding lists relates to your ability to organize data a crucial skill in today's labor market moreover you'll see Python creates a friendly environment for dealing with lists assume you wanted to create a list called participants that contains the names of John Lila Gregory and Kate follow the rules about creating a generic variable but be careful about two things place the strings within square brackets and make sure you use quotation marks precisely these brackets indicate the elements inside form a list and not some other type of a sequence good we see the participants list has already been prepared am I going to be able to extract the name of one member of the group of course I can do you remember how we extracted the letter D from Friday using brackets after the word Friday the logic here is the same all right the name of the list and in brackets I'll indicate the position corresponding to the name I am interested in it is important that I don't use parentheses or braces for instance let me extract the name of Leela as programmers we start counting from 0 so 0 1 1 should be the correct position and it is for the sake of argument in such a situation a computer scientist might say you have accessed the list by indexing the value 1 this means you have extracted the 2nd of the elements in this list variable okay nice in addition there is a way to get to the last element from your list start counting from the end towards the beginning then you need the minus sign before the digit and don't fall in the trap of thinking we begin in numerating from zero again to obtain Kate we have to ride minus one to obtain Gregory we need – to okay now let's study a key feature of lists replacing or deleting items in a list let's assume Kate had to quit for some reason but Maria could replace her here's what we can do across the value at position number three which currently refers to Kate and assign it with the string Maria let's check if our intuition was correct 100% amazing another scenario unfortunately Gregory got a better offer somewhere else so he quit as well there's nobody to replace him but we must adjust our list accordingly the del keyword could deliver the required result type del then correctly index Gregory's position by typing participants to and voila important to note is that deleting an element changes the indices of all successive elements after removing Gregory Maria's position shifted one place to the left and is now at the second position there is no element at the third position so a new name Dwain needs to be added to the participants list and will use a method called append think of the terms method and function as interchangeable because in practice methods work quite like functions however the technically correct term to use in this situation is method here is the syntax that allows you to call ready-made built-in methods that you do not have to create on your own and can be used in Python directly after the name of the object which in this case is the participants list we'll put a dot called a dot operator the dot operator allows you to call in or invoke a certain method to call the method append state its name followed by parentheses to insert the name to wane in our list we must put the string to wane in inverted commas between the parentheses after we execute the cell we should have Duane added to our group shift and enter correct great remember this general structure because we have to comply with it if we wish to call any existing method in Python alternatively the same result can be achieved by using the extend method let's invite George and Catherine in our group first let's invoke the extend method okay good this time within the parentheses we'll have to add brackets as we are going to extend the participants list by adding a list specified precisely in these parentheses execute through Shift + Enter and you'll have the two pieces attached the initial participants list and the extension thus you still managed to enlarge your original list write a couple more things before we close this lesson first let me show you that lists elements are directly treated as string values after printing this command we can see the first participant in our list is John it was not necessary to put any quotation marks around the participants element to do that perfect finally the line' built-in function counts the number of elements in an object for instance if our word is dolphin this function tells us it is composed of seven letters more importantly though this same function can be applied for obtaining the number of elements in a list applied to the list we have here it shows us the list and tells six members awesome to summarize observe how a built-in function takes the object participants as an argument while when we are calling built-in methods they are applied to the participants list with the help of the dot operator the different syntax helps you distinguish between the two by the way lists can be sliced too but more on that in our next video in this lesson we'll introduce you to another very important concept slicing in the future when working in Python you'll typically have to deal with data that is quite big many of the problems that must be solved will regard a tiny portion of the data and in such cases you can apply slicing imagine you want to use the participants list we saw earlier to obtain a second much smaller list that contains only two names Lila and Maria in pythonic that would mean to extract the elements from the first and second position to access these elements we will open square brackets just as we did with indexing and write 1 : 3 the first number corresponds precisely to the first position of interest while the second number is 1 position above the last position we need in our case 2 plus 1 equals 3 correct we can say we just sliced our participants list to obtain a new one with the names Leela and Maria I know this piece of syntax seems a bit strange but it is not that illogical let's get the first two names from the list John and Leela in this case you don't need a number at the beginning and you can start by typing a colon okay so by typing : 2 we get exactly the first 2 elements very good and how can I obtain the last 2 one way would be to indicate the fourth position corresponding to George and leaving nothing after the colon this would mean we will extract all the elements from the fourth position included to the end of our list another way to obtain the same result would be to put a minus sign in front of the number two thus python will revert the direction of counting starting from the end towards the beginning how many elements are we asking for – let's execute and here's the output we've obtained George and Katherine in a new list perfect okay let's check out some additional methods that can be applied to lists assume you know Murray is in your list but you don't know her position in other words you'd like to obtain the index of the element Maria from the participants list just call the index method and indicate the string variable of interest in parentheses the Machine tells us Maria is in the second position and it is the next functionality is an interesting one I will show you it is possible to create a list of lists my goal will be to create a list called bigger list which contains the participants list and a new one I will call newcomers let the ladder and close the names of Joshua and Britney shift and enter okay we created newcomers all I need to do in the next cell is write the name of the variable bigger list and site within brackets the names of the lists I would like to include let's verify if this works yes it does the two lists are shown in the suggested order great an important method that could order the names of your participants in alphabetical order is sort as you can see after applying it to our list catherine comes first and peter is last if within the brackets we say we would like the names to be sorted in a reversed order by stating reverse equals true Peter would be first and Catherine last naturally if our elements were sheer numbers instead of people's names this method would function without any problems observe how and this example I sorted the numbers from one to five from the smallest to the largest and here from the largest to the smallest wonderful this was a very important lecture tuples are another type of data sequences but differently to lists they are immutable tuples cannot be changed or modified you cannot append or delete elements the syntax that indicates you are having a tuple and not a list is that the tuples elements are placed within parentheses and not brackets by the way the tuple is the default sequence type in Python so if I enlist three values here the computer will perceive the new variable as a tuple we could also say that three values will be packed into a tuple for the same reason we can assign a number of values to the same number of variables do you remember we went through that a few lectures ago on the left side of the Equality sign we just added a tuple of variables and on the right a tuple of values that's why the relevant technical term for this activity is tuple assignment in the same way we did for lists we can index values by indicating their position in brackets that's why we obtained the first number from the tuple X namely 40 in addition we can also place tuples within lists and then each tuple becomes a separate element within the list tuples are similar to lists but there are some subtle differences we should not overlook they can be quite useful when dealing with different comma separated values for example if we have age and years of school as variables and I have the respective numbers in a string format separated by a comma hence the name comma separated values the split method with the proper indication within the parentheses will assign xxx as a value for age and 17 as a value for years of school we can print the two variables separately to check the outcome everything seems to be correct awesome last functions can't provide tuples as return values this is useful because a function which can only return a single value otherwise can produce a tuple holding multiple values check this code I will input only the length of the side of a square and as an output the square info function will return a tuple the tuple will tell me the area and the perimeter of the square you this is how we can work with tuples in Python now that you know what lists and tuples are you will more quickly understand what dictionaries are about dictionaries represent another way of storing data each value is associated with a certain key more precisely a key and its respective value form a key value pair in this example we have four keys different names of animals are attached to each one of them pay attention that neither parentheses nor brackets will work in this case you need curly braces after a certain dictionary has been created a value can be accessed by its key instead of its index kay one can be used for cat while k3 a mouse similarly as we could do with lists we could add a new value to the dictionary in the following way the structure to apply here is dictionary name new key name within brackets equality sign and the name of the new value the value will assign to key number five is parrot I'll press Shift + Enter and we are good to go replacing a value follows the same syntax just let the new variable correspond to an existing key from that moment on attached to the second key we won't see a dog anymore huh it's a squirrel now you feel a list should be able to take part in a key value pair and you are right let's turn to another example say only Peter works in Department one but three people work in department – Jennifer Michael and Tommy shall we verify right there for our second element is a list there is another way to fill in a dictionary I'll create a new variable and we'll use empty curly braces to indicate it'll be a dictionary I will not place any keys or values within the braces instead I will assign the keys in the values one by one and at the end my dictionary will be fool quite nice and if I asked for the center I will see Hector's name let me introduce you to an interesting Python feature if the get method gives us the name of the small forward of a given team the machine won't display an error if we ask for the name of the coach whose name does not take part in my dictionary none is the default value Python returns in cases where an object does not actually exist within a given dictionary now you can imagine that dictionaries could do a great job sometimes for instance when using companies names as keys and their prices on the market as values right Bravo you are going deeper into programming remember things will remain quite abstract unless you take the time to practice and apply what you've learned in these lessons iteration is a fundamental building block of all programs it is the ability to execute a certain code repeatedly in this section we will focus on a few examples of iteration processes in Python to begin we have prepared a list called even it contains all the even numbers from 0 to 20 imagine we want these numbers printed out so we can write the following 4 in and even : which would mean for every element in in the list even do the following print that element in this case in is called the loop variable it is not required to have called it in any other name would have worked fine the phrase print in access the body of our loop don't forget it should be indented to run the loop properly the command in the loop body is performed once for each element in the even list now let's go over the steps implied by this piece of code the loop starts by taking an element in from our list then the computer execute the body of the loop in our case it will simply print that variable when the computer is done with this operation called iteration or pass of the loop Python will go back to the for statement and pick the next element in that is in the even list it will then print out and so on and so forth until the loop body has been executed for all available elements in the list right let's apply this code to see the outcome exactly as expected all numbers were stated in a column what if we wanted to see them ordered in a single line a comma after the element in in the command print in will help us achieve that the comma will indicate every next element from the loop should be placed on the same row this was a short but important introduction to the concept of iteration in programming the same output we obtained in the previous lesson could be achieved after using a while loop instead of a for loop however the structure we will use will be slightly different initially we will set a variable X equal to zero and we'll say while this value is smaller than or equal to 20 print X but please be very careful and I mean it if you leave the code until here you will run into an infinite loop and your computer will crash this is a situation you want to avoid right so be very careful since X will always be smaller than 20 your loop will be infinite it will iterate the same variable repeatedly this is what we did here with x equals zero and always is not what we want in an iteration we want to get the loop to end what is supposed to succeed the loop body in the wild block is a line of code that specifies a change in X or what has to happen to X after it is printed in our case we will tell the computer to bind X to a value equal to X plus 2 let's see if it works awesome this is much better actually there is a term for what we just did in programming terms adding the same number on top of an existing variable during the loop is called incrementing the amount being progressively added is called an increment in our case we have an increment of two furthermore the Python syntax offers a special way to indicate incrementing x+ equals two shows we are incrementing the value of two on top of the base X just as if we had typed x equals x plus 2 as you can see the two outcomes are the same to conclude whether you will use a four or a while loop will depend mainly on your personal preferences what matters is that your code does not crash and provides correct results right pythons built-in range function can help us by creating a list of numbers the syntax of the function is the following type range and in parentheses mark a start stop and step value the start value will be the first number in the list the stop value will be greater than the last value in the list it is going to be equal to the last number plus one just classical pythonic logic right the so called step value represents the distance between each two consecutive values on the list the stop value is a required input while the start and step values are optional if not provided the start value will be automatically replaced with a zero and the step value would be assumed to be equal to one you could also remember the stop value as most important the start value is less important and the step value as least important for this reason range of 10 will provide a list of 10 elements starting from zero implied after not indicating a start value and ending at the tenth consecutive number number nine in another cell if in the range function we declare as arguments three and seven for instance Python will accept three as a start value and seven as a stop value of the range so we'll have four elements three four five and six good to specify step value in a range the other two arguments must be chosen as well in this situation I'll obtain a list with all the odd numbers from 1 to 19 included I will start with the number 1 and the list will end with number 19 which equals the stop value 20 minus 1 stating only the odd numbers this is how we can create lists with pythons range function in our next lecture we'll see how it can be applied in practice now that you know what the range function does let's see it in a for loop to print all the values from 2 to the power of 0 2 to the power of 1 and so on until 2 to the power of 9 we can use the following code for in in range of 10 print to double star in I will also have to insert a comma because I would like to see the output on a single line good I guess you can agree it was not necessary to specify the name of a list that exists in our code using a list created through the range function is going to work too now let's be brave and create an iteration that includes a conditional in the loop body we can tell the computer to print all the even values between 0 and 19 and state odd in the places where we have odd numbers let's translate this into computational steps if X leaves a remainder of 0 when divided by 2 which is the same as to say if X is even then print X on the same line else which means unless X is even or if X is odd print odd this is an example of a combination of an iteration and a conditional in Python there are two main ways to program a loop and until this moment we paid attention only to the first one we have a list X that contains the numbers 0 1 & 2 we saw we can print out each of its elements by typing for each item in the excellest print out that item the second way finds its practical application and more sophisticated codes its structure takes advantage of the range and Lin functions in the following way for each item and a range that goes through the elements from the list X that is Lynn with an argument X print out each item if we do this the variable item will loop through a new list created by range and that has as many elements as the X list itself please note that in this situation the second line of our code needs indexing to extract each item from the X list in practice we will print out the element at position zero from the list X then the element at position one and finally the element at position two to conclude both approaches can lead to the same outcome although the second one looks unnecessarily complicated in advanced coding it might turn out to be a lot more useful so it is important you know both we use iterations when we have to go through variables that are a part of a list in this lesson I'll show you how to count the number of items whose value is less than 20 in a list first define a function that takes as an argument numbers where numbers will be a certain list variable the trick is to create a variable that so-to-speak departs from zero let's call it total the idea is that when certain conditions are verified total will change its value this is why in such a situation it is appropriate to call this variable a rolling some more technically when we consider X in the numbers list if it is smaller than 20 we will increment the total by one and finally return the total value this means that if X is less than 20 total will grow by 1 and if X is greater than or equal to 20 total will not grow so for a given list this count function will return the amount of numbers smaller than 20 let's verify if this function works properly in this list we have four numbers that are less than 20 right let's check that out great now if I add 17 for example somewhere in the list the outcome will adjust accordingly five exactly perfect by the way look how the whole if statement is indented even more to the right this allows us to separate it logically from the rest of the code in the cell that refers to this function if you are eager to know how to iterate over a dictionary in Python and I am sure you are you will see this in our next video thank you for watching let's look at something a bit more challenging iterating over a dictionary we have a couple of examples here the prices of a box of spaghetti of a portion of lasagna and of a hamburger are stored in a dictionary called prices Jan went to the supermarket and bought six boxes of spaghetti ten pieces of lasagna and no hamburgers this data was stored in a dictionary named quantity our problem is how much did Jan spend in the supermarket well it is obvious you'll need to multiply the quantity of each food by its price you must have noticed our dictionaries have exactly the same keys we should exploit this the procedure to go to the box of spaghetti in the first dictionary and take the value of four then get the value of 6 from the quantity dictionary and then multiply those two must be repeated for each food product that must ring a bell I am sure you probably think the same we need a loop okay that's clear but what are we going to do with it what is the loops body going to contain before anything else some variable must account for the amount of money spent right let's implement a well known trick I'll create a rolling some called money spent which will initially assume the value of zero so we can start by iterating over each item in prices I in prices for short at every step of the loop I would like the money spent variable to grow by the product of the price in the quantity of a certain good I and that should be enough let's print the result to check whether we are working correctly apparently yes Wow such a simple problem in terms of mathematics required to connect knowledge on dictionaries iteration and creating a variable with an increment so from a programmers perspective the problem looks different the good thing is that at the end this whole thing boiled down to a mere four lines of coding as a side note do you realize that if we put quantity instead of prices here the outcome will remain the same so what is the conclusion it does not matter if you loop through prices or through quantity because the two dictionaries contain the same keys and this is the reason this loop works correctly – thanks for watching if you found this video interesting and want to gain an edge in your career make sure to LIKE comment and subscribe and don't forget to check out some of our other videos for another quick win in the data science skills department

One Reply to “Python Programming Bootcamp | Learn to Code in Python [Tutorial and Exercises]”

  1. Jie Jenn

    I noticed that you are using Python 2 in your tutorial. Isn't Python 3 would be more suitable since Python 2 is being retired slowly by most companies.

Leave a Reply

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