DEV Community


Posted on • Updated on


Python Debugging Exercises

[The following is a series of debugging exercises that you may encounter in the real world of development. They are based on problems I have been asked. I thought it would be fun to share them.]

It is your first week at your new job as a software developer. You have your environment set up and you're seated beside a fellow junior who started a few days before you.

He turns to you and asks if you have a minute.

"Hey if you don't mind, please help me find out what's wrong..."

Problem 1


To change display name of Model Instances, we will use def __str__() function in a model. The str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

For example, if we adjust a model in like so

from django.db import models
from django.db.models import Model

class SomeModel(Model):
    name = models.CharField(max_length = 100)

    def __str__(self):
         return f"{}"
Enter fullscreen mode Exit fullscreen mode

When we access SomeModel.objects.all(), the output should be a list of the name fields of this object.


It doesn't work for comments. When a Comment object is printed, it shows [Comment object (1)] rather than what is defined under str.

Let's check the code:

# imports here

class Listing(models.Model):
  max_bid = models.DecimalField(...)

  def __str__(self):
    return ...

class Bid(models.Model):

class User(AbstractUser):

class Comment(models.Model):
  comment = models.TextField()
  listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
  user = models.ForeignKey(User, on_delete=models.CASCADE)

  def _str__(self):
    return f'{}: {self.comment}' 
Enter fullscreen mode Exit fullscreen mode

Where did your fellow teammate go wrong?

Problem 2


Your coworker was secretly interviewing with other companies and was told to find the min value in a list without using min.


The below code doesn't seem to find the minimum element in the list. Why?

def minimum(some_list):
    a = 0
    for x in range(1, len(some_list)):
        if some_list[x] < a:
            a = some_list[x]
    return a
Enter fullscreen mode Exit fullscreen mode

Where did your fellow teammate go wrong?

Top comments (1)

kingorie profile image

Your teammate should change line 2 of the code from "a = 0" to "a = some_list[ 0 ]

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.