We will learn how to use a special tool called a 'debugger' or 'code inspector'. This tool helps us look at our code step by step to see what it is doing. We will learn how to pause our code and move through it one line at a time.
We will learn how to use a special tool called a 'debugger' or 'code inspector'. This tool helps us look at our code step by step to see what it is doing. We will learn how to pause our code and move through it one line at a time.
Let's check if your program is working. We do this by running a special test. Open your terminal and type this command:
pytest module-1.2/blueprint-PY-1.2-BP6/quest-15
What you will see:
test_debug_me_function_calls
This test will show a red X because your code is not finished yet.
Open the main.py
file. You need to add commands to the debug_me
function to draw a square. The sides of the square should be 100 steps long. After drawing, the function should say 'Square drawing commands issued.'.
Here's how you can make a turtle draw a square:
import turtle
my_turtle = turtle.Turtle()
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.left(90)
Use this example to help you draw the square.
Now that you've written your code, let's check it again. Type this command in your terminal:
pytest module-1.2/blueprint-PY-1.2-BP6/quest-15
test_debug_me_function_calls
You have made the code work correctly!
Now, get ready to show your code to your teacher. Be ready to talk about how you used the code inspector to understand what the code was doing.
This document provides a quick reference for key concepts and techniques covered in this blueprint, focusing on finding and fixing errors (debugging) and improving code structure (refactoring).
A bug is an error in a computer program that causes it to produce an incorrect or unexpected result, or to behave in an unintended way. Bugs are a normal part of the software development process.
Debugging is the process of finding and resolving defects or problems within a computer program.
Debugging involves investigating your code to understand why it isn't behaving as expected.
Using print()
statements is a fundamental technique to inspect the state of your program and understand its execution flow.
print()
calls with descriptive messages and variable values where you suspect an issue might be occurring.# Example: Checking a variable's value inside a loop
count = 0
while count < 5:
print(f"Current count: {count}") # Check the value of count
# ... other code ...
count += 1
print("Loop finished.") # Confirm the loop completed
Your code editor (like VS Code) has powerful, built-in tools for debugging.
Refactoring is the process of restructuring existing computer code without changing its external behavior. The goal is to improve nonfunctional attributes of the software, such as readability, maintainability, and simplicity.
Refactoring is like simplifying an algebraic expression; the value is the same, but the form is cleaner and easier to work with.
If a block of code performs a single, well-defined task, move it into its own function.
# Before Refactoring (example)
# ... inside a loop ...
# Calculate area
width = 10
height = 20
area = width * height
print(f"Area: {area}")
# ... rest of loop ...
# After Refactoring (example)
def calculate_area(width, height):
"""Calculates the area of a rectangle."""
area = width * height
return area
# ... inside the loop ...
width = 10
height = 20
area = calculate_area(width, height) # Call the new function
print(f"Area: {area}")
# ... rest of loop ...
Write code that is easy for others (and your future self) to understand.
total_price
instead of tp
).# Less readable (example)
# Calculate final price with tax
p = 100
t = p + (p * 0.08)
final = round(t, 2)
# More readable (example)
# Calculate final price with tax
subtotal = 100
tax_rate = 0.08
tax_amount = subtotal * tax_rate
total_price = subtotal + tax_amount
final_price_rounded = round(total_price, 2)
In Pygame, the event loop processes user input and system events.
event.type
attribute to identify the type of event (e.g., pygame.QUIT
, pygame.KEYDOWN
, pygame.MOUSEBUTTONDOWN
).pygame.KEYDOWN
, pygame.KEYUP
), use event.key
to identify which key was pressed (e.g., pygame.K_r
).pygame.MOUSEBUTTONDOWN
, pygame.MOUSEBUTTONUP
), use event.pos
to get the mouse coordinates.# Example Pygame event loop structure
import pygame
# ... setup ...
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
# Check event.key here
pass
if event.type == pygame.MOUSEBUTTONDOWN:
# Access event.pos here
pass
# ... drawing and update ...
In graphics programming, the order in which you draw is crucial. Objects drawn later appear on top of objects drawn earlier.
pygame.display.flip()
or pygame.display.update()
) to show the completed frame.# Example Pygame drawing order
# ... inside the game loop ...
# 1. Draw background
screen.fill(BACKGROUND_COLOR)
# 2. Draw game elements
pygame.draw.rect(screen, PLAYER_COLOR, player_rect)
# ... draw other objects ...
# 3. Update display
pygame.display.flip()
# ...
Variables defined outside of any function are called global variables. To modify a global variable from inside a function, you must use the global
keyword.
global
keyword.global
keyword inside the function.# Example using global
counter = 0 # Global variable
def increment_counter():
global counter # Declare intent to modify the global 'counter'
counter += 1
def read_counter():
# No 'global' needed to just read the value
print(f"Current counter value: {counter}")
# ...
increment_counter()
read_counter() # Output: Current counter value: 1
Adding sound effects can make an application more engaging.
import pygame
pygame.mixer.init()
pygame.mixer.Sound
object.
# Assumes 'sound.wav' is in the same directory
sound_effect = pygame.mixer.Sound("sound.wav")
.play()
method on the sound object when the corresponding action occurs.
# Example inside a function triggered by an event
def on_action():
# ... perform action ...
sound_effect.play() # Play the sound