We will learn about making our code cleaner and easier to understand, without changing what it does. This is like making a messy room tidy, but everything is still in the room.
We will learn about making our code cleaner and easier to understand, without changing what it does. This is like making a messy room tidy, but everything is still in the room.
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-25
What you will see:
test_no_tax_no_discount
test_with_tax_only
test_with_discount_only
test_with_tax_and_discount
test_zero_quantity
test_full_discount
test_rounding_behavior
These tests will show a red X because your code is not finished yet.
Open the main.py
file. You need to write code that calculates the total price of items, including tax and discounts.
Here's how you can multiply numbers:
result = 5 * 10 # result will be 50
Here's how you can subtract a percentage:
original_price = 100
discount_percent = 20 # 20% off
price_after_discount = original_price * (1 - (discount_percent / 100))
print(price_after_discount) # Shows: 80.0
Here's how you can add a percentage (like tax):
original_price = 100
tax_rate = 0.08 # 8% tax
price_with_tax = original_price * (1 + tax_rate)
print(price_with_tax) # Shows: 108.0
Here's how you can round a number:
import math
my_number = 12.3456
rounded_number = round(my_number, 2) # Round to 2 decimal places
print(rounded_number) # Shows: 12.35
Use these examples to help you calculate the total price.
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-25
test_no_tax_no_discount
test_with_tax_only
test_with_discount_only
test_with_tax_and_discount
test_zero_quantity
test_full_discount
test_rounding_behavior
You have made the code work correctly!
This lesson taught you about making code cleaner without changing what it does. This is called refactoring.
Now, get ready to show your code to your teacher. Be ready to talk about how you made the code cleaner.
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