Python from Scratch:

Automate a to-do list using Python (for true beginners!)

annalect
9 min readJan 8, 2019

The following article was written by Kate Borst, one of our innovators at AnnalectLabs. For more from Kate, you can find her here.

If you can type, you can program.

Motivation: You have a looooong to-do list and hardly even have the time to read it, none-the-less accomplish everything on it. Where do you even begin? If only your computer could tell you how to order your list! Well, it can, but you have to tell it how. That’s where Python comes in, and yes, even you can do it!

Python is a programming language. That’s all you need to know for now! You can download it here, or if you’d prefer to work in your browser, you can use this in-browser version. Throughout the tutorial, there will be links to the code so that if you don’t want to follow along (or you think you made a mistake) you can see what the finished code looks like. You can edit this code and use it as a jumping-off point, too! To begin, if you’re working on your local machine (your computer), once you have installed Python, navigate to your Terminal (or Command Prompt if you’re on a PC*), type python (and hit [return] or [enter]) and you will be in what we call a Python Terminal. If you’re using the in-browser version, this is what you see when you first load the page. However you access it, the Python Terminal is a great place to start experimenting with simple Python code!

* This tutorial was written for a Mac, and while the majority of Python commands will work on either a PC or a Mac version, if something isn’t working for you, Google the command + “on a PC” and there should be some online answer to what the PC version of that command is.

Experimenting with some basics…

Click here to see an interactive version of the below code.

A print statement tells Python “I want to see this output”.

print(a<b)

OUTPUT:
NameError: name ‘a’ is not defined

This error showcases the difference between a variable and a string in Python. A variable is a representative for another Python object. Think of it as giving something a name, so that later on in your code you can make references to it. The way to set a variable is to use one single equals sign (=) like so:

a = 4 
b = 12
print(a<b)

OUTPUT:
True

In the above, the variable a is a representative of the number 4, and the variable b is a representative of the number 12. So when we ask Python, “Is a less than b?” We’re really asking, “Is 4 less than 12?” To which, of course, the answer is yes, that is true. Then, because we asked Python to print the output, it prints the word True. Simple enough! We can also compare values of letters in Python, which comes in handy when you’re trying to alphabetize things (like, for example, a to-do list! don’t forget…that’s what we’re doing…eventually).

To do this, we need to use strings. A string is a data-type that is some letters and/or numbers strung together, wrapped in either single or double quotation marks. It can be a word, a sentence, a paragraph, or even a serial number.

string1 = 'Look at me! I am a string!! :-)'
string2 = "I am also a string"
string3 = 'AB@X125"!@wuB5%'
print(string1)
print(string2)
print(string3)
print('a'<'b')

OUTPUT:
Look at me! I am a string!! :-)
I am also a string
AB@X125"!@wuB5%
True

Notice that the “less than” operand (<) works with strings too, using alphabetical order. If you have time, play around some more in your Python Terminal.

Some terminology…

Dictionary- {key1 : value1, key2 : value2}
A dictionary is a set of values, coupled with keys that point to them, similar to how a dictionary (the book) has words (keys) and definitions (values) that belong to them, which allows you to “look up” a potentially unknown value by the key. It is always enclosed in curly brackets ({}), has keys and values separated by a colon (:), and key-value pairs separated by commas (,). The following example shows how to look up a value based on a key by placing the key in square brackets following the dictionary variable.

my_numbers_dictionary = { 1 : ‘one’, 2 : ‘two’, 3 : ‘three’ }
print(my_numbers_dictionary[1])

OUTPUT:
one

You can also print a list of all of the keys in a dictionary using the .keys()method:

print(my_numbers_dictionary.keys())

OUTPUT:
[1, 2, 3]

Lastly, you can add a new element to a dictionary by setting the value for the desired key using the equals sign, shown below. The value can be almost any type of object, such as a string, a list, or even another dictionary!

my_numbers_dictionary[4] = 'four'
my_numbers_dictionary['list'] = ['I', 'am', 'a', 'list']
my_numbers_dictionary['dictionary'] = { 'key' : 'value' }
print(my_numbers_dictionary)
print(my_numbers_dictionary.keys())
print(my_numbers_dictionary['dictionary']['key'])

OUTPUT:
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, ‘list’: [‘I’, ‘am’, ‘a’, ‘list’], ‘dictionary’: {‘key’: ‘value’}}
[1, 2, 3, 4, ‘list’, ‘dictionary’]
value

List- [item1, item2, item3]
A list is a collection of items in a specific order. Items can be repeated and are indexed starting with 0 (because computers are weird like that) so the first item in the list has index 0, the second has index 1, etc.

my_list = ['apple', 'orange', 'pear', 'apple']
print(my_list[0])
print(my_list[1])
print(my_list[0] == my_list[3])

Notice that because we use a single equal sign (=) to give values to variables, the way to compare whether two things are equal to each other is to use TWO equal signs (==).

OUTPUT:
apple
orange
True

Functions- A function is a way of telling Python to do one or more things in a specific order. They can be very complex or very simple, but have the basic structure:

def myFunction(input):
< some stuff the function should do >
return output (this is not always necessary)

Here are some examples:

def print_something_five_times(input): #this is where we define a function
print(input)
print(input)
print(input)
print(input)
print(input)
#this function does not return any value
print_something_five_times('Hello!') #this is where we 'call' the function

OUTPUT:
Hello!
Hello!
Hello!
Hello!
Hello!

def add_two(input):
#this function adds two to the input, and returns the result
output = input + 2
return output
print('3 plus 2 is')
print(add_two(3))

OUTPUT:
3 plus 2 is
5

We can pass the output of one function into another function:

print('3 plus 2 plus 2 is')
print(add_two(add_two(3)))

OUTPUT:
3 plus 2 plus 2 is
7

When we use a function inside the definition of another function, it’s called a helper function. In the following example, add_two is a helper function being used in the function add_four.

def add_four(input):
input_plus_two = add_two(input)
output = add_two(input_plus_two)
return output

print('3 plus 4 is')
print(add_four(3))

OUTPUT:
3 plus 4 is
7

Now that we’ve had some fun playing around with some basics, let’s move on to our task today: sorting a list of things we have to do!

Activity: Sort a list

Just like when you learned how to write an essay in elementary school, coding is easiest when you start by making an outline and a simple (“rough draft”) version of your program. It is a good practice to write a comment at the top of your program that explains what it does. As you go, and your program gets more and more complicated, you may take these comments and make them into a README file, so that someone who may want to run your code can do it without your help.
Our objective is to sort a to-do list. In our first iteration, we will store our to-do list in a list type object and simply alphabetize it.

Click here to see an interactive version of the below code.

todo = ['put away laundry', 'do the dishes', 'wash the car']def sort_my_list(list):
list.sort()
return list
print(todo) #before sorting
sort_my_list(todo)
print(todo) #after sorting

OUTPUT:
[‘put away laundry’, ‘do the dishes’, ‘wash the car’]
[‘do the dishes’, ‘put away laundry’, ‘wash the car’]

Python has a built-in list-sorting method .sort() which works using the built-in ordering for the type you are working with. Since we are working with strings, if you recall from before, the ordering is alphabetical by default. Simple enough, right?

Now, alphabetizing a list isn’t really the best way to go through your chores. It would probably make more sense to sort the tasks by an estimated completion time, or value added, or some other number associated with each task. To do this, we’re going to use a dictionary object, with the task as the key, and the estimated amount of time it will take the complete the task as the value.

Click here to see an interactive version of the below code.

todo = {'put away laundry': 45 , 'do the dishes' : 10, 'wash the car' : 20}def sort_my_list(todo_dict):
done = []
for key in todo_dict.keys():
done.append(list((key, todo_dict[key])))
done.sort(key = lambda x : x[1])
return done
print(sort_my_list(todo))

OUTPUT:
[[‘do the dishes’, 10], [‘wash the car’, 20], [‘put away laundry’, 45]]

You may be thinking, WHAT THE HECK? But stay with me. We’ll dissect this bit by bit.

First, we create an empty list called done.
Then, for each of the keys in our to-do list (for each task), we are appending (adding) a list that looks like [task, time] to our list called done. We are left with a list of lists. You may ask why we didn’t start with it in that format to begin with (this will become apparent later!). Now that we have a list, we can use Python’s built-in sorting method .sort() again! Hooray!
Except we no longer have a list of something nice like the strings we had before, which had a built-in alphabetical order, but instead we now have a list of lists. So we need to tell Python how it should sort the objects in the list called done.
That’s where this key = lambda x : x[1] part comes in. The key part means “sort by this value” and the lambda part basically means “I’m making a teeny tiny little function here, where for the x that you (Python) were trying to sort (in this case, a list) just pretend you’re looking at the element x[1] of it and sort based on that. So if you’re looking at the item [‘do the dishes’, 10] please sort it based off of the value 10.”

Hopefully, that makes a little more sense now! And there you go!! We have a list sorted by the amount of time it takes to complete each. If you’d rather do the most time-consuming task first, you can add the clause reverse=True to the .sort() method, like so:

def sort_my_list(todo_dict):
done = []
for key in todo_dict.keys():
done.append(list((key, todo_dict[key])))
done.sort(key = lambda x : x[1], reverse=True)
return done

Finally, we’re going to step it up a notch (just one last time!) and see if we can associate multiple values with each task, using dictionaries.

Click here to see an interactive version of the below code + extra credit solutions.

todo = {'put away laundry': {'time':45, 'urgency':3,'completed':False}, 'do the dishes' : {'time':10, 'urgency':2, 'completed':False}, 'wash the car' : {'time':20, 'urgency':5, 'completed':False}}
def sort_my_list(todo_dict, how='time'):
done = []
for key in todo_dict.keys():
if not todo_dict[key]['completed']:
done.append(list((key, todo_dict[key][how])))
done.sort(key = lambda x : x[1])
return done
print(sort_my_list(todo))
print(sort_my_list(todo, 'urgency'))

OUTPUT:
[[‘do the dishes’, 10], [‘wash the car’, 20], [‘put away laundry’, 45]]
[[‘do the dishes’, 2], [‘put away laundry’, 3], [‘wash the car’, 5]]

Adding the how='time' input to the function sets the default value for that input equal to 'time' meaning that this input is optional for the function. If the user doesn’t include this input, then the function will take it to be 'time', though it could also (in this case) be set to 'urgency'. Using a dictionary object, we can associate many different aspects of the task with the task so that Python can not only tell us which order to perform them in, but also whether it has been completed, perhaps who has completed it, when it is due, etc. You can get creative with it!

Great job! You’ve written your first couple of Python functions, and you’re well on your way to becoming a Python programmer. Keep going and when you’re confused about something, Google it! There are thousands of resources online to help you learn, and you’ll learn best by doing, making mistakes, and debugging!! Good luck!!

-Kate

P.S.
Extra credit 1:
Write a function that can write a simple sentence to tell you which order to perform the tasks (great practice with string and list manipulation).

Extra credit 2 (advanced):
Learn how to import and use the datetimePython methods, and adding a due date for the task and ability to sort by due date.

Kate works on the AnnalectLabs team, the rapid prototyping and experimentation department at Annalect. Its purpose is to build fast, stimulate experimentation, and push r&d forward within the company.

Annalect is the data, technology, analytics, and consulting division of Omnicom Media Group (OMG). Sitting as a foundation of technical expertise, Annalect manages all product development, data management, and advanced analytics to support client embedded teams in the OMG agencies.

--

--

annalect

Provider of data-driven marketing strategy, powered by a connected system of technology, analytics, and consultants. Latest insights: http://bit.ly/2wYLdOP