Congratulations on deciding to learn programming! Programming is one of the most useful skills you can learn. It's great fun, too!

In this article, I'll lead you through the very basics of programming in bite-sized chunks. Each tutorial is meant to take no more than 20 minutes, often less. You'll find lots of challenges and exercises so you can remember what you learn.

Before you start working through these tutorials, you might like to read last issue's article on how to learn programming. It shows you how to approach tutorials and work through problems strategically. 

Let's get to it!

Day 1: What's Python all about? 

We're going to be learning Python. Python is one of the world's most popular programming languages. Because Python is very popular, lots of people have written code in it you can include in your own programs. There's code you can use to make your own games, get information off the internet and control robots. Python makes it easy for you to build off others' work.

Python was published in 1991 by Guido Van Rossum, a programmer from the Netherlands. He borrowed lots of the best ideas from older programming languages. Python is very powerful, but at the same time it's also very easy to read. See if you can guess what this code does:

def open_files(input_filename, output_filename):
	input_file = open(input_filename, 'r')
	output_file = open(output_filename, 'w')
	
	if len(input_file.read()) == 0:
		print("There's a problem! Input file is empty!")
		return False
	else:
		return True

In the following lessons, we're going to be going step-by-step through just the basics. As you learn, try to mess around and experiment as much as you can. You'll learn a lot just by making mistakes. 

Day 2: Getting ready to go 

Let's get stuck in. Today, we get your computer ready to run Python. 

What we're going to do is install a program called an interpreter. We have to do this because the programming languages we write can't be understood by the computer. We need to translate our code into the language the computer speaks. That's the job of the interpreter.

If you're on GNU/Linux, you almost certainly have Python already installed. Check by opening a terminal and typing python3. If you see something saying something like Python 3.10.40, you're all set. If not, you might need to run apt install python3 on Debian-based systems or pacman -S python on ones based on Arch. 

If you're on Windows, you'll need to download and install Python. You can download it from https://www.python.org/downloads/release/python-3140/. Download the 'Windows Installer 64-Bit' from the bottom of the page. To install Python, go to your Downloads folder and double click on the installer you downloaded. The instructions will show you exactly what to do. 

Day 3 and 4: Meet the interpreter 

Today we actually start writing some Python! First things first: let's open the Python interpreter. 

If you're on GNU/Linux, you already know what to do: open a terminal and type python3

On Windows, you need to open Command Prompt. To do that, hold the Windows key and R at the same time. When a little window comes up, type cmd in the box and hit Enter. From here on out, you'll need to do this every time you start the day's tutorial. 

The interpreter will print some stuff to screen, then sit there waiting for you to start typing:

You see those three arrows? That's Python telling us it's ready to work. Anything we type will appear after them. 

Let's move on. For around 50 years, almost every new programmer's first program has been a cute little program to print hello, world to screen. In Python, the Hello World program is just one line. It goes: 

print("hello, world!") 

Try it: type it into the interpreter, then press Enter. Type it exactly, without any capital letters or extra spaces. 

If you did it right, the interpreter will say hello, world right back! 

Let's try doing some maths. Doing maths in Python is a lot like doing maths with a calculator. The only difference is you use * for multiplication and / for division. Python does multiplication and division first, just like in algebra. You can use brackets when you want to change the order things are done. 

Try typing ((3 + 4) * 5) / 4. Do the calculation by hand and check Python's answer.

In programming, we often make mistakes. It's easy to mistype something or use Python wrong. It's important to know what will happen if we mess up. 

In Python, you're not allowed to divide by zero, just like in maths. Try typing 4/0 and see what Python says. 

When we try to divide by zero, Python replies ZeroDivisionError: division by zero. ZeroDivisionError is the name of the kind of error you made; what's after the double dots explains what happened. Of course, Python is telling you nothing here you don't already know. 

We're nearly done for the day. It might be a good idea to learn how to leave Python, no? If you want to leave Python you can it in two ways. You can type quit() or you can hold the Ctrl and D keys together at the same time. Everything you did in the interpreter will be deleted. 

Challenges 

Every other day from here on out, there'll be challenges to help you remember what you learnt. Today, there are two: 

Challenge 1: Open the interpreter, and put in the equation below into Python. Check your answer against a calculator. When you get the right answer, quit the interpreter. Try to do this without looking at the tutorial. 

Challenge 2: Type Print(print me!) into the interpreter. What errors do you get? How do you fix the program so it works? 

Day 5 and 6: More maths 

At the bottom of it, computers are just oversized calculators. Every document you write, video you watch or photo you take is just numbers to the computer. A lot of what you do in Python will be adding, subtracting, multiplying and dividing.

You've already seen how to do basic calculations in Python. You know how to use +, -, * and /. You also know Python follows the same order of operations as in algebra. 

There are two more things you should know: how to raise a number to a power and how to find the remainder when you divide. 

To raise a number to a power, you use the ** operator. For example, if you want to find x2, you'd type x**2. If you want to find the remainder after a division, you use the % operator. For example, if you want to find the remainder of 5 divided by 3, you'd write 5 % 3.

Give it a go. Can you find the remainder of 123÷ 9.5? 

So far, all the results of our calculations have gone once we've done them. What if we want to save them for later? 

In Python we keep information in variables, which are like boxes for data. Variables have names and a type. A type is the kind of data a variable can hold. Some of the types we've seen so far are integers (whole numbers), floating point numbers (numbers with decimal points) and strings (text between quotes). 

There are complicated rules about what you can call variables, but if you stick to using letters, numbers and the underscore, and make sure you don't use a word that means something in Python, you'll do fine. Just make sure you never start a variable name with a number -- the interpreter will try to treat it like one! 

Variables are created when you store something in them. If you want to store something in a variable, you assign it to it using the equals sign:

variable = value 

You can assign variables to other variables, and replace the data later: 

variable1 = variable2
variable1 = 3 

Variables can be used just like the data they contain. 

hello = "hello, world!"
print(hello) 
weight = 10
totalweight = weight * 2 

You often have to change a variable by a number, so Python gives you a short way of writing assignments like x = x + y:

  • x += y is the same as x = x + y
  • x -= y is the same as x = x - y
  • x *= y is the same as x = x * y
  • x /= y is the same as x = x / y
  • x % y is the same as x = x % y

In you interpreter, try creating and using variables of different types and try calculating stuff with them. Experiment with assigning variables of different types with each other. See what happens when you assign a number with a decimal point to an integer. 

Challenges 

Challenge 1: Unlike many other programming languages, Python can store some very big numbers as integers! Unfortunately, those big numbers have to be stored somewhere. Using the ** operator, can you find out what happens if a number is too big to store? You can stop a calculation that's going on too long by holding Ctrl and C at the same time; otherwise, you might need to turn your computer off by holding down the power button! (Hint: you can nest exponents using brackets). 

Challenge 2: The formula for calculating the circumference of a circle is 2pir. Can you write a program that calculates the circumference of a circle of 9.2m? Store the radius and pi in their own variables.

Day 7 and 8: How to read input and how to run Python from disk 

Until now, all the programs you've written have disappeared when you quit Python. If we want to use our code again, we need to save it somewhere. 

When we write source code to a file, we can't just use a word processor like LibreOffice or Word. Those programs add a lot of information that Python can't understand. Instead, we need something that will store just what we type and nothing else. 

On GNU/Linux, you want to use a text editor like nano, vi or emacs. nano is the easiest to learn. You can run nano from the terminal just by typing its name at the prompt. Later, if you do a lot of programming, you might like to learn vi or emacs. However, there's no space to show you how to to use them here. 

On Windows, you can use Notepad. You can open Notepad just like the command prompt. Hold the Windows key and R, then type notepad in the box that appears. 

To run code you've saved to a file, you start Python by adding the filename, like this: 

python3 my-code.py 

When the program is running, the interpreter won't show you anything except errors and anything you've asked the program to show on screen. When Python reaches the end of the file, it'll stop. You can also end your programs with quit():

print("hello")
quit()

Now we know how to save programs to file, we can write bigger ones. Let's go back to our program to calculate the circumference of a circle. 

It would be far more useful if the user could tell the program the radius to use. In Python, we can ask for the user to input something and store their reply in a variable by using input()

variable = input("Type the radius of the circle: ") 

When input() stores the answer, it doesn't store it in a way that we can use in calculations, but as characters. Characters are used for writing. If we want to use the user's input in a calculation, we need to convert it to a floating point number (remember, a floating point number is a number with a decimal). We can do this by putting the variable inside float() like this: 

radius = input(radius)
radiusTimesTwo = float(radius) * 2 

The equivalent to float() for whole number is int(). Try converting numbers back and forth using float() and int(). What happens to what's after the decimal point? 

Challenges: 

Challenge 1: Find a text editor on your system. Open the program, then create and save a file. 

Challenge 2: Rewrite your program to find the circumference of a circle, but this time ask the user for the radius. Save it to file and try it out. Does it work the same? What happens if you type in words instead of numbers when you run it? 

Day 9 and 10: Decisions, decisions

Programs aren't very useful if they can't do different things in different situations. Python lets us make decisions with the if statement. 

The if statement looks like this: 

if variable > 2:
	print('variable is bigger') 

This means 'if the variable is bigger than two, print 'variable is bigger' to screen'. 

There are a couple things you need to be very careful about. You see how the second line is further in than the first? That's because Python uses indentation to show what code you want run if the condition is true (we say "the code in the block"). If you don't put the tab in, Python will complain that it was waiting for you to type an indented line. Secondly, it's very important that you indent using the Tab key, not the space bar. The Tab key sits above Caps Lock. 

Type if 2 > 3: into your Python interpreter. Do you see the three arrows be replaced by three dots? That means that Python is expecting you to type some indented lines for the if statement. When you're done, you can just hit Enter on a blank line to tell Python you're done. 

When you want to add more code after the block, just stop indenting: 

if x < 5:
	print('x is smaller than 5') 
print('done') # this will be run no matter what x is. 

You can also put if statements inside another if statement's block, so long as you indent everything properly: 

if age < 20:
	if age > 12: 
		print('teenager') 
	print('minor') 

There are two more parts to the if statement. You can add code that will be run if the condition is false:

if age > 3:
	print('not a baby') 
else: 
	print('a baby') 

You can also chain if statements together with elif (short for 'else if'): 

if age > 3:
	print('not a baby') 
elif age > 12: 
	print('not a child') 
elif age > 18:
	print('an adult') 

Try writing different if statements with elif and else

Challenges:

Challenge 1: Write a program that asks for two numbers and tells you if the first is bigger than the second

Challenge 2: Expand your program from Challenge 1 so it asks for three numbers and shows the biggest one. 

Day 11 and 12: More comparisons 

We've learnt about four different data types so far: integers, floating points, strings and characters. Now we'll add a fifth: a boolean

When you add two integers, Python returns an integer. When you're using the interpreter, the return value is what's shown on the screen. Return values can be stored in variables and used in other expressions (an expression is a piece of code). 

Just like +, > also returns something. In this case, it returns a boolean. A boolean is a special data type that can only have two values: true or false. Just like integers and floats, you can assign values to booleans. You use the words True and False (note the capitalisation!):

b = True
c = False 

You can see how comparisons return a value by assigning them to a variable: 

Comparisons are one type of conditional. There are more we can use. Here are some of them: 

  • > means 'greater than'
  • < means 'less than'
  • == means 'equal to' (notice there are two equals signs so it doesn't get confused with assignment)
  • != means 'not equal to'
  • >= means 'greater than or equal to'
  • <= means 'less than or equal to'

You can also combine comparisons with and, not and or

  • and returns true if both conditions are true
  • or returns true if either condition is true
  • not reverses the truth of the conditional

It works if you use brackets, just like when you're doing maths. For example, we can write: 

if not (w >= y and z <= w):
	# do something 	

(Note that anything after # in a line of Python won't be read by the interpreter.)

It's a very common mistake to mix up == and =. If you confuse them, Python will complain:

Challenges 

Challenge 1: You saw that * and / go before + and -. We say they have higher precedence. and, or and not also have different precedences. Which one has the highest? 

Challenge 2: To the computer, booleans are small whole numbers. Can you find out what numbers the computer uses for true and false by converting booleans to integers? 

Challenge 3: The if statement will run the code inside it so long as the condition's return value is not false (or the integer that means false). Because of this, almost anything can be used as the condition. Can you use this fact to write an if statement that can test if a number is not zero without using ==

Day 13 and 14: The while loop 

One of the best things about computers is that they can do things over and over again without getting bored or tired. One of Python's ways of doing something over and over again is called the while loop. 

while runs code over and over again while some condition is true. It looks like this: 

x = ''
while x != 'q': 
	x = input("Press q to stop the loop! ") 

If there's some reason you need to quit the loop before the condition is true, you can use break:

x = 0
while x < 10: 
	x = x + 1 
	do_quit = input("Press q to quit: ") 
	if do_quit == 'q': 
		break 

Challenges 

Challenge 1: A infinite loop is one that will run forever. Write a program that starts an infinite loop and stops when the user tells it to. Use input(). (Remember: you can kill a misbehaving program with Ctrl-C) 

Challenge 2: Write a program that calculates the first 100 numbers in the Fibonacci sequence. The Fibonacci sequence goes like this:

1 1 2 3 5 8 ...

Each number after the first two is calculated by adding the two previous numbers together. 

Day 15 and 16 : Lists 

When we write programs, we want to combine variables into bigger structures. Think about all the information we might store about a character in a game: we need to know her position, what's in her inventory, her health and what moves she can do. One of the most simple ways of combining data is simply to put it in a list. 

A list in Python is just a collection of things one after another. The 'things' in a list can be anything: numbers, letters, variables, or even other lists. You can use the what's in a list if you know where it is (its index). The first item in a list has an index of 0. For example: 

myList[0] # 'the first item in the list'
myList[2]  #'the third item in the list'
myList[100] #'the 101st item in the list' 

There is also a way to use a range of items in a list : 

myList[2:6] # 'every item from 3 to 6'
myList[5:14:2] # 'every second item from 6 to 14' 
myList[:6] #'every item to 6' 
myList[3:] # 'every item from 4' 
mylist[:40:3] #'every third item from the start to 40'

Getting used to counting from zero can take a bit of getting use to. If you have a problem with a list, try to check if you're using the index you mean to.

To create a list, we put the items we want in brackets like this: 

myList = [pi, 3, 'g', '$'] 

Lists containing lists are made like this: 

listInList = [4, '%', [3, 't', "hello"], 3]
# or:
innerList = [3, 't', "hello"] 
listInList = [4, '%', innerList, 3] 

When we want to use a list that has another list in it, you use a second pair of brackets. To get "hello" from the list above, we type:

listinList[3][3] 

You can use lists within lists to make tables. For example, you could write part of the times tables like this:

timesTable = [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]] 

This is the same as: 

1  2  3  4
2  4  6  8
3  6  9 12
4  8 12 16

Experiment with making and using lots of different lists like you've seen in today's tutorial. 

Challenges 

You're half-way to the end of the tutorial! It's time to review. Spend some time rereading the previous lessons and going over what you've learnt. 

Day 17 and 18: The for loop

 When you've got a list, you often want to do something for each of the items in it. Python has a special way of doing that. It looks like this: 

for number in list:
	print(number) 

This means 'take each item from list in turn, copy it to the variable number and print it'. The variable name we use at the start of the for loop can be called anything we want. It's deleted once the for loop is done. 

If we want to use only every second item, we can use range(): 

for n in range(0,len(list), 2):
	print(list[n]) 

This might be a bit hard to understand. range() returns a list containing numbers from the first number to the second one. The last number between the parentheses is how big the steps are. 2 means every second one, 3 means every third one and so on. If there's no third number, it's the same as putting 1 in. len() returns the size of the list you type between the brackets. So range(1,len(list),2) means 'return a list of numbers from 1 to the length of list, taking steps of size 2'. 

Notice how in this second example, we're using brackets to get the number from our list. This is because n will only have a number from range() in it, not items from the list.

Challenges 

Challenge 1: Write a program that uses a for loop to calculate all of the times tables from 1 to 10. Use this format: 

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40

... and so on

You'll need to tell the program how long the lists are using this code: 

table = [[],[],[],[],[],[],[],[],[],[]]
timeTables = [] 
for n in range(1,10): 
	timesTable.append(table)

This makes a list containing ten empty lists of ten items each. 

Challenge 2: In some programming languages, all for loops work more like our example with range(). For example, in C, a for loop looks like this: 

for (int i = 1; i <= 10; i++)
{ 
	printf("%d", list[i]); 
} 

i works like counter. This loop counts from 1 to 10, adding 1 to i at the end of each go through. Every time the loop runs, it prints another item from list. Can you write the above code in Python using range()

Challenge 3: The for loop with range() is very similar to a while loop. Can you rewrite the program in Challenge 2 using while

Day 19 and 20: Strings, characters and methods

Remember how I said everything is just a number to the computer some time back? That's true of letters, too. Every letter, written numeral, space, emoji, Chinese character or Egyptian hieroglyph is represented by a number. For example, 'A' is 65 and '猫' is 29483.

In Python, the type for letters, spaces and other things we use for writing is called a character. When we want to use characters in our code, we put them between quotes. For example, to use the character ᙶ in our code, we would write 'ᙶ' (ᙶ is a character from the system used to write many indigenous languages in Canada). 

There's a difference between a character and a number. For example, the number 9 used to do maths is stored as the computer differently from the character '9'. However, Python can convert between the two forms easily. 

You can convert a character to an integer using ord(). You do the opposite with chr():

ord('A')
65
chr(75)
'K'

Strings are a bunch of characters after one another. As you've seen, you write a string by putting it between quotes: 

'I'm a string'
"me too" 

If you want to put another set of quotes inside, you use single or double quotes like this: 

"I'm a 'string'"
'Me "too"' 

You can make strings that go over many lines with """

""" This will go
over many lines """ 

We can add characters to strings or combine strings with +:

'A' + 'B'
'AB' 

 You can even leave the + out: 

"hello" "world"
'hello world'

 If we want to use a add a variable in a string, we use f"":

name="John Smith"
print(f"Hello, {name}!") 
Hello, John Smith! 

Not every character can be written on your keyboard. You can't type in the character that makes the screen flash or the terminal beep, for example. Other characters you put in might confuse the interpreter, like quotes.

There's a special way of writing these (an escape sequence) so you can use them in strings: 

  • \n newline
  • \t tab
  • \' single quote
  • \" double quote
  • \a beeps or makes the terminal flash

You use them like this:

print('hello, world\n')

Strings are an example of something called an object. Objects are data that can "do" things. We tell an object to do something by putting a dot and a method after its name: 

"hello".capitalize()
'HELLO' 

We say we're calling the method. The way we use methods will be familiar. Some of the other things we've used like print() look exactly the same. print() is something called a function. A function in Python is a bit like a method, but it's built into Python and doesn't belong to an object. The stuff you put between the brackets when you call a  is called its arguments

Here are some other methods useful for strings:

  • upper() Put the string in upper case
  • lower() Put the string in lower case
  • rstrip() Remove whitespace like newlines from the end

Lists are another kind of object. They have quite a few methods you can use with them: 

  • reverse() Reverse the order of items in the list
  • sort() Sort the items in a list
  • append() Add an item to the end of a list

See what all of these do by trying them out. 

Not every type of object have methods like these. Integers and floats, for example, don't have methods you can use like capitalize()

Challenge: 

range() can take step sizes that are negative. Use it to write a program that takes a string and reverses it using a for loop. 

Day 21 and 22: Dictionaries and tuples

A list is an an example of something called a collection in Python. Python has other kinds of collections, too. Another collection is called a dictionary. Dictionaries allow you to use what's in them by calling them a name -- a key --instead of having to use an index. You make and use dictionaries like this: 

phonenumbers={'alice':5552321, 'bob':55512393}
print(f"Alice's phone number: {phonenumbers['alice']}")
Alice's phone number: 5552321

Dictionaries have some special methods: 

  • keys()  List all keys in the dictionary
  • values() List all values in the dictionary 

You can find out if something is in a dictionary using the keyword in

if 'alice' is in phonenumbers:
	print(f"Alice's phone number: {phonenumbers['alice']}) 

The other type of collection we'll look at today is called a tuple. Tuples are like lists, but once you make them you can't change what's in them. You use tuples almost the same way as a list, but you use parentheses instead of square brackets when you create them: 

tuple = (1, 3.14, 10)
x = tuple[2] 

Challenge:

Write a little address book program. It should ask the user for names and phone numbers until they choose to quit. Once the address book is full, your program should let the user search for a number from a person's name. If the name isn't in the address book, the program should show an error message. 

Day 23 and 24: Defining methods

It's tiring to write the same thing over and over again. Programs often use the same little bit of code over and over again. By defining our own methods, we can write programs that are built from little pieces that can be reused easily. 

In Python, this is how you'd write the equation y = mx + c from algebra as a method:

def f(m, x, c):
	return m * x + c

The methods we define in this tutorial don't belong to an object, so you use them like a function:

y = f(2, 4, 3)

y will have the  result of 2 * 4 + 3 when the method exits. 

You can also have more than one return statement in a method:

def is_odd(n):
	if n % 2 != 0:
		return True
	else:
		return False

When you use method, you're only working on a copy of the arguments. For example, in the code below m will not change after the method is called:

def g(arg1, arg2):
	arg2 += 1
	return arg1
	
m = 2
g(3, m)

It's also important to remember that anything that the method doesn't return is deleted once the method ends. 

def h():
	var = 3
	return True
var

Traceback (most recent call last):
	File "<stdin>", line 1, in <module>
NameError: name 'var' is not defined. Did you mean: 'vars'?

Challenge:

To convert Celsius to Fahrenheit, you use this equation:

To convert it back, you use this one:

Write a program to convert between Fahrenheit and Celsius. Write a method for each of the equations above.

Day 25 and 26: import and random numbers

Whenever we write programs, we're always basing what we do on other's work. It's impossible for anyone to know everything. 

Python has a large amount of code you can use in your own programs. It comes as modules. You can include modules in your program using import

import random 

This imports the random module. The random module contains code useful for making random numbers; we'll get to it in a bit.

There are other modules that are built into Python. Here are a few of them:

  • math Objects and functions useful for mathematics
  • os Helps you do things with the operating system, like run shell commands
  • sys Contains variables and constants about the Python interpreter. This includes sys.argv[], the list of command-line arguments

You can import multiple modules using a comma:

import math, random, sys

Now we know how to import the random module, we should learn a bit more about how to make it useful.

You call a function from the random module like it's a method:

random.random()
0.168452315232413

You'll see that random.random() only returns floating point numbers smaller than 1. If we want integers instead, the random module gives us random.randint(). The arguments are the highest and lowest number the method can pick:

random.randint(1,50)
45

There are two more functions from the random module that are especially useful for writing games. random.shuffle() shuffles a list:

deck = ['A', 'K', 'Q', 'J']
random.shuffle(deck)
deck
['A', 'K', 'J', 'Q']

random.choice() chooses an item at random from a list:

random.choice(deck)
'J'

See if you can write a program to shuffle a deck of cards and deal a hand. 

Challenge:

Write a program that plays the game 21 against the user. In 21, players take turns adding a small number until the loser is forced to say 21. Use random numbers to choose the computer's move. 

A game might go:

I'll start: 1
You say:	3
I say:		6
You say:	10
I say:		12
You say:	15
I say:		19
You say:	20
I say:		21
You win!
Play again (y/n)?

Day 27 and 28: Exceptions and try/catch 

In programming, things have a tendency to go wrong. Even if your code is perfect, the world isn't. Neither are your users. Errors are inevitable. It's important that your programs can handle problems as they arise. 

Back on the second day, we tried to divide by zero:

You see the ZeroDivisionError? That's Python telling you it threw an exception. Exceptions come in different types for different errors. For example, there are also ones for if you try to use a file that doesn't exist, if you use a method an object doesn't have or if you try to use more memory than is in your computer. 

When you want to deal with an exception that's just been thrown, you catch it. Catching an exception means jumping to a place in our program with code meant to be run if a problem happens. 

When we run code that might cause an exception we want to catch, we put try before it. We put the code we want to run if we catch an exception after except

n = input("Input a number: ")
try: 
 	12 / n
except:
	print("Something went wrong!") 

We can also choose to catch only particular types of exception:

 try:
 	12 / n
 except ZeroDivisionError: 
 	print("you tried to divide by zero!") 
 except: 
 	print("something went wrong, but at least you didn't divide by zero!")

If there's code you want to run if no exceptions were raised, you can use else:

try:
	12 / n
except:
	print("something went wrong")
else:
	print("everything went fine")

If there's code you always want to run after the try block ends, use finally

try:
	12 / n
except:
	print("something went wrong")
else:
	print("everything went fine")
finally:
	print("whew, we're out of the danger zone")

The code under finally will always run, even if you use break or return in the try block. 

Challenges: 

Challenge 1: Try to cause as many different exceptions as you can. What might they mean?

Challenge 2: Write a program that asks the user for 10 numbers to divide. Use try and except to handle errors that might happen. 

Day 29 and 30: Writing files to disk

Congratulations on making it to the last lesson in your first month of Python! I hope you've enjoyed it and look forward to learning more. 

The last thing we're going to look at is how to use files. Most of the programs you use either read or write them. It's obviously important you know how, too! 

To open files, we use the function open()

file = open(filename, 'r') 

open() takes a filename and a mode. The mode tells Python what you want to do with the file. Some of the modes are: 

  • 'r' - read only, in text mode
  • 'w' - write only, in text mode
  • 'r+' - read and write, in text mode 

In text mode, Python translates everything into characters. This might mean things act weird if you open a file that's meant to contain information that isn't text! There is also binary mode, but we won't be covering that in this tutorial. 

If you try to open a file for reading that doesn't exist, Python will throw a FileNotFoundError exception. You can create the file by catching it and then opening and closing the file in write-only mode: 

try:
	file = open(filename, 'r+')
except FileNotFoundError: 
	file = open(filename, 'w') 
	file.close() 
	file = open(filename,'r+') 

To read the contents of a file, you use the method read()

filecontents = file.read() 

read() returns all of what's in the file a one big string. 

You write back data using write():

hello = "Hello, world"
file.write(hello) 

It's up to you to decide how you want to store information in a file. You want to choose a format that will be easy to get back when you open it again. For example, you might have a list of people's names and ages in a list. You could store the list with each person on their own line, putting a tab between the name and age: 

people = [['Alice', 13], ['Bob', 15], ['Eve', 16]]
output = ''
for person in people: 
	current = person[0] + '\t' + str(person[1]) + '\n' 
	output += current

You can get the information back using split(). split() can cut the string into pieces at every whitespace:

output.split()
['Alice', '13', 'Bob', '15', 'Eve', '16']

If you give split() a character as an argument, it will only cut the line when it sees that character:

output.split('\n')
['Alice\t13', 'Bob\t15', 'Eve\t16', '']

Challenge: 

Write a program for keeping a diary. It should ask the user for a date and the day's entry and add it to the end of a file on disk. Use try and catch to handle exceptions gracefully.

Where to next?

If you've been following along this month, you've learnt a lot. You should be proud of what you've achieved. Take a moment to pat yourself on the back!

This is only the beginning. Next month, Libre! will have yet another month of Python for you to sink your teeth into. We'll be learning more about why they call Python an object orientated language and how we can use objects to make very big programs. Keep an eye out!

Previous: How to advocate for your own freedom

Next: Join the FSF40 Hackathon!