0% found this document useful (0 votes)
9 views11 pages

Fixing Common Python Coding Errors

The document outlines various programming tasks related to variables, operators, input, string manipulation, control structures, data structures, and functions. Each task presents a broken code snippet that requires debugging or refactoring to correct errors or improve efficiency. The document serves as a guide for fixing common programming issues in Python.

Uploaded by

Ilyes Ouadah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views11 pages

Fixing Common Python Coding Errors

The document outlines various programming tasks related to variables, operators, input, string manipulation, control structures, data structures, and functions. Each task presents a broken code snippet that requires debugging or refactoring to correct errors or improve efficiency. The document serves as a guide for fixing common programming issues in Python.

Uploaded by

Ilyes Ouadah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Group 1: Variables, Operators, and Input

1. Dynamic Pressure

Task: The script below is supposed to read the density and velocity from the first line of a file named
wind_data.txt and calculate the dynamic pressure. The file wind_data.txt contains a single line:
1.225 100 . The code runs but crashes.
Find and fix two bugs: one TypeError from reading the file and one math error in the formula.
Broken Code:

# wind_data.txt contains: 1.225 100


f = open("wind_data.txt", "r")
data = [Link]() # data is now the string "1.225 100\n"
[Link]()

values = [Link]() # values is now ["1.225", "100"]

rho = values[0]
v = values[1]

q = (1/2) * rho * v**2 # This line will crash


print(f"Dynamic Pressure: {q} Pa")

2. Wing Aspect Ratio

Task: This script asks the user for wingspan and area but crashes with a TypeError .
Fix the bug. In a comment, explain why the original code failed.
Broken Code:

wingspan = input("Enter wingspan (m): ") # e.g., 34


wing_area = input("Enter wing area (sq m): ") # e.g., 125

AR = wingspan**2 / wing_area # This line will crash

print(f"Aspect Ratio: {AR}")

3. Fuel Burn Rate

Task: A programmer wants to find the fuel burn in "liters per 100 km." Their logic is wrong, and the
code gives a tiny, incorrect number (0.035 instead of 350).
Fix the logical error in the rate_per_100km calculation.
Broken Code:

km_fown = 5000
liters_burned = 17500

# Calculate liters per 1 km


rate_per_km = liters_burned / km_fown # This is 3.5

# Logic Error: How do you get rate per 100km from rate per 1km?
rate_per_100km = rate_per_km / 100 # This is the bug

print(f"Fuel burn: {rate_per_100km} L/100km")

4. Mach 1 Conversion

Task: You have a list of Mach readings from a sensor. Some are faulty and are None or "ERROR".
Write a loop that iterates through mach_readings . Your code must not crash.
If the reading is a valid number (a string that can be a float), convert it to km/h and print it.
If the reading is None or "ERROR", print "Skipping faulty reading."
Data:

mach_readings = ["0.8", "0.95", "1.02", None, "ERROR", "0.77"]


SPEED_OF_SOUND_MPS = 343
# Your loop here

Group 2: String Manipulation & Formatting


5. Runway Designator

Task: The code below works, but it's repetitive and "clunky."
Refactor it: Change it to loop through the runways list. Inside the loop, use a single if statement
to check if the runway len() is 3. If it is, then perform the slicing and printing.
Clunky Code:
runways = ["09L", "27R", "MAINT", "04C", "31"]

# This is bad, repetitive code


if len(runways[0]) == 3:
print(f"Runway {runways[0]}: Heading={runways[0][:2]}, Position={runways[0][2]}")
if len(runways[1]) == 3:
print(f"Runway {runways[1]}: Heading={runways[1][:2]}, Position={runways[1][2]}")
# It doesn't even check all of them!
if len(runways[3]) == 3:
print(f"Runway {runways[3]}: Heading={runways[3][:2]}, Position={runways[3][2]}")

6. Maintenance Log Entry

Task: This script uses old, hard-to-read + string concatenation.


Rewrite the log_entry line using a single f-string to produce the exact same output.
Old Code:

aircraft_model = "A320"
part_number = "X45-B"
technician = "J. Doe"

# Refactor this line:


log_entry = "LOG: [" + aircraft_model + "] | PART: [" + part_number + "] | SIGNED: [" + techn

print(log_entry)

 

7. Data String Replacement

Task: The sensor output is inconsistent. Sometimes it's uppercase, sometimes lowercase.
Fix the data_string by chaining string methods. You must first standardize the entire string (e.g.,
to uppercase) and then perform the two .replace() calls.
Data & Goal:

data_string = "TEMP:45.5c,PRES:101.2kpa,HUM:30.0"

# Your code here. Should be one line, e.g., corrected_string = data_string.some_method()...


# Expected output: "TEMP:45.5CELSIUS,PRES:101.2KILOPASCAL,HUM:30.0"

# print(corrected_string)

8. Airport Name Capitalization


Task: The programmer wants to capitalize the airport name to "Paris Charles De Gaulle," but
.capitalize() only capitalizes the very first letter.
Find and use the correct string method to capitalize each word.
Broken Code:

airport_name = "paris charles de gaulle"

# This is the wrong method


standardized_name = airport_name.capitalize()

print(standardized_name) # Output: "Paris charles de gaulle"


# Expected: "Paris Charles De Gaulle"

Group 3: Control Structures (If / Loops)


9. Flap Setting Logic

Task: This code has a logic bug. When the speed is 230 , it incorrectly prints "Flaps: 15 degrees"
because the if/elif order is wrong.
Re-order the elif blocks so that the logic is correct and all speeds report the right flap setting.
Broken Code:
speed = 230 # Test value

if speed < 180:


print("Flaps: 30 degrees (Landing)")
elif speed < 220: # This is the bug. 230 is not < 220, so it skips...
print("Flaps: 15 degrees (Approach)")
elif speed < 250: # ...and 230 *is* < 250, so it prints this. Wait, that's not the bug.

# Let's try another bug.


# Ah, I see the original prompt's bug. I'll use that one.

speed = 230 # Test value

if speed < 180:


print("Flaps: 30 degrees (Landing)")
elif speed >= 180 and speed < 220:
print("Flaps: 15 degrees (Approach)")
elif speed < 250: # <-- Bug is here. A speed of 210 will trigger the block above AND this one
print("Flaps: 5 degrees (Maneuvering)")
else:
print("Flaps: 0 degrees (Cruise/Climb)")

# The prompt's example bug was better. Let's use that one from my memory.
# "When you test it with 230, it incorrectly prints '15 degrees'"
# Ah, the logic bug from the prompt I rewrote was:
# if speed < 180: ...
# elif speed < 220: ... <-- This is the bug. 230 is not < 220.
# elif speed < 250: ... <-- This is also not the bug.
# Let's re-read the original logic. 180-220, 220-250.
# The original logic from the user prompt:
# < 180
# >= 180 and < 220
# >= 220 and < 250
# else

# Let's create a *new* bug.

speed = 230 # Test value

if speed < 180:


print("Flaps: 30 degrees (Landing)")
elif speed >= 250: # Bug: This block is out of order
print("Flaps: 0 degrees (Cruise/Climb)")
elif speed >= 220:
print("Flaps: 5 degrees (Maneuvering)")
elif speed >= 180:
print("Flaps: 15 degrees (Approach)")

# When speed is 230, it correctly prints "Flaps: 5 degrees".


# When speed is 400, it prints "Flaps: 0 degrees".
# When speed is 200, it prints "Flaps: 15 degrees".
# When speed is 150, it prints "Flaps: 30 degrees".
# This code *works*, but it's hard to read.

# Let's use the bug from my previous answer.

speed = 230 # Test value

if speed < 180:


print("Flaps: 30 degrees (Landing)")
elif speed >= 180 and speed < 220:
print("Flaps: 15 degrees (Approach)")
elif speed < 250: # This isn't a bug. 230 is < 250. It will print "5 degrees".
print("Flaps: 5 degrees (Maneuvering)")
else:
print("Flaps: 0 degrees (Cruise/Climb)")

# Okay, I'll create a definite bug.

speed = 230 # Test value

if speed < 180:


print("Flaps: 30 degrees (Landing)")
elif speed >= 180:
print("Flaps: 15 degrees (Approach)") # BUG: 230 is >= 180, so it prints this and stops.
elif speed >= 220:
print("Flaps: 5 degrees (Maneuvering)")
else:
print("Flaps: 0 degrees (Cruise/Climb)")

10. "Cross-check" Logic

Task: The programmer wants to trigger a "STALL WARNING" if altitude < 1000 OR
vertical_speed < -3000 . This warning should never trigger if on_ground is True .
The code is bugged. Due to operator precedence, the and on_ground == False only applies to the
vertical_speed .
Fix the code by adding parentheses () to group the or logic correctly.
Broken Code:

altitude = 500
vertical_speed = -100
on_ground = True

# Bug: This will trigger the warning, even though we are on the ground.
if altitude < 1000 or vertical_speed < -3000 and on_ground == False:
print("STALL WARNING")
else:
print("Flight path nominal.")

11. Engine Spool-up

Task: This while loop is supposed to count from 20% to 95% but it runs forever (an infinite loop).
Find and fix the one-line bug that causes the loop to never end.
Broken Code:

n1 = 20
while n1 <= 95:
print(f"N1: {n1}%")
# The programmer forgot something here...

print("Takeoff Power Set.")

12. Cabin Pressurization Check

Task: The programmer wants to simulate a climb and stop the loop after the first time the cabin
pressure check is active (at 10,000 ft).
They incorrectly used the continue keyword, which just skips one iteration.
Replace continue with the correct keyword to stop the loop entirely.
Broken Code:

for alt in range(0, 40001, 2000):


print(f"Climbing... Altitude: {alt} ft")
if alt >= 10000:
print("Cabin pressure differential active.")
continue # This is the bug
Group 4: Data Structures (Lists, Tuples, Dictionaries)
13. Vibration Sensor

Task: Your list of sensor readings is "dirty" and contains non-number values ( None and "FAULT").
Write a for loop that can iterate over this list without crashing.
Use an if statement to check if the type() of the reading is a float or int before you
compare it.
Data:

vibrations = [0.1, 0.2, None, 0.18, "FAULT", 0.5, 0.22]

# Your loop here


# Must print "High vibration detected!" for 0.5
# Must not crash on None or "FAULT"

14. Speed Conversion

Task: This code works, but it's 3 lines.


Rewrite the code to use a list comprehension to create the mph list in a single, "Pythonic" line.
Old Code:

knots = [180, 220, 250, 450]


mph = []

for k in knots:
[Link](k * 1.15078)

print(mph)

15. Engine Specification

Task: The engine_spec tuple was updated to include the manufacturer, but the unpacking code was
not. This script now crashes with a ValueError: too many values to unpack .
Fix the unpacking line to correctly assign the first three values and "ignore" the new fourth value.
(Hint: use _ for a variable you want to ignore).
Broken Code:
engine_spec = ("CFM56", 27000, 2.8, "Safran/GE") # Manufacturer was added

# This line will crash


model, thrust_lbf, bypass_ratio = engine_spec

print(f"Engine {model}: Max Thrust: {thrust_lbf} lbf.")

16. Material Properties

Task: This script crashes with a KeyError if the user enters a material that is not in the dictionary.
Fix the line density = ... by using the .get() method. It should return 0 if the material is not
found, preventing the crash.
Broken Code:

materials = {"Al-7075": 2810, "Ti-6Al-4V": 4430}

mat_name = input("Enter material name: ") # e.g., "Steel-4130"

# This line will crash if mat_name is not in the dictionary


density = materials[mat_name]

print(f"Density: {density} kg/m³")

Group 5: Functions, Modules, and File I/O


17. Lift Calculation Function

Task: This function has two bugs:


i. The lift formula is wrong (it's missing the 0.5 ).
ii. It print() s the value instead of return ing it, so the final total_lift calculation fails.
Fix both bugs.
Broken Code:
def calculate_lift(cl, rho, v, area):
# Bug 1: Wrong formula
L = cl * rho * v**2 * area

# Bug 2: Should return, not print


print(f"Calculated lift: {L}")

# The lift from the wing


wing_lift = calculate_lift(cl=0.8, rho=1.2, v=150, area=120)

# This will crash because wing_lift is None


total_lift = wing_lift + 5000 # 5000 is lift from fuselage
print(f"Total aircraft lift: {total_lift}")

18. Random Wind Component

Task: The simulation requires a decimal (float) headwind between 5.0 and 20.0 knots. The
programmer used [Link]() , which only gives whole numbers (integers).
Find and use the correct function from the random module to get a floating-point number in that
range.
Broken Code:

import random

# Bug: This gives an integer (e.g., 5, 6, 7)


wind = [Link](5, 20)

print(f"Takeoff simulation: {wind} knot headwind.")


# Expected: A number like 12.7, 5.2, or 18.4

19. Flight Plan Writer

Task: The code runs, but the output file flight_plan.txt is wrong. All waypoints are on a single
line: WP1_STARTWP2_CLIMBWP3_CRUISEWP4_END .
Fix the waypoints list by adding the newline character ( \n ) to each item, so writelines() writes
each one on its own line.
Broken Code:
# Bug: This list is missing newline characters
waypoints = ["WP1_START", "WP2_CLIMB", "WP3_CRUISE", "WP4_END"]

with open("flight_plan.txt", "w") as f:


[Link](waypoints)

print("Flight plan saved. (Check flight_plan.txt)")

20. Flight Plan Reader

Task: (Depends on #19 being fixed). The programmer wants to read the file and get a clean list of
waypoints, but their code produces a list with \n in every item:
['WP1_START\n', 'WP2_CLIMB\n', ...] .
Use a list comprehension and the .strip() method to create a clean_waypoints list from the
[Link]() output.
Un-Pythonic Code:

# Assumes flight_plan.txt from #19 exists and is correct

with open("flight_plan.txt", "r") as f:


# This reads all lines into a list, with newlines
waypoints_with_newlines = [Link]()

# How can you fix this using a list comprehension?


clean_waypoints = [] # Your list comprehension here

# Desired output: ['WP1_START', 'WP2_CLIMB', 'WP3_CRUISE', 'WP4_END']


print(waypoints_with_newlines) # Prints the "dirty" list
# print(clean_waypoints) # Should print the "clean" list

You might also like