Python Code Review and Error Correction
Code Snippet 1: Error Correction
Error: Missing colon ':' at the end of for loop.
Corrected Code:
for i in range(5):
print(i)
Explanation: A colon is required at the end of for loops to denote the start of the loop body.
Code Snippet 2: Error Correction
Error: Used '=' instead of '==' in the if statement.
Corrected Code:
if x == 5:
print("x is 5")
Explanation: '=' is an assignment operator. '==' is used for comparison in conditions.
Code Snippet 3: Error Correction
Error: Missing colon ':' at the end of function definition.
Corrected Code:
def add_numbers(a, b):
return a + b
Python Code Review and Error Correction
Explanation: Function definitions require a colon to begin the function block.
Code Snippet 4: Error Correction
Error: Index out of range. Trying to access list[5] in a list of size 5.
Corrected Code:
list = [1, 2, 3, 4, 5]
print(list[4])
Explanation: List indices start at 0. list[4] accesses the last element.
Code Snippet 5: Error Correction
Error: Indentation error for print inside for loop.
Corrected Code:
for i in range(3):
print(i)
Explanation: Python uses indentation to define code blocks. print must be indented.
Code Snippet 6: Error Correction
Error: Cannot add integer to string from input.
Python Code Review and Error Correction
Corrected Code:
x = int(input("Enter a number: "))
print(x + 5)
Explanation: input() returns a string. Convert to int for arithmetic.
Code Snippet 7: Error Correction
Error: print statement inside function not indented.
Corrected Code:
def greet(name):
print("Hello", name)
greet("Alice")
Explanation: Function body must be indented properly.
Code Snippet 8: Error Correction
Error: Missing colon ':' in while loop.
Corrected Code:
while True:
print("Infinite Loop")
Python Code Review and Error Correction
Explanation: while loops need a colon to indicate the loop block.
Code Snippet Task 2: Presentation Summary
1. Introduction and History of Python:
- Created by Guido van Rossum in 1991.
- Known for simplicity and readability.
- Open-source and supports multiple paradigms.
2. Functions & Modules:
- Functions: Reusable code blocks using 'def'.
- Modules: Files containing Python code, imported with 'import'.