7 Simple Tricks to Write Better Python Code

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi my name is bas Amato and today I would like to show you seven simple tricks that you can use to make your fighting 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 and this I will I do this in fighting 3.4 but although all the tips and tricks are equally applicable to fight in 2.7 or whatever kind of version of fighting that is currently used by most people alright let's so let's start with the first trick and this this is a very gone 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 right so we want to get all the items from the list and their positions the very common but what bad way to solve this problem is to create a counter variable I which starts out at 0 right because the first position in the list is position 0 not position 1 with 0 and then we walk through all cities in the lists for city in cities we print out the counter variable and the name of the city and then we increment counter variable by 1 now if I select this and execute it you see that you see here in the terminal that this works right so it prints out 0 marsai more size the first city in the list amsterdam's the second one universe the third one and lonliness the fort one so it works but it is bad because we create it's quite difficult magma moderately difficult to grasp the logic at first side and we create this counter variable that we don't really need so let's take a look at good way five donek way to do this and that is using the enumerate function so what we can do is instead of walking directly walking directly through the list of cities we can pass the list of cities to enumerate and new enumerate returns a list of indices and city names right print so basically enumerate first returns is 0 comma more site then it returns 1 comma Amsterdam then returns to common New York and then it returns 3 comma long 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 this 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 counter variable as you see here in the bad way now let's move on to a scenario or tip number two which again has to do has to do with lists and the scenario is the Foley 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 to 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 cord right so instead of first looping through the X list and then looping through the wine 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 3 right because there are three items then we create a range from zero rode through the length to the length of this list so we get basically 0 comma 1 comma 2 and then we loop through that right so it is basically 4 I in 0 comma 1 comma 2 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're currently at right so we get for the first time we get 1 second time we get 2/3 times 3 we do the same for the y-coordinates but first time we get 2 & 4 & 6 and then we print them out now if I select this run it then you see here in the in terminal you see that it works right so the first x and y tuple basically that we print out is 1 & 2 then we print out 2 & 4 so 2 & 4 then we print print out 3 & 6 & 3 & 6 so that's what we want to do but it is very difficult to read right especially this range land X list thing is quite quite horrible so the good way to do this fighting is to make use of the zip function so what we can do is for X Y zip X list my list and then X Y so what zip does is it takes two or more lists and it really shifts them together so basically pairs creates creates tuples that bear items at the same positions in all of these lists right so it pairs one with two it bears 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 1 Y is 2 second time X is 2 y is 4 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's 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 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 so you a have two variables x and y and we want to swap their values so we start out with X being 10 and Y the 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 value variable so we assign the value of y to 10 then we assign value X to Y then we assign the value of them 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 enduring as well as 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 a and we also needed to create this temporary swapping value variable so good good way it's as follows comment after that way the good way is simply do this X Y is mine my X and we can do the whole swap in one line and this is a trick that is very cool you're very particular to fightin and it is really cool it's called tuple unpacking so what we do first we create a tuple so pair of values first the y coordinate then in the x coordinate and we then pack 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 and since we don't need this this this temporary swapping very variable then 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 10 but it is better because it is only one one line of code and it is also in my opinion much easier to read you can do the same trick if you want here so instead of instead of saying X is 10 and Y is minus 10 you can say X 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 earn back on the left hand side and this also needs to be tuple a particular biten by the data type you can use this kind of a yeah tuple and packing 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 have 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 values and we want to get the age of one person dick in this case but we are not 100% sure whether dick is actually in the in the dictionary that's a problem because if we just say okay H is ages dick right I select it and I run it then of course it crashes with a key error kierra dick because dick is not in this dictionary most people are aware that you need to check therefore you need to check whether dick 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 dick is actually in the dictionary then we get the age of dick 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 dick is been known years old right and if I add dick to the dictionary dick it will say ah and I exhale select it executed it will say dick is 51 years old right so gets dick 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 okay so what I'm typing here is the good way good let's go on this out okay so what I'm doing here is basically getting the age of dick from the fiction ages dictionary but if dick is not actually in this dictionary we fall back to a default value Brno so this single line expresses the same logic that took us four lines here right so it 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 tick is 51 years old if I removed it here from the dictionary selected run it it will say take a spin on years olds right because dick is no longer I comment a dick 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 a trick number five scenario number five which has to do with for loops and I think very few people are familiar with that with this particular trick now let's take the following scenario in which we have 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 of course we can do this just by asking if needle in haystack but that's not what we're going to do here we're going to use this little search demonstration to make it point so let's start with the bad way so what can we do we can start out by assuming by creating a market variable old found and assuming that the needle has not been found so we start out by saying founders fools then we loop through each letter in the haystack and if the letter matches the needle we print out found to do it to the terminal we set the marker variable to true and then we break the we break the list we break the loop right 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 after loser 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 a 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 that because we have this marker variable which is unnecessary and it's also makes a little 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 bitin bitin for loops 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 market variable here ne and then instead of saying if notes found we say else and what bit else basically needs here in this context or in any context is if no break occurred all right 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 loop through the entire haystack without encountering your needle we have not broken and therefore no break occurred and we execute this print not found so if I select this 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 a haystack so this works it does exactly the same thing as 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 so the bottom line is if you want to do something when you've at the end of the loop only if the loop was completely finished and this happens quite a lot then you should use the else statement in combination with a for loop right so you should think of else s if no break occurred so that's a very convenient trick to know okay so let's move on to trick number six source 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 a text file and to process each line from the text file one by one so let's say that we have the lyrics from pimping and easy by ice-t and we'll want to read those lyrics and print them out one line at a time then we can do something like the following in a bad way so what we do is we open the text file we read the context of the text file and save it in the variable text then we split the text by slash n so since slash and it's 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 terminal that it works right so take a look at me everything I own is iced out then maybe you can see my wrists with the light out this is how I do with mad in clothes golf follow baby only play to my rooms so that works what it is bad it is bad in two ways actually the first is that we we don't actually the the file object is quite sophisticated and we don't need to read the entire next 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 it 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 the individual lines the only difference being that in this case the line separations are not stripped off which is why you will you you see actual additional and blank lines so this is the the the better somewhat better way but there is an even better way what we can do is make use of a so called context with the width statement and it goes like this with open pimpin and easy the text SF for line and then we removed flow statement so what this means is that everything that is under with so these two lines are a context are executed in a context and disco and which means sounds very sophisticated but it just means basically that before this is executed files opened and after this is executed the file is automatically closed so the width statement basically allows us to do something without having to bother with cleaning up afterwards right closing the file is a way of cleaning up and if we use a with statement if we use context then we we don't need to bother with cleaning up so if I take this I take this and I execute it you see that it's still worked right still prints each of the lines out to their out to the terminal so especially you're not usually inviting 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 width 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 trick as a bit of an explanation about try and accept statements so catching exceptions catching errors that occur in your program now let's say that we want to convert something to an integer all right so say that we want to print say that we say okay we print out to the screen converting then we convert the string 1 to an integer so we take a string 1 and we turn it into the number 1 right so we change the data type we print it out to this to terminal and then we sit down I select this and execute it okay converting printout the one that's fine but let's say the we instead of trying to convert 1 we try to convert X then we run into problem if I learn 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 except statements so say try except for example say print version v and then if we take this and we execute it you say you see it prints out conversion fails but the whole program doesn't crash anymore right so we captured 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 so conversion successful and else is basically the opposite of accept so if no accepts accept so basically we try to convert this to an integer if it doesn't work we print that conversion field if it does work we print out conversion successful and then at the very end we print out done so if I select this execute it nothing changes right because fills it fills to convert to X so princess conversion filled but if I for example change this to one I select it execute it you see it says converting then prints have 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 supports another statement equal to finally state and finally basically it means always print well we can just move this print statement up here so whatever is endured finally in the finally block is always executed regardless of whether an exception occurred or not can also regardless of whether the conversion was successful now so basically you can think of it as follows we try to do the conversion if it didn't work we print out conversion field if you 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 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 L stand so we have this we have only a try and finally and if I take this I execute it all right it works now with say I I change this to neck so an error occurs execute it all right so we get a value error and then if we scroll up a little bit you see that done which comes from here still execute it and the logic is the following and it's very very convenient to know so if we tried it 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 it you can kind of put your clean up code here so imagine that you have an open file here and you're trying to do some stuff with file but an error occurs then you nevertheless want to close the file lucien and then you can do that under finally right because finally is executed even if an exception occurred so that's a very convenient convenient cleanup function right so in this case Don is printed out whereas if I would have just done basically would have just done this so just remove the hole then Don wouldn't have been printed out because as soon as this this line causes a crash all program stops so try you cannot only have a try except but you can ever try except else or you can ever try except else finally or you can even just have a try finally so try is very very first tile and construction that you can use in in various ways to to to handle exceptions that occur during the execution of your program okay well that was it I hope you found it found it useful and thank you for watching
Info
Channel: Sebastiaan Mathôt
Views: 306,040
Rating: 4.8565078 out of 5
Keywords: Python, programming, computer science, tutorial
Id: VBokjWj_cEA
Channel Id: undefined
Length: 25min 38sec (1538 seconds)
Published: Mon Dec 28 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.