Most Useful Things To Learn in Python for Beginners
If you’re just getting started in Python there are some things you should learn that will get you productive right away. In my experience with learning from no prior technical experience, I’ve found that 90% of what you’re doing is manipulating data structures to do what you want. Here’s the things I would recommend you learn right away so you can do some damage.
List Comprehensions
Once you’ve learned the “for” loop for iterating through a list of items, there is a much easier way to write out a loop called a “list comprehension.” It’s like a shorthand for loop that keeps your code clean and very readable.
# This is a for loop that is pretty common
new_list = []
for item in list_of_items:
if item.property > 15:
new_list.append(item)
# This is the same thing with a list comprehension
new_list = [i for i in list_of_items if i > 15]
This reduced 4 lines into a simple one liner. It’s cleaner, more readable, and does the same thing. Read up on them. In python 2.7 and up you can also do this with dictionaries!
Datetime
Sometimes you need to manipulate time (whoa). There is a built in package in python for just that. If you need to figure out last week’s date or subtract time or figure out what day of the week it is 1000 days from now then datetime has you covered.
# What was last week's date?
from datetime import datetime, timedelta
today = datetime.today()
last_week = today - timedelta(days=7)
print last_week.strftime("%A %m/%d %Y")
Functions or Don’t Copy and Paste
If you look at code and you’re like, “Man I really just need that code I used over there in here,” then you need to learn to use functions. Code reuse is a skill that you will need because it will be easier to read, maintain, and change. General rule of thumb, if you need to do something more than once, make a function out of it. Don’t copy and paste, it’s a disaster waiting to happen.
# Basic function example
def add(x, y):
# x, y are arguments to the function
# If the function is called with x,y
# the values are available in this namespace
# Do some stuff to the arguments x, y
z = x + y
# Return back the value of the stuff you processed
return z
There’s a Package for that
Python is very much a “batteries included” language in that there are built in packages for handling most common problems that will come up. There’s time and date, file io, url tools, and the list goes on. If it’s not already in the core of Python then there is probably a library someone has written that does what you want. Check out PyPy or go through github. You’re problem is almost certainly not unique and someone has probably solved it already.
I’ll probably add some more to this post, but I’m running low on coffee…
1 Notes/ Hide
-
joeconyers liked this
-
alexkehayias posted this