Some Tips and Tricks for Writing Better Code in Python
When I started python I should have known about these. I used to solve problems on URI Online Judge. I started facing many problems that occurred because of runtime errors and many errors. During my journey, I found these tips and tricks very helpful especially for those who have started their journey very recently.
- We may have seen many programs like this if x is greater than 5, print more than 5 elements are there; else there could be 5 or fewer elements. Let’s see an example.
2. Separate long numbers using underscore( _ ) like this: 10_000_000. You can also format your string to show the number with commas.
3. Use enumerate() to show index numbers without getting complex.
4. You can use zip function to combine two or more lists or tuples. This one will help you a lot. you can also create a dictionary from lists easily using zip.
5. You can merge two dictionaries easily by following below.
6. Avoid variables that you don’t need to call. Let’s assume we have to print Hello, World! 10 times. we can easily print it using python’s for loop. We don’t need to declare i or any variable for this. We can just use underscore( _ ).
Both of the loops will print 10 times Hello, World! So, we should stop declaring unnecessary variables.
These are very simple tips for python but really very useful and essential.