Fix the Number Converter
Intermediate · Fix the bug · from Python Try-Except: Handle Errors Without Crashing
From the lesson: Python Try-Except: Handle Errors Without Crashing
Imagine a trapeze artist performing high above the ground. No matter how skilled they are, there's always a safety net below. If they slip, the net catches them and they can climb back up and try again.
Read the lessonThe function below is supposed to convert a list of strings to integers, skipping any values that can't be converted. But it has bugs! Fix the code so it produces the correct output.
Expected output: [1, 2, 3]
def convert_numbers(strings):
numbers = []
for s in strings:
try:
numbers.append(int(s))
except TypeError: # Bug 1: wrong exception type
pass # Bug 2: should print a message
return numbers
result = convert_numbers(["1", "hello", "2", "world", "3"])
print(result)
More Try-Except exercises
- Safe DivisionBeginner
- Predict the OutputBeginner
- Input Validator with raiseIntermediate
- Safe Dictionary LookupAdvanced
- Build a Safe CalculatorAdvanced
All Python exercises · 50 practice problems · Error Handling quiz