Practice: Syntax Errors
Q1. Fix the colon
The code below has a syntax error. Write the corrected version that prints big.
n = 12
if n > 10
print("big")Goal: Fix a missing colon.
Q2. Fix the bracket
The code below has a syntax error because a bracket is not closed. Fix it so it prints 3.
items = [1, 2, 3
print(len(items))Goal: Close brackets.
Q3. Fix the comparison
The code uses = in a condition. Fix it so it prints five.
x = 5
if x = 5:
print("five")Goal: Use == correctly.
Q4. Fix the quote
The text below has a quote problem. Fix it so it prints Don't stop.
print('Don't stop')Goal: Handle quotes.
Q5. Fix the indentation
The code below raises IndentationError. Fix it so it prints 1 and 2.
for i in [1, 2]:
print(i)Goal: Indent blocks.
Q6. Fix the keyword name
The code uses a reserved word as a variable. Rename the variable so it prints 7.
class = 7
print(class)Goal: Avoid keywords.
Q7. Fix the missing comma
The list below is missing a comma. Fix it and print its length.
names = ["Ana" "Raj", "Lee"]
print(len(names))Goal: Check commas.
Q8. Fix the def line
The function header has a syntax error. Fix it so it prints 9.
def square(n)
return n * n
print(square(3))Goal: Fix a def header.
Q9. Detect with compile
Use compile on the text if x > 1 (without a colon) and print caught when SyntaxError is raised.
Goal: Catch syntax errors.
Q10. Valid or not
Write a function is_valid(text) that returns True when text compiles as Python and False otherwise. Print is_valid("1 + 1") and is_valid("1 +").
Goal: Write a checker.
Q11. Report the line
Compile the three line text a = 1, b = 2, c = then print the line number of the SyntaxError.
Goal: Use lineno.
Q12. Count valid snippets
From the list ["x = 1", "y = ", "print(2)", "if True"] count how many snippets compile and print the count.
Goal: Count valid code.
Q13. Class check
Print whether IndentationError is a subclass of SyntaxError, then whether TabError is a subclass of IndentationError, on two lines.
Goal: Know the hierarchy.
Q14. Indentation catch
Compile the text for i in range(2):\nprint(i). Print IndentationError when that exact type is raised.
Goal: Catch IndentationError.
Q15. Valid text
What does this print?
text = "if x"
print(len(text))Goal: Text is not code.
Q16. Subclass test
What does this print?
print(issubclass(SyntaxError, ValueError))Goal: Know the hierarchy.
Q17. Compile result
What does this print?
try:
compile("print('a'", "<s>", "exec")
print("valid")
except SyntaxError:
print("invalid")Goal: Spot unclosed brackets.
Q18. Statement text
What does this print?
code = "x = 3\nprint(x * 2)"
exec(compile(code, "<c>", "exec"))Goal: Use compile and exec.
Q19. Two strings
What does this print?
print("ab" "cd")Goal: Know implicit joins.
Q20. Before or while
What does this print?
print("start")
value = 10 / 2
print(value)Goal: Parse versus run.