Python Programming Bootcamp 2020 | Learn to Code in Python [Tutorial and Exercises]
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 5 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 5 is equal to 15 divided by 3, 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 Hooray! Will it work if we check for 5 being equal to 18 divided by 3? It is not supposed to, since 5 differs from 6 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 “Hooray!” 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 the if-condition is not true, our program will directly lead us to some other output or, as it is in our case, to 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 equals sign Isn’t 5 different from 3 times 6? Yes, it is It is True that it is different Hence, we have “Hooray!” 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, and “Case 2” if it is less than or equal to 3 Ok, we could write two if-statements one after the other Let’s see if we get the correct outcome Yes, we are in case 2 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 3” That translates into “when x is less than or equal to 3” Let’s verify if what we did was correct Bingo! Case number 2! 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 2” 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!
This is the right moment to introduce you to the notion of blocks of code 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 keyword, 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 a tail with the respective block that says “return “Equal” Let’s confirm we wrote the code correctly We can print out the “compare to five” 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? Ok Perfect What if we carry out this operation for the number 2? The machine tells us that 2 is less than 5 And that’s what we expected To obtain the third outcome, we must compare the number 5 with a number that is not greater or smaller than 5 This will happen only if the argument of the function is 5, 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 0, the string “Negative” should be displayed I will place this block between the if and the other elif statement Let’s see what happens The function with an argument of minus 3 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 0 and 5, say 3 Yes, we see “Less”, so everything is ok 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 1, which is printing the string “Greater” The computer will disregard the elif and 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 2, which is printing the string “Negative” If not, we will get to statement number 3 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 Ok? Let me print “compare to five” of minus 3 Ha! Instead of “Negative” we obtained “Less” This is how the computer reasons: assume y equals -3 Print out “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 examined 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 4, print out “Correct” In all other cases, print “Incorrect” 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 4, the machine will print the corresponding statement “Correct” Else, which means if the statement “x greater than 4” 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 0s and 1s, “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 Python’s functions – 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 Def is neither a command nor a function It is a keyword To indicate this, Jupyter 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 а good style of coding! All right, 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 parentheses See? Great! Ok, 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 10 as a result… Always begin with the “def” keyword Then, type the name of the function, “plus ten”, 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” plus 10” This will be the body of this function Now, let’s call “plus ten” with an argument 2 specified in parentheses Amazing! It works Once we’ve created a function, we can run it repeatedly, changing its argument I could run “plus ten” 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 “plus ten” 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 plus ten with an argument of 2, call plus ten 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 programming, 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 ten” or “addition of 10”, and the function will still run correctly This is a sign of good design On a sheet with one thousand 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 ten” with an argument of “a” and a colon On the next line, instead of directly returning the value of “a” plus 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 to 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 “plus ten” with an argument of 2, I obtain 12 It is all fine again “Print” takes a statement or, better, an object, and provides its 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 keywords does This will help you a great deal when working with functions The following could be helpful Let that 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 that statement and then return ‘result’, we will get what we wanted: the “outcome” statement and the result of the calculation – 15 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 dollars per hour So this should work Ok 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 dollars 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 dollars 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 8 hours today and the boss was very happy with your performance Wage with an argument 8, and “with bonus” with an argument 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 dollars If he did not manage to save at least 100 dollars, though, she would prefer not to give him the extra cash Clear Now, let’s define a function called “add 10”, 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 10 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 “m” 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 value greater than “m” with 10 At the end, we say: from now on, return a value equal to the new “m” Finally, in all other cases say, 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, and 2? I get 4 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 10 to the variable a, 3 to b, and 2 to c 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, a equals 10, and c equals 2 And of course, we could obtain the same answer – 4! 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 As a matter of fact, you saw examples of built-in functions in the lesson about data types The function “type” allows you to obtain the type of variable you use as an argument, like in this cell – “Type” of 10 gives “int” for integer The “int”, “float”, and “string” functions transform their arguments in an integer, float, and string data type, respectively This is why 5.0 was converted to 5, 3 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 this cell Good “Min” does just the opposite – it returns the lowest value from a sequence So, we get 10 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, and 4 as its data When I type “sum list 1”, my output will be equal to 1 plus 2 plus 3 plus 4 The sum of these numbers equals 10 “Round” returns the float of its argument, rounded to a specified number of digits after the decimal point “Round” 3.555 with 2 digits after the decimal point will turn into 3.56 If the number of digits is not indicated, it defaults to zero 3.2 is rounded down to 3.0
Great! If you are interested in elevating 2 to the power of 10, you know you could type “2 double star 10” You can get the same result if you use the “pow” function, which stands for “power” Write “pow”, and in the “parentheses”, specify the base and the power, separated by a comma In our case, “2 comma 10” Execute with “Shift and Enter” and… voilà! 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 Great! We’ve made excellent progress so far! By now, you know a bit more about Python’s syntax, about if, elif, and else statements, and about functions In this section, we’ll cover an important topic for Python programming – lists So, what is a list? A 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, Leila, Gregory, and Cate 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 I’ll write 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 Leila As programmers, we start counting from zero, 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 second of the elements in this list variable Ok, 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’d need the minus sign before the digit and don’t fall in the trap of thinking we begin enumerating from 0 again! To obtain “Cate”, we have to write -1; to obtain “Gregory” we need -2 Ok! 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: access the value at position number three, which currently refers to “Cate”, and assign it with the string “Maria” Let’s check if our intuition was correct 100 percent! Amazing! Another scenario: unfortunately, Gregory got a better offer somewhere else, so he quit as well There is 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 2” and voilà! 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, “Dwayne”, needs to be added to the “Participants” list, and we’ll 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 on or invoke a certain method To call the method “append”, state its name, followed by parentheses To insert the name “Dwayne” in our list, we must put the string “Dwayne” in inverted commas between the parentheses After we execute the cell, we should have Dwayne 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 Ok, 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 and 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, right? 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 “Len” 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 7 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 entails 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 – Leila 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 colon 3 The first number corresponds precisely to the first position of interest, while the second number is one 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 Leila 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 Leila In this case, you don’t need a number at the beginning, and you can start by typing a colon Ok, so by typing colon 2, we get exactly the first 2 elements Very good! And how can I obtain the last two? 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 2 Thus, Python will revert the direction of counting, starting from the end towards the
beginning How many elements are we asking for? 2 Let’s execute And here’s the output – we’ve obtained George and Catherine in a new list Perfect Ok, let’s check out some additional methods that can be applied to lists Assume you know “Maria” 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 latter enclose the names of Joshua and Brittany Shift and Enter… Ok, we created “Newcomers” All I need to do in the next cell is write the name of the variable “Bigger List” and cite 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, in this example, I sorted the numbers from 1 to 5 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 tuple’s 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 the 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 30 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 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 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! K1 can be used for cat, while K3 – a mouse! Similarly, as we could do with lists, we can 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 we’ll assign to key number 5 is parrot I’ll press Shift plus Enter and… we are goоd 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 Ha, 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 1, but three people work in department 2 – Jennifer, Michael, and Tommy Shall we verify? Right Therefore, our second element is a list There is another way to fill in a dictionary I’ll create a new variable and will 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 and the values one by one, and at the end, my dictionary will be full 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 function 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 “for n in even”, colon, which would mean
for every element n in the list “even”, do the following: print that element In this case, n is called the loop variable It is not required to have called it n; any other name would have worked fine The phrase print n acts as 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 n from our list Then, the computer executes 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 “n” that is in the “even” list It will then print it 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 “n” in the command “print n” 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 = 0 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 “while” 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 two Let’s see if this 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 a loop is called incrementing The amount being progressively added is called an increment In our case, we have an increment of 2 Furthermore, the Pythonic syntax offers a special way to indicate incrementing “X Plus equals two” shows we are incrementing the value of 2 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 for 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? Python’s 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 0, and the step value would be assumed to be equal to 1 You could also remember the stop value as most important, the start value as less important, and the step value as least important For this reason, “range of 10” will provide a list of 10 elements, starting from 0, 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 3 and 7, for instance, Python will accept 3 as a start value, and 7 as a stop value of the range So, we’ll have 4 elements – 3, 4, 5, and 6 Good To specify a 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 Python’s 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 “n” in range of 10, print “2 double star n” 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” Lovely! 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, and 2 We saw we can print out each of its elements by typing “for each item in the x list, print out that item” The second way finds its practical application in more sophisticated codes Its structure takes advantage of the range and len functions in the following way: “for each item in a range that goes through the elements from the list x, that is “len 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 0 from the list x, then the element at position 1, and finally the element at position 2 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 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 0 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 sum More technically, when we consider x in the numbers list, if it is smaller than 20, we will increment the total by 1 and finally return the total value This means that, if x is less than twenty, 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 5 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 6 boxes of spaghetti, 10 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 4, 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 Ok, that’s clear, but what are we going to do with it? What is the loop’s 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 sum, called “money spent”, which will initially assume the value of 0 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 and the quantity of a certain good “i” And that should be enough Let’s print the result to check whether we were 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 programmer’s 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, too Thanks for watching!