๐งช Practice: Spot the Tokens
Module 2 gave you the atoms: keywords, identifiers, literals, operators, delimiters โ plus comments, docstrings, and the indentation rule. Time to prove it. Attempt everything before peeking at the solutions.
Exercise 1 โ Token autopsy
List every token in this line, and name each one's family:
total = price + 50Exercise 2 โ Legal or illegal?
Mark each identifier as legal or illegal. If illegal, say why:
1. my_score
2. 2nd_player
3. for
4. For
5. user-name
6. _temp
7. class
8. Class2Exercise 3 โ Keyword or identifier?
True, true, while, While, none, None, is, is_notWhich are keywords?
Exercise 4 โ Comment or docstring?
Which of these does Python store for help() to display?
# A: keeps the app alive
""" B: Keeps the app alive """
def keep_alive():
# C: keeps the app alive
""" D: Keeps the app alive """
passExercise 5 โ The indentation detective
This code has three indentation problems. Find and fix them:
score = 75
if score >= 50:
print("Passed!")
print("Well done")
else:
print("Failed")Exercise 6 โ Predict the output
*Before* running, write down what this prints:
# count = 10
count = 5
print(count)Solutions
Exercise 1: total (identifier) = (operator) price (identifier) + (operator) 50 (literal).
Exercise 2:
my_score โ
2nd_player โ starts with a digitfor โ keywordFor โ
โ case-sensitive, For โ foruser-name โ hyphen reads as minus_temp โ
underscore is legal (and means "internal use" by convention)class โ keywordClass2 โ
โ contains the keyword but isn't oneExercise 3: True, while, None, is are keywords. true, While, none, is_not are identifiers โ keywords are case-sensitive.
Exercise 4: Only D โ a docstring placed first inside the function is stored and shown by help(). A is a comment, B is a floating string at module level (stored as __doc__ of the module, but the classic answer: D is the function's docstring), C is a comment.
Exercise 5:
score = 75
if score >= 50:
print("Passed!")
print("Well done")
else:
print("Failed")Problems were: (1) print("Passed!") needed indenting under the if, (2) print("Well done") was indented 2 spaces โ must match the block's 4, (3) print("Failed") needed indenting under the else.
Exercise 6: It prints 5. The first line is a comment โ Python never saw it. Comments are for humans; only real code runs.
โ Checkpoint
Six exercises done from your own keyboard? Module 2 complete. You now speak Python's *alphabet*: tokens, names, comments, and indentation.
Next module: Variables & Data Types โ where your programs finally start remembering things.