Learn to Code by Solving Problems: A Python Programming Primer Homepage for the book Learn to Code by Solving Problems: A Python Programming Primer

Can You Find the Bug?

Hello, Python people,

It may be clear to you already that writing code is crucial in the process of learning to program. But there are other important skills that may be less obvious but that we need to practice as well.

For example: reading code written by others. You never know what you’ll learn by reading through other people’s code. You might learn a new bit of Python, or a technique for solving a problem, or a new approach to a problem you’ve already solved. This is why I recommend in the book to look at other code submissions and compare them to yours.

Another important skill: debugging! Finding bugs in code! Many programmers have a negative reaction to bugs… they just want them fixed. And don’t we all :) but there are learning opportunities here. When you finally fix that elusive bug and finish your celebration, take a few minutes to reflect on the process:

Finding and Fixing a Bug

I’ve included many suggested practice exercises in the book. I thought it would be fun here to provide you some code that doesn’t quite solve one of these exercises. It has a bug. Can you find it?

The exercise that we’re working through here is from Chapter 8… this Utrka problem about marathons.

Here’s the code that doesn’t quite work.

n = int(input())

d = {}

for i in range(2 * n - 1):
    person = input()
    if not person in d:
        d[person] = 1
    else:
        d[person] = d[person] + 1

for person in d:
    if d[person] == 1:
        print(person)

What Do You Think?

Did you have fun with this exercise? Want me to highlight your most devious bugs? :D Please get in touch!