In this part we have given some practice problems for python debugging. Please try them out one by one. Solution link is at the bottom
Problem 1: Syntax Error
- Problem: Identify and fix the syntax error in the following code:
def greet(name)
print("Hello, " + name)
greet("Alice")
Problem 2: Indentation Error
- Problem: Correct the indentation error in the following code:
def print_numbers():
print("1")
print("2")
print("3")
print_numbers()
Problem 3: Logical Error
- Problem: Fix the logical error in the code to calculate the sum of numbers from 1 to 5:
def calculate_sum(n):
result = 0
for i in range(n):
result += i
return result
print(calculate_sum(5))
Problem 4: NameError
- Problem: Fix the
NameError
in the following code:
def print_message():
print(message)
print_message()
Problem 5: Type Error
- Problem: Correct the
TypeError
in the code below:
age = input("Enter your age: ")
if age > 18:
print("You are an adult.")
else:
print("You are not an adult.")
Problem 6: IndexError
- Problem: Fix the
IndexError
in the code that attempts to access an element outside the list’s bounds.
my_list = [1, 2, 3]
print(my_list[3])
Problem 7: ValueError
- Problem: Correct the
ValueError
in the code where the user is prompted to enter an integer, but they enter a non-numeric value.
age = int(input("Enter your age: "))
2 Responses