π§ͺ 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 + 50
Exercise 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. Class2
Exercise 3 β Keyword or identifier?
True, true, while, While, none, None, is, is_not
Which 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 """
pass
Exercise 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 one
Exercise 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.