 Hi, my name is Sebastia Matteau and today I would like to show you seven simple tricks that you can use to make your Python code easier to read, simpler and just in general more beautiful. All of these are solutions to very simple but common problems that you encounter while writing Python code and that people tend to solve in suboptimal ways. So I will show you several simple ways just to efficiently solve little problems that you might encounter. I will do this in Python 3.4, but all the tips and tricks are equally applicable to Python 2.7 or whatever kind of version of Python that is currently used by most people. Let's start with the first trick. This is a very common scenario in which we have a list, in this case a list of cities, and we want to walk through this list, this list of cities, while printing them out for example to the terminal and also printing out their position in the list. So we want to get all the items from the list and their positions. A very common but bad way to solve this problem is to create a counter variable, i, which starts out at zero because the first position in the list is position zero, not position one, but zero. And then we walk through all cities in the list, so for city in cities, we print out the counter variable and the name of the city and then we increment counter variable by one. Now if I select this and execute it, you see here in the terminal that this works, right? So it prints out zero, Marseille, Marseille is the first city in the list, Amsterdam is the second one, New York is the third one and London is the fourth one, so it works. But it is bad because we create, it's quite difficult, moderately difficult to grasp the logic at first sight and we create this counter variable that we don't really need. So let's take a look at the good way, the phytonic way to do this and that is using the enumerate function. So what we can do is instead of walking directly through the list of cities, we can pass the list of cities to enumerate and enumerate returns a list of indices and city names, right? So basically enumerate first returns is 0, Marseille then it returns 1, Amsterdam then returns 2, New York and then it returns 3, London. And if I select this and I execute it, you see here in the debug window that it works, it does exactly the same thing as the bad way but it is easier to read and it avoids two lines and it also avoids this temporary counter variable. So the bottom line is that whenever you have a list and you want to walk through this list and at the same time keep track of the positions in this list, you should usually use enumerate and not create a kind of a counter variable as you see here in the bad way. Now let's move on to scenario or tip number 2 which again has to do with lists and the scenario is the following. Say that we have two lists for example a list of x coordinates and a list of y coordinates and we want to walk through these two lists at the same time for example to print, for example to draw a dot at these coordinates, right? So we want to first get the first x-coordinate and first y-coordinate then next time get the second x-coordinate, the second y-coordinate and then get the third x-coordinate and the third y-coordinate, right? So instead of first looping through the x-list and then looping through the y-list, we want to loop through both lists at the same time. Now this is quite a common problem and I think you'll usually see it solved in this kind of awkward way that you see here. So what you can do first is get the length of x-list which is three right because there are three items then we create a range from zero through the length to the length of this list so we get the basically zero comma one comma two and then we loop through that right so it is basically four i in zero comma one comma two that's what it says here even though it's quite difficult to read. Then we get the x-coordinate at the position that we currently at right so we get the first time we get one, the second time we get two, third time we get three. We do the same for the y-coordinate so the first time we get two and four and six and then we print them out. Now if I select this and run it then you see here in the in the terminal you see that it works right so the first x and y tuple basically that we print out is one and two then we print out two and four so two and four then we print print out three and six so three and six so that's what we want to do but it is very difficult to read right especially this range length x-list thing is quite quite horrible. So the good way to do this in Python is to make use of the zip function so what we can do is for x y in zip x-list y-list and then we print x y so what zip does is it takes two or more lists and it really zips them together so basically pairs creates tuples that pair items at the same positions in all of these lists right so it pairs one with two it pairs two with four and it pairs three with six and then basically you can say okay walk through each of these pairs so the first time is x is one y is two the second time x is two y is four etc and then we can print it out so if i select this and i run it you see that it does exactly the same thing as before right the only thing is that it is shorter we have saved two lines of codes and it is much more readable right so the bottom line is that whenever you have two or more lists and you want to walk through these lists at the same time you probably want to use zip instead of devising a kind of an awkward ugly range construction that you see below now let's move on to scenario number three which again is a very common scenario and it is the following say the way you have two variables x and y and we want to swap their values so we start out with x being 10 and y being minus 10 but we want to swap this so that x becomes minus 10 and y becomes 10 then what you usually do is you use this kind of or what most people do is use this kind of temporary variable so we assign the value of y to temp then we assign the value of x to y then we assign the value of temp to x and then we've done the swap right so we need this temporary variable to make sure that we don't lose one of the values in the in the during the swapping now if i select this and i run it you see that it works right before x is 10 and y is minus 10 and afterwards x is minus 10 and y is 10 so it works but it's bad because it is we have the swap took us three lines and it is uh uh and we also needed to create this temporary swapping value variable so the good way says follows comment out that way up the good way is simply do this x y is y comma x and we can do the whole swap in one line and this is a trick that is very peculiar very particular to python and it is really cool it's called tuple unpacking so what we do first we create a tuple so a pair of values first the y coordinate and then the x coordinate and we unpack it to the left hand side so basically it means y gets assigned to x and x gets assigned to y and because this whole line whole line happens at one at the same time right it happens instantaneously in a sense uh we don't need this this this temporary uh swapping variable temp that we needed before right because we don't lose we don't lose any of the values in the swapping process now if i take this and i execute it you see that it does exactly the same thing as the bad way so x goes from 10 to be minus 10 y goes from minus 10 to be 10 but it is better because it is only one uh one line of code and it is also in my opinion much easier to read now you can do the same trick if you want here so instead of uh instead of saying x is 10 and y is minus 10 you can say x comma y is 10 comma minus 10 right so whenever the number of items basically on the right hand side matches the number of things that you unpack on the left hand side and this also needs to be tuple a particular python uh python data type you can use this kind of uh yeah tuple unpacking multiple assignment or whatever you want to call it right so i'm not sure whether in this case it is worth it but in this case it is definitely worth it so whenever you want to swap variables around using this kind of tuple unpacking can be a very convenient tool to use okay now let's move on to scenario number four trick number four which has to do with dictionaries again a very common problem that many people run into so say that we have a dictionary in our case a dictionary of ages and the names are the keys and the ages are the values and we want to get the age of one person dig in this case but we are not 100 sure whether dig is actually in the in the dictionary that's a problem because if we just say okay age is ages dig right i select this and i run it then of course it crashes with a key error key error dig because dig is not in this dictionary now most people are aware that you need to check uh therefore you need to check whether dig is actually in this in the dictionary and it can be done in the following way in the following bad way you can say okay if dig is actually in the dictionary then we get the age of dig from the dictionary else we fall back to a default value called unknown and if i select this and i run it you see it works it says dig is unknown years old right and if i add dig to the dictionary dig it will say and i select it execute it it will say dig is 51 years old right so gets dig from the dictionary so this works in that sense it's fine but it's ugly because we have these four lines of code just to get something from the dictionary so we can do it better and we can do it better in the following way we can make use of the get function so what i'm typing here is the good way good way let's comment this out okay so what i'm doing here is basically getting the age of dig from the dictionary but if dig is not actually in this dictionary we fall back to a default value unknown so this single line expresses the same logic that took us four lines here right so basically get gets a value from a dictionary but it also takes a default value to fall back to if the value is not in the dictionary so it's a very convenient function to know about now if i select this and i execute it you see it works dig is 51 years old if i remove dig here from the dictionary select it run it it will say dig is unknown years old right because dig is no longer i comment to dig out of this out of the dictionary right so whenever you want to get things from a dictionary but you're not actually sure whether the thing that you want to get is in the dictionary it is nice to use the dot get function of a dictionary which takes a default value in case the value is not in the dictionary okay so let's move on to trick number five scenario number five which has to do with for loops and i think very few people are familiar with with this particular trick now let's take the following scenario in which we have a needle the letter d and we want to search a haystack which is a list of letters to see if d is actually in this list now of course we can do this just by asking if needle in haystack but that's not what we're gonna do here we're gonna use this little search demonstration to make a point so let's start with the bad way so what can we do we can start out by assuming by creating a marker variable called found and assuming that the needle has not been found so we start out by saying found is false then we loop through each letter in the haystack and if the the letter matches the needle we print out found to the to the terminal we set the marker variable to true and then we break the we break the list so we break the loop and then at the end of the loop we check our marker variable to see if the needle was found and if not we print out not found to the terminal so if i select this and i run it it prints out not found which is correct right because our needle d is not in the haystack if i add the needle to the haystack and i run it it will say found which is again correct because of course now the needle is actually in the haystack but this is bad because we have this marker variable which is unnecessary and it also makes the whole logic of the thing a little bit more difficult to understand so how can we improve this well we can make use of the fact that python uh python for loops uh have an else statement which is a bit odd but very powerful so what is the good way the good way is to start out by removing this marker variable here and here and then instead of saying if not found we say else and what else basically means here in this context or in any context is if no break occurred right uh so this whatever is under else is only executed if no break statement occurred during the loop so what we have is the following logic we loop through the haystack if we encounter the needle we break and therefore do not execute this however if we looped through the entire haystack without encountering the needle we have not broken and therefore no break occurred and we execute this print not found right so if i select this i execute it will say found because the needle is in the haystack if i remove the needle from the haystack and i select it and execute it will print not found right so because the needle is no longer in the haystack so uh this works it does exactly the same thing as the the bad way but it is better because it is less lines of code we don't need this marker variable found right and it's just overall more easy to understand easier to understand um so the bottom line is if you want to do something when you've at the end of a loop only if the loop was completely finished and this happens quite a lot right then you should use the else statement in combination with a for loop right so you should think of else as if no break occurred so that's a very convenient trick to know okay so let's move on to trick number six or uh which has to do with file reading a very common thing to do with the text file if you have a simple script is to read the text file and to process each line from the text file uh one by one so let's say that we have the lyrics from Pimpen and Easy by Iced and we want to read those lyrics and print them out one line at the time then we can do something like the following in a bad way so what we do is we open uh the text file we read the context of the text file and we save it in variable text then we split the text by uh slash n so since slash n is a line separation so basically we split the entire text up into individual lines and then we walk through all of these individual lines we print them out to the screen and then afterwards we close now if I select this and I run it you see here in the terminal that it works right so take a look at me everything I own is iced out Pimp baby you can see my wrists with the light out this is how I do it mad bitches in clothes godfather baby only play to my ropes so that works but it is bad it is bad in two ways actually the first is that we we don't actually the the the file object is quite sophisticated and we don't need to read the entire text and we don't need to manually split it we can just loop directly over the file object so basically we can basically the file object supports this supports if you can use a file object as an iterator you can loop through it and it will return you individual lines so if I select this and I run it you will see it also loops through all of the uh the individual lines the only difference being that in this case the line separations are not stripped off which is why you will see you you see actual additional blank lines so this is the the the better way the somewhat better way but there is an even better way what we can do is make use of a so-called context with the with statement and it goes like this with open pimp in an easy the text sf for line and then we remove the closed statement so what this means is that everything that is under with so these two lines are a context uh are executed in a context and this and which means it sounds very sophisticated but it just means basically that before this is executed the file is opened and after this is executed the file is automatically closed so the with statement basically allows us to do something uh without having to bother with cleaning up afterwards right closing a file is a way of cleaning up and if we use a with statement if we use a context then we we don't need to bother with cleaning up so if I take this and I take this and I execute it you see that it still works right still prints each of the lines out to the out to the terminal so especially you you will not usually in python you don't encounter contexts that often so many people may not be familiar with the with statement but especially when working with text files or files in general using the with statement is very powerful because it just makes the logic of your your code cleaner and easier to read okay so let's move on to the seventh and final trick which is maybe not so much a trick as a as a bit of an explanation about try and accept statements so catching exceptions catching errors that occur in in your program now let's say that we want to convert something to an integer right so say that we want to print say that we say okay we print out the screen converting then we convert the string one to an integer so we take a string one and we turn it into the number one right so we change the data type we print it out to the terminal and then we say done I select this and I execute it it's okay converting print out the one that's fine but let's say that we instead of trying to convert one we try to convert x then we run into problem if I put problems if I take this and execute it you see we get a value error right because you cannot convert the string x to an integer that's just not possible python doesn't know how to do that so then what you need to do when I think most people are familiar with that is you use a try accept statement so say try accept and for example we say print conversion filled and then if we take this and we execute it you say you see it prints out conversion filled but the whole program doesn't crash anymore right so we we capture the the error that occurs and then we just let the program continue that's nice but what also what you can also do is use the else statement and that I think many people do not know so conversion successful and uh else is basically the opposite of accept so if no accept so basically we try to convert this to an integer if it doesn't work we print out conversion filled if it does work we print out conversion successful and then at the very end we print out done so if I select this I execute it nothing changes right because it fills it fills to convert the x uh so it prints out conversion filled but if I for example change this to one I select it execute it you see it says converting then prints out one then prints out conversion successful and then says done right so the try statement just like the for loop quite surprisingly supports an else statement which in this context context just means if no exception occurred the try statement even uh supports another statement called the finally statement and finally basically means uh always print uh well we can just move this print statement up here so whatever is under the finally in the finally block is always executed regardless of whether an exception occurred or not and also regardless of whether the the conversion was successful now um so basically you can think of it as follows we try to do the conversion if it didn't work we print out conversion filled if it did work we print out conversion successful but regardless of whether it worked or not we print out done so if I select this execute you see it says converting one conversion successful done just like before basically now the finally statement may seem a little bit pointless because you can just as well you could just as well do this right does does the same thing in this case but it does serve a purpose in the following way let's say that we have a try statement but we have no accept and no else statement so we have this we have only a try and finally and if I take this I execute it all right it works now but say I I change this to an x so an error occurs I execute it right so we get a value error um and then uh if we scroll up a little bit you see that the done which comes from here is still executed and the logic is the following and it's very very convenient to know so if we try this and an error occurs then before this error is actually propagated up in the program so before basically the program crashes we still execute whatever is under finally so it's kind of a you can kind of put your cleanup code here so imagine that you have an open file here and you're trying to do some stuff with the file but an error occurs then you nevertheless want to close the file usually and then you can do that under finally right because finally is executed even if an exception occurred so that's a very convenient uh convenient cleanup function all right so in this case done is printed out whereas if I would have just done uh basically would have just done this huh so just remove the whole uh then done wouldn't have been printed out because as soon as this this line causes a crash the whole program stops so try you can not only have a try accept but you can have a try accept else or you can have a try accept else finally or you can even just have a try finally so try is very versatile construction that you can use in in in various ways to to to handle uh exceptions that occur during the execution of your program okay well that was it I hope you found it uh found it useful and uh thank you for watching