Over the years, I’ve taken several programming courses, read dime-a-dozen articles, and written hundreds of programs. I could’ve done all of that better and faster, if I had known a few things – “hacks”, if you will. Here’s 11 tips I wish I knew back then which will help you program better and faster.
I had been interested in programming for several years, and took many free courses on dime-a-dozen platforms over the years. They were mainly beginner level courses that were way too generous with their compliments, leading me to believe I knew how to code (barring HTML / CSS etc, which I’ve been quite familiar with for a while).
Then in March 2018 I was given a project as part of one of my doctoral training programme – ‘replicate the results of a 4* Finance research paper’.
Coding knowledge was presumed, so no training was provided whatsoever. I was metaphorically “thrown into the deep end”, and was pretty clueless about how I was going to tackle this issue.
Despite all the free and paid courses I had taken, the reality was finally apparent – I did not really know how to code.
But unlike my previous attempts at learning how to code, this time I had very specific problems I needed to solve.
I found that this one simple thing led to an exponentially faster, and more interesting learning experience. Along the way, I also learned a few other things to get better, faster, and have fun while doing interesting work.
Here are the Top 11 Python Tips I wish I had known when I first started coding in Python.
Tip #1: Have a very specific problem you want to solve.
I can’t stress this enough. This really was the “make or break” for my learning. Having a (or few) specific problems you want to solve helps you focus on problem solving and learning code to solve those problems.
When I first started learning to code on places like CodeAcademy I felt like I was making some progress, but didn’t quite know what, where, how, or why I was “progressing”.
Although I was gaining knowledge on programming, I wasn’t really able to apply it to anything I find interesting. This also made the learning experience quite boring.
The entire experience changed as soon as I had very specific problems to solve. The overarching mandate was to replicate the results of a 4* Finance journal article. Specific problems I then encountered included:
How do I…
- Merge datasets?
- Sort data by quintiles or deciles?
- Construct and “rebalance” portfolios?
Where do I…
- Get data from efficiently?
- Find information on how some factor F is specifically measured?
- Learn how to plot dynamic graphs?
For me, these questions are a lot more interesting than say…
How do I…
- Create a function that calculates quotients.
- Write a for loop that iterates over a range from 1 to 10.
- Print a string reversed.
Of course, these questions – however uninteresting they might seem – are important ones. And I did end up learning how to do all of them and a whole lot more. But not while asking these generic questions.
I ended up learning how to do these things by asking the more specific questions highlighted earlier. This made the whole programming experience a lot more fun, fast, and practical.
It also means that you can see tangible, measurable evidence of progress. No need for excessive and arguably shallow “Great job!” compliments when you print(“Hello World!”).
Tip #2: Remember that you really don’t need to know everything.
Believe it or not, a large part of my day (still) goes in googling around for solutions. By no means am I a full fledged “Python expert” at this time, but even the pros spend a lot of their time googling around for solutions.
As you go along, the complexity of what you google will increase, but the frequency will likely remain roughly the same, maybe a tad bit lesser than when you just start out.
I found this remarkably accurate image while googling stuff around. Notice how a lot of the process comes right back to Google!
So don’t beat yourself up if you can’t remember how to read in a text file, or delete a column, or sort values. As long as you consistently write code, a lot of the things will just “come to you naturally”.
Make it a habit to google around and look for solutions on sites like Stack Overflow. But crucially, contrary to the image above, don’t just copy and paste code from there. Instead, write it out yourself so you get used to it. Especially if you’re in the “early days” of your coding journey. I’ll talk more about this further down in Tip #10. For now though…
Tip #3: Create your personal “Code Library”
This is something I started on much later into my journey, and kinda wish I had started right from the word go.
You’ll often end up repeating lines of code in different projects. For instance, virtually any “data analysis” intensive project will involve reading in a csv (or other dataset) of some kind. So you’ll inevitably go:
data = pd.read_csv('path_to_file' + 'file.csv') df = pd.DataFrame(data)
Or perhaps rename a column of your dataframe:
df.rename(columns = {df.columns[0] : 'my_col_name'}, inplace = True)
Although Python’s syntax is incredibly user-friendly and easy to read and understand, sometimes it’s easy to mess it up. For instance, in the the df.rename() code we used above, it’s easy to imagine using df.columns(0) instead of df.columns[0], which will lead to some sort of error.
A code snippets library will help you avoid making these “easy errors”. I personally use SnippetsLab which I find insanely great! It’s one of the best £10 I’ve ever spent. Here’s what a snapshot of my library:
Prior to using SnippetsLab, if I wanted to reuse code, or refer back to a problem I know I’ve solved before, I’d have to…
- Think about which file I solved this problem in.
- Locate said file and open it.
- Look for the specific line where the problem is solved.
- Rewrite said solution (can’t copy & paste because the variable names might be different).
With SnippetsLab, I can…
- Search for the problem I’m trying to solve.
- Rewrite solution (or copy & paste if my snippet is generic enough).
This system gets exponentially more useful as the complexity of programmes increases.
Especially because your Code Library isn’t limited to just code snippets. You could also maintain “checklists” and “cheatsheets” to speedup your workflow even more!
Speaking of speeding up your workflow…
Like what you see?
Fill in the form below and I’ll keep you in the loop!
Tip #4: Automate your repetitive code
Once you’ve got reasonably comfortable with your language of choice, it’ll be worth automating some of the standard lines of code.
For instance, most of my “financial data analysis” programmes start like this:
# file_name.py # Author: Vash # Last updated: 26 Mar 2019 """ Brief description of this programme goes here. """ import pandas as pd import numpy as np import datetime import os # Global paths path_to_databases = os.path.join( r"" ) path_to_workingDirectory = os.path.join( r"" )
So rather than typing the same things every time I want to start a new “financial data analysis” project, I just created a “snippet” on Alfred for Mac to automate this process.
Now when I use the magic word “cstart”, it automatically pastes the text above and I’m good to go! The “c” in cstart is just my chosen prefix (for coding), so I don’t end up with that text as soon as I use the word start!
Here’s what I mean:
All I need to do is paste the directory path, add a brief description about the programme, and I’m good to go!
Pro Tip: To use the magic word without getting it to activate:
- Type all the letters of the magic word except the last one.
- Move way from the magic word (right arrow)
- Move back to the magic word (left arrow).
- Type the last letter of the magic word.
The same goes for when I want to read in a csv file. Rather than defining it from scratch, I just use the magic word “ccsv”, which gives me:
pd.read_csv(path_to_workingDirectory + '.csv')
This way all I need to do is add the name of the file and I’m good to go.
Here’s just one more example. I like to label sections within a programme with #=== above and below the heading, and this too is easy to do with the magic word “cseccomment”
# ============================ # INSERT SECTION HEADING # ============================
Tip #5: Write great documentation (for your own sake)
Many people tend to whinge about writing documentation. The internet is also flooded with loads of programmes with little-to-no documentation whatsoever. And if you’ve ever read any of those, then you know it’s just a bit of a pain.
As you go along, you’ll end up writing tens, hundreds, perhaps thousands of programmes. And then you’ll end up going back to something you wrote a few months or perhaps years ago. Well documented programmes will make for better and quicker understandability as well as reusability.
And if at some point you have an epiphany like I did about the wonders of Open Source, then you might want to share your code with other people. Well documented code will make their life easy, too.
Of course it goes without saying that if you’re working on some programme with other people, you’ll certainly want need to have well documented code.
Now unless you really enjoy documentation for some strange reason, I’m sure you’ll agree it’s not the most exciting thing to do. So here’s something you can do to make the documentation process a little less painful:
Apply the Grandma (or Grandpa) Test
If you’re fond of your Grandma or Grandpa, and assuming they don’t know how to code, write out your documentation in a way they would be able to understand easily. Crucially, they should be able to understand it well without you explaining it to them!
If you’re not a fan of your Grandma or Grandpa, just think about anyone you know who doesn’t know how to code but wants to learn more about what you’re doing.
The bottom line… write with the end user in mind, not you.
Also, if you can spare a bit of time, it’s well worth reading the official PEP8 Style Guide for Python Code.
Tip #6: Use variable names that make sense.
As you go along, you’ll find your programmes becoming increasingly complex. Oftentimes, single programmes can have tens – possibly hundreds – of variables. Naming them something that makes sense and is easy to understand at first sight makes for an easier programming experience.
For instance, say you’re dealing with a list of customer names and for whatever reason, you want to identify customers whose names start with ‘A’.
A bad way to write this out is something like this…
cn = ['jack', 'jill', 'tom', 'harry', 'jo', 'amy'] for i in cn: if i.startswith('a'): print(i) # Output: ['amy']
It’d make better sense to write it as…
customer_names = ['jack', 'jill', 'tom', 'harry', 'jo', 'amy'] for name in customer_names: if name.startswith('a'): print(name) # Output: ['amy']
Or perhaps even better:
customer_names = ['jack', 'jill', 'tom', 'harry', 'jo', 'amy'] names_with_a = [name for name in customer_names if name.startswith('a')] print(names_with_a) # Output: ['amy']
They all give exactly the same result, but the latter two are just a lot more readable now, aren’t they?
Using names that make sense also helps minimise the amount of documentation needed. In the examples above, we probably don’t need any documentation since we can see we’re clearly talking about customer names. And for whatever reason, we’re interested in customers whose names begin with ‘A’.
Tip #7: Choose an editor that works well for you
I started off on Jupyter Notebooks and really loved coding on it. Jupyter’s incredibly powerful, and feels very friendly and non-intimidating. As time went by and my needs changed, I switched over to Atom, which is my preferred and only IDE now.
I like the fact that I can use Jupyter’s core features within Atom itself. For instance, being able to view dataframes, and run single line codes and see the effects then and there. I also love the fact that I can change to a dark theme (as well as hundreds of other themes). This is all thanks to all the themes and ‘packages’ Atom offers as free addons.
It just makes for a much more personal coding environment.
Other well known IDEs include Sublime Text, PyCharm, and perhaps Spyder. There’s a really great, detailed overview of all the Python IDEs here.
If you’re just starting out on your coding journey, I strongly recommend Jupyter Notebooks. It’s got just the right amount of functionality to help you get started and get on with it. It’s got a clean and minimalistic feel to it, making it a great coding / development environment.
Tip #8: Save your code. Seriously.
IDEs for whatever reason don’t appear to have caught up to the age of autosave. I myself have had to rewrite large chunks of code simply because I didn’t save my work and the editor ended up crashing for some or the other reason.
It’s easy to forget to save your work especially because most of the apps you’re working with will likely autosave. Take it from me – you don’t really want to have to redo your work!
If I remember correctly, Jupyter does have some level of autosaving, but it’s not anything like the autosave on say, Google Docs.
Atom shows you an annoyingly helpful blue dot to remind you that you have unsaved changes. There’s a special sort of feeling when you see that blue dot go away after you hit cmd+s (or ctrl+s).
# Tip 9: Focus on getting better, continuously.
Always ask yourself if you can achieve the same thing with fewer, cleaner lines of code. Especially when you’re doing things that are repetitive.
A simplistic “progress report” during a large for loop might look like this…
if files_renamed == 1: print("1 file renamed. Original name: ", file) elif files_renamed == 100: print("100 files renamed. Last one: ", file) elif files_renamed == 1000: print("1,000 files renamed. Last one: ", file) elif files_renamed == 5000: print("5,000 files renamed. Last one: ", file) elif files_renamed == 10000: print("10,000 files renamed. Last one: ", file)
This would be better:
progress_points = [1, 100, 1000, 5000, 10000] for point in progress_points: print(f"{point} files renamed. Original name: ", file)
This example also goes to show that improvement shouldn’t be measured by the number of lines of code you can write. And despite me very much being an “Apple Boy”, I can’t seem to find a better quote to really make this point stand out. So here’s Uncle Bill:
“Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”
– Bill Gates
That being said, if you’re just starting out on Python, you might well measure your progress by the number of lines you can write. Assuming you code everyday going forward, it’ll be worth changing this metric after 2 – 3 weeks.
Here’s an oversimplified function that may help you keep track of your progress:
def checkMyProgress(num_lines_added, num_lines_reduced): return num_lines_added + num_lines_reduced checkMyProgress(10, 2) # Output: 12
Tip #10: Stick to one language until you get good
It’s tempting to learn multiple languages, especially during the early days when you’re just testing the waters.
The fact is, languages tend to be incredibly similar in terms of their capabilities. Especially the more modern languages. So if you know one language well, you’ll find it fairly easy to learn another one. But learning multiple languages right from the word go is likely a guaranteed way to make life difficult.
Now that I’m quite comfortable with Python, I find reading and writing code in R quite straightforward. Of course, I find Pythonic code to be a lot more readable and user friendly, but feel that R is a pretty close contender.
And while I can’t code in JavaScript yet, being able to code in Python means that I can read and understand JavaScript, as well as other languages.
# Tip 11: Have fun!
Granted, there are times when things can get frustrating. When you’re trying to do something that seems to simple in theory and it just won’t do it for whatever reason.
Remember that it could be a lot worse. You could be forced to use MATLAB for instance. The horror. Or one of the many other languages which don’t have such an easy to read syntax and style.
Thanks to Python’s multiple use cases, you can use it outside of work too! For instance, you can use Python to…
- Create Amazon Alexa skills to customise your Alexa device.
- Automate your home using Internet of Things (IoT) technology.
- Send automated emails, WhatsApp messages, text messages – for instance, on people’s birthdays.
- Check the sentiment of a stock, industry, region, or country based on tweets.
- Develop functional / dynamic websites from scratch.
- Automate the boring stuff (literally)
- Do anything you can imagine.
BONUS Tip: Don’t reinvent the wheel code
Coding something from scratch is amazing. It’s amazing because you’re literally creating something from nothing.
Thanks to Python’s open source system and culture, a lot of the code you’ll need is already out there. So before you start working on a massive programme / project, check GitHub and other sites that host people’s programmes and packages.
In some cases, it’s good to reinvent the code because it helps you gain a better understanding of why the programme works the way it does. But if you know why it works the way it does, and you know how to code it pretty much from scratch, then there’s no harm in just using a package.
What you don’t want, is to be in a place where you’re using packages without really knowing what, why, and how they’re doing whatever they’re doing.
This is particularly important for troubleshooting and dealing with bugs in packages. It’s extremely rare to find major issues in packages like Pandas and NumPy of course. But it’s not uncommon to find errors in smaller packages. And by knowing how the programme works, you can even contribute to improving it if you find bugs, or a better way of doing it!
And that’s it!
So there you have it. Those are the 11 12 Python Tips I wish I knew when I first started learning Python. Well done if you did read this 3,000 word post fully!
Do you have any particular tips that work well for you? Let me know!
Want more Python Tips?
Fill in the form below and I’ll keep you in the loop!
Feature Image by Jantine Doornbos on Unsplash
Leave a Reply