Python Principles

How to approach a coding exercise

When you're struggling with solving a programming exercise, it helps to take a structured approach.

First determine what to do. You can do this by writing down in plain English what you want your program to do. This description is called pseudocode. Write the description as comments in your code by starting each line with a # symbol.

Once you've got a set of steps written down as pseudocode, write the actual code underneath each comment, one at a time.

An example

To give you an example of using this approach, consider the exercise called "Sum of lengths":

Define a function named length_sum that computes the sum of the lengths of
two strings.

The function length_sum should take two parameters. The two parameters are
strings.

Your function should compute the length of each string, storing these
lengths in variables. Add the lengths together and return the result.

First we rewrite the description into pseudocode:

# define a function named length_sum
# the function should take two parameters
# the two parameters are strings
# your function should compute the length of each string
# store these lengths in variables
# add the lengths together
# return the result

Then we fill in each line:

# define a function named length_sum
# the function should take two parameters
# the two parameters are strings
def length_sum(string1, string2):

# your function should compute the length of each string
# store these lengths in variables
length1 = len(string1)
length2 = len(string2)

# add the lengths together
total = length1 + length2

# return the result
return total

Fix the indentation, remove the comments, and we have a correct solution:

def length_sum(string1, string2):
    length1 = len(string1)
    length2 = len(string2)
    total = length1 + length2
    return total

Optionally you can then simplify the code by getting rid of variable assignments. This makes your solution more concise:

def length_sum(string1, string2):
    return len(string1) + len(string2)

And we're done! You can use this approach for nearly every exercise on this site.