Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Debugging Conditional Statements

Author: Sophia
what's covered
In this lesson, you will learn how to debug code and conditional statements in Python. Specifically, this lesson covers:

Table of Contents

hint
If needed, here are some Tips for Accessing Replit in your Sophia course.

1. Debugging Tips

In a previous lesson, we discussed and practiced debugging techniques. We learned that the difference between testing and debugging is that testing identifies if there are bugs or issues, whereas debugging is going through the process of fixing those issues.

Conditional statements can create a number of potential issues with coding that require debugging. With large chained and nested statements, syntax and other errors can happen unexpectedly. One common issue is the use of whitespace errors, such as spaces or tabs. Whitespace errors can be tricky because spaces and tabs are invisible and we're used to ignoring them.

EXAMPLE

For example, look at the following code.


x = 5
 y = 6

When run, this gives us an error.


  File "main.py", line 2
     y = 6
     ^
IndentationError: unexpected indent

In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.

In general, error messages tell you where the problem was discovered, but that is often not where it was caused. The best way to avoid these problems is to use spaces exclusively (no tabs). Tabs and spaces are usually invisible, which makes them hard to debug, so try to find a text editor that manages indentation for you. Most text editors that know about Python do this by default, but some don’t.

did you know

Replit is a perfect example of an IDE and text editor. A text editor is a program that allows you to edit plain text without the added formatting features. Notepad on Windows is a very common text editor. An IDE has other features and functionalities that allow a programmer to interact with the code directly in the program. For example, Replit allows you to create and run code in a number of popular programming languages, including Python. Have you noticed that when you write an if statement in Replit and hit enter to move to the next line, it automatically indents the block line?

try it

Maybe up to this point you have only copied and pasted code into Replit. Let’s take a step back and write some code. We'll need it for the next topic anyway.

Directions: Open Replit and add the following code line by line and notice how Replit’s text editor automatically indents conditional statements.


grade = 85
if grade > 90:
  print("You got an A")
elif grade > 80:
  print("You got a B")
elif grade > 70:
  print("You got a C")
elif grade > 60:
  print("You got a D")
elif grade <= 60:
  print("You got a F")
print("We are done!")

Notice the auto indentations? You can write a lot of code in Replit and other text editors using the return and backspace keys. Pretty nice, huh?


2. Debugging Conditional Statements

To help with debugging conditional statements, we need to know what path the code is taking. That way we will be able to step through the code and see what it is doing. When we run the program you just typed in, we simply get the result at the end of the program once everything has been processed:

EXAMPLE


You got a B 
We are done!

Although we have an idea of what happens, we’re not quite sure if our assumptions are correct or not. In order to help with this, we need to use the Debugger feature in Replit, which is the third item in the left column. If you click on it, the Files and Configuration column (panel) to the right will be changed to the debugger tool.

The Replit Debugger side menu tool.

before you start

One thing to note is that your debugger panel and the debugger tools may not be the same color as the images that follow. The functionality is identical but depending on your Replit theme (dark/light), browser, etc., the colors may be different. Just know that the directions and steps will not be affected.

Also, we used the "Settings" icon to change the Replit layout to "stacked"—that way we can see both the debugging and output on top of one another instead of side by side.

Replit settings with side-by-side layout chosen.

Either layout will work fine.

2a. Adding Breakpoints

We can add interactive breakpoints in the code on the editor screen to allow us to skip or stop at specific points in the code. This will allow us to step through the code one breakpoint at a time.

In order to establish a breakpoint, we click beside a line number. This will then allow us to step through from that point.

try it

Directions: Add a breakpoint on the code you previously entered.

Let’s click to the left of line 2 to add a breakpoint to that conditional statement. We should see a dot appear beside line 2, and see it listed under the Breakpoints.

The Replit Editor screen showing a breakpoint.

2b. Running the Debugger

try it

Directions: Continue the process to run the Replit debugger function.

To start the debugging process, we will click on the Run arrow in the Debugger column. The program will start executing and stop on line 2, because that is where we set our breakpoint.

The Replit editor screen showing the program stopped at the breakpoint.

We should see that line 2 is highlighted in the code editor. There isn’t any output yet, so the console (output sandbox) at the bottom is still empty. In the Debugger column, we will see the variables that are currently declared in the code and the value that they are set to. In this case, we have the variable grade that is set to 85, which was executed and set in line 1. We also see that the Run button has now turned into a Stop button. The program is currently stopped.

Since the program is stopped at the breakpoint at line 2, there are two options:

  1. The Replit debugging Next Step icon. We can click on the Next Step (single arrow) button to move to the next line.
    The Next Step button will allow you to run through the code line by line, stopping at each line.

  2. The Replit debugging Next Breakpoint icon. The other choice is the Next Breakpoint (double arrow) button, which will continue running the program until the next set breakpoint.
    On stopped and highlighted line 2, the conditional statement is checking if the grade is greater than 90. Since it is not, we can see what happens next.
try it

Directions: Click on the single arrow to move to the next step.

The Replit editor screen with debugger stopping on line 4.

Notice now that line 4 is highlighted since that is the next condition to be checked.

Directions: Press the single arrow button again.

The Replit editor screen with debugger stopping on line 5.

We can see now that line 5 is highlighted, as the condition was entered (since 85 is greater than 80).

Directions: Let’s press the single arrow button again.

The Replit editor screen with debugger stopping on line 12.

We now see that the “You got a B” displays in the output on the screen and line 12 is now highlighted. This is because all of the other elif statements are skipped since the condition on line 4 satisfied the overall condition.

Directions: Let’s press the single arrow one more time.

The Replit output screen showing We are done!

The last line “We are done!” is now outputted to the screen and the breakpoint area is reset.

By stepping through the execution of a program using the breakpoints, it allows us to quickly spot what path the code takes.

Now let’s try a situation where we may have multiple breakpoints to help track the path of each condition.

try it

Directions: Enter the following code into Replit.


hungry = input("Are you hungry? Enter y if you are and n if you are not: ")
if hungry == "n":
  print("You are not hungry.")
else:
  healthy = input("Did you want a healthy meal? Enter y if you do and n if you do not: ")
  if healthy == "n":
    print("Getting some junk food.")
  else:
    print("Getting a healthy meal.")
print("All done!")

Directions: Enter the debug function. Let’s place some breakpoints on each condition on lines 2 and 6. That way we can skip over a breakpoint to fast forward to the next breakpoint if needed.

The Replit editor screen with two breakpoints on lines 2 and 6.

Directions: Start the debug tool using the Run button. It should ask us the input question in line 1 and await our input. Enter the first input using a “y” for now.

The Replit editor screen with two breakpoints on lines 2 and 6.

It should now stop on line 2 to await the next step. Perhaps we may have finished testing the first condition. One option is to remove the breakpoint by clicking on the dot beside the line. The other option is to still include that breakpoint but skip over it by clicking on the Next Breakpoint (double arrow) button.

The Replit debugging Next Breakpoint icon.

This will allow you to step over the other breakpoint on line 6 and the commands that would normally be stopped after that point.

Directions: Select the Next Breakpoint button. It will first ask you whether or not you want a healthy meal question. Make sure to answer that.

The Replit output screen showing each of the input questions.

In our demo, we answered “y” to a healthy meal. Therefore, we skipped down to our second breakpoint on line 6. If we were to continue in debug mode:

  • We could watch line by line using the Next Step button. Next Step would drop us down to line 9, since we selected a healthy meal. Selecting Next Step again, we would see the output “Getting a healthy meal.” Finally, one more click, and we would see the output of “All done!” from line 10, and the debugger column would clear and reset.
  • Or, we could have pressed the Next Breakpoint button. Since we did not have another breakpoint set, we would have seen the outputs “Getting a healthy meal.” and “All done!” appear, and the debugger column would clear and reset.

try it

Directions: Using the code we just debugged, or any other code of your choice with conditional statements included, try setting up your own breakpoints and executing the code through the debugger feature. The more you use this feature, the easier it will become.

summary
In this lesson, we learned about some debugging tips that included making sure we watch for common whitespace errors like spaces and tabs. Since they appear invisible to us, they can be tricky to spot. That is why it is always good practice to code with a text editor that is familiar with Python. Replit is perfectly suited for this reason. Next, we used the Replit debugger feature to debug some conditional statements. We learned that using breakpoints and “walking” through the code as it executes is a great way to determine the path the code is following. We will see in future lessons just how helpful the debugger tool is with lengthy code.

Best of luck in your learning!

Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR. CHARLES R. SEVERANCE ACCESS FOR FREE AT www.py4e.com/html3/ LICENSE: CREATIVE COMMONS ATTRIBUTION 3.0 UNPORTED.