Skip to main content

Keywords and Capstone: Building a Type-Safe Calculator

You've mastered four types of operators. Now it's time to learn one more important concept about Python's language structure: keywords. Keywords are reserved words that Python has claimed for itself. You can't use them as variable names because Python needs them for language features.

Then we'll bring everything together in a capstone project: a calculator that demonstrates all four operator types, combined with keyword awareness and type validation.

What It Is: Python's Reserved Words

A keyword is a word that Python uses for language syntax. These words have special meaning and control how Python works. Because Python needs them for specific purposes, you can't use them as variable names.

Python has 35 keywords (as of Python 3.14). You don't need to memorize them—you need to recognize common ones and know how to check if a word is reserved.

Discovering Python Keywords

Python provides a simple way to see all keywords:

# Import the keyword module
import keyword

# See all Python keywords
print("Python keywords:")
print(keyword.kwlist)

# Output (abbreviated):
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
# 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
# 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
# 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
# 'while', 'with', 'yield']

# Count them
print(f"Total keywords: {len(keyword.kwlist)}") # 35

# Check if a specific word is a keyword
print(keyword.iskeyword("for")) # True (reserved)
print(keyword.iskeyword("forloop")) # False (not reserved)
print(keyword.iskeyword("count")) # False (not reserved)

These 35 keywords are Python's grammar. They define language structure: loops (for, while), conditionals (if, else), functions (def), classes (class), and more.

💬 AI Colearning Prompt

"Why can't I use keywords as variable names? What would happen to Python's design if if, for, or def weren't reserved? Explain the problem and why reservation is necessary."

This question helps you understand language design—why certain words must be protected.

Why Keywords Are Reserved

Let's see what happens when you try to use a keyword as a variable name:

# WRONG: Trying to use 'for' as a variable
# for = 5 # SyntaxError: invalid syntax (for is reserved!)

# RIGHT: Use a descriptive alternative
for_loop_count: int = 5 # Underscore makes it clear
loop_count: int = 5 # Descriptive name
iterations: int = 5 # Alternative name

# Common keywords and what they do
# if, elif, else — conditional logic (Chapter 17)
# for, while — loops (Chapter 17)
# def — define functions (Chapter 20)
# class — define classes (Chapter 24)
# import, from — import modules (Chapter 20)
# return — return from function (Chapter 20)
# try, except, finally — error handling (Chapter 21)
# True, False, None — special values (Chapter 14)
# and, or, not — logical operators (Lesson 3, this chapter!)

The reason for, if, def are reserved is that Python needs them for language structure. If you could write for = 5, Python would get confused: "Is this the start of a for loop, or is this assigning 5 to the variable for?"

🎓 Instructor Commentary

In AI-native development, you don't memorize all 35 keywords. You develop a reflex: "If I get a SyntaxError when naming a variable, it might be a keyword. Let me check with keyword.iskeyword()." This defensive habit will save you debugging time.

Checking if a Word is Reserved

A smart programming practice is to check before using a word as a variable name:

import keyword

# Function to check if a name is valid (simplified)
def is_valid_name(word: str) -> bool:
"""Check if a word is not a keyword"""
return not keyword.iskeyword(word)

# Test it
potential_names: list[str] = ["count", "for", "result", "while", "data"]

for name in potential_names:
if keyword.iskeyword(name):
print(f" '{name}' is RESERVED - use '{name}_var' instead")
else:
print(f" '{name}' is OK - can use as variable name")

# Output:
# count is OK
# for is RESERVED - use for_var instead
# result is OK
# while is RESERVED - use while_var instead
# data is OK

This pattern—checking before using—is good defensive programming.

🚀 CoLearning Challenge

Ask your AI Co-Teacher:

"Create a program that:

  1. Lists all 35 Python keywords
  2. Groups them by category (control flow, function definition, special values, etc.)
  3. Explains what each category does

Then explain: Why do you think keywords are organized this way? What would happen if Python had no keywords?"

Expected Outcome: You'll see that keywords follow logical categories; understand that language design requires structure; appreciate why Python protects certain words.

Capstone Project: Calculator with Type Safety

Now let's bring everything together. You'll create a calculator that demonstrates:

  • Arithmetic operators (Lesson 1): +, -, *, /, //, %
  • Comparison operators (Lesson 2): ==, !=, >, <, >=, <=
  • Logical operators (Lesson 3): and, or, not
  • Assignment operators (Lesson 4): =, +=, -=, *=, /=
  • Type validation: Using type() to verify results
  • Keyword awareness: Recognizing reserved words

Simplified Calculator (Beginner-Friendly Version)

If you haven't learned functions yet, here's a straightforward version:

# Capstone Project: Simple Calculator with Type Safety
# Demonstrates all 4 operator types + type validation + keyword awareness

import keyword

print("=" * 50)
print("SIMPLE CALCULATOR WITH TYPE SAFETY")
print("=" * 50)

# Input two numbers
num1: float = float(input("\nEnter first number: "))
num2: float = float(input("Enter second number: "))

# Arithmetic operators (Lesson 1)
print("\n--- ARITHMETIC OPERATORS ---")
add_result: float = num1 + num2
print(f"{num1} + {num2} = {add_result} (type: {type(add_result).__name__})")

sub_result: float = num1 - num2
print(f"{num1} - {num2} = {sub_result} (type: {type(sub_result).__name__})")

mul_result: float = num1 * num2
print(f"{num1} * {num2} = {mul_result} (type: {type(mul_result).__name__})")

# Comparison operators (Lesson 2)
print("\n--- COMPARISON OPERATORS ---")
is_equal: bool = num1 == num2
print(f"{num1} == {num2}: {is_equal} (type: {type(is_equal).__name__})")

is_greater: bool = num1 > num2
print(f"{num1} > {num2}: {is_greater} (type: {type(is_greater).__name__})")

is_less: bool = num1 < num2
print(f"{num1} < {num2}: {is_less} (type: {type(is_less).__name__})")

# Logical operators (Lesson 3)
print("\n--- LOGICAL OPERATORS ---")
both_positive: bool = (num1 > 0) and (num2 > 0)
print(f"Both positive: {both_positive} (type: {type(both_positive).__name__})")

either_large: bool = (num1 > 10) or (num2 > 10)
print(f"Either > 10: {either_large} (type: {type(either_large).__name__})")

not_equal_result: bool = not (num1 == num2)
print(f"Not equal: {not_equal_result} (type: {type(not_equal_result).__name__})")

# Assignment operators (Lesson 4)
print("\n--- ASSIGNMENT OPERATORS ---")
total: float = 0.0
total += add_result
print(f"After adding result: total = {total}")

total -= 5.0
print(f"After subtracting 5: total = {total}")

total *= 0.5
print(f"After halving: total = {total} (type: {type(total).__name__})")

# Keyword awareness
print("\n--- KEYWORD AWARENESS ---")
test_words: list[str] = ["count", "for", "result", "if", "my_var"]
print("Checking variable names:")
for word in test_words:
if keyword.iskeyword(word):
print(f" '{word}' is RESERVED - don't use as variable name")
else:
print(f" '{word}' is OK - can use as variable name")

# Division with safety check
print("\n--- SAFE DIVISION ---")
if num2 != 0:
div_result: float = num1 / num2
print(f"{num1} / {num2} = {div_result} (type: {type(div_result).__name__})")
else:
print("Cannot divide by zero")

print("\n" + "=" * 50)
print("Calculation complete!")
print("=" * 50)

✨ Teaching Tip

Use your AI tool to extend the calculator: "Add more features to the calculator: modulus (%), floor division (//), exponentiation (**). Show the results for num1=10, num2=3."

That's the complete calculator! You've now integrated all four operator types (arithmetic, comparison, logical, assignment) plus keyword awareness and type validation—all using only the Python concepts you've learned so far (Chapters 13-15).

What about functions? You might wonder why the calculator code is all in one block instead of organized into functions. That's intentional! Functions are taught in Chapter 20. For now, focus on understanding how operators work together. When you reach Chapter 20, you can come back and refactor this calculator using functions as practice.


Try With AI

Now it's your turn to explore keywords and integrate all your operator knowledge with an AI co-teacher.

Tool Choice: Use Claude Code, Gemini CLI, or ChatGPT web—whatever you have access to.

Prompt 1: Concept Exploration (Understand)

Copy and ask your AI:

"I just learned about Python keywords. I ran:

import keyword
print(keyword.kwlist)
  • What are Python keywords and why does Python have them?
  • Why can't I use 'if' or 'for' as variable names?
  • Can I use 'For' or 'IF' (different capitalization)?
  • Show me what error I get if I try to use 'def' as a variable name."

Expected Outcome: You'll understand keywords are reserved syntax elements; learn Python is case-sensitive (For is valid, for is not); see SyntaxError demonstration; grasp language design constraints.


Prompt 2: Application (Apply)

Copy and ask your AI:

"Write a simple calculator that:

  1. Gets two numbers from the user
  2. Adds them (arithmetic operator)
  3. Checks if first > second (comparison operator)
  4. Combines conditions: (num1 > 0) and (num2 > 0) (logical operators)
  5. Updates a total using += (assignment operator)
  6. Uses type() to verify result types

You can skip function definitions - just write straightforward code. Show me the complete calculator."

Expected Outcome: You'll implement capstone project (or simplified version); apply all operator types; practice type validation; create working, testable code.


Prompt 3: Edge Case Discovery (Explore)

Copy and ask your AI:

"Test your calculator with different inputs:

  • Two positive numbers (10, 5)
  • Two negative numbers (-10, -5)
  • Zero and a positive (0, 5)
  • Very large numbers (1000000, 2000000)

Which inputs work well? Are there edge cases that break the calculator? How would you fix them? Show me the problematic outputs."

Expected Outcome: You'll test edge cases (negative numbers, zero, large numbers); discover any type safety issues; learn defensive programming; ask AI about error handling for robustness.


Prompt 4: Synthesis & Validation (Understand + Analyze)

Copy and ask your AI:

"I've now learned 4 different operator types:

  • Arithmetic (Lesson 1): do math
  • Comparison (Lesson 2): ask True/False
  • Logical (Lesson 3): combine conditions
  • Assignment (Lesson 4): update variables

How do these fit together in a complete program?

  • In the calculator, where does each operator type appear?
  • Why do I need all 4 types?
  • How does this prepare me for Chapter 17 (Control Flow with if/while/for)?
  • What would Chapter 17 look like using these operators?

Draw a connection map showing how the 4 operator types work together."

Expected Outcome: You'll synthesize understanding: arithmetic operators perform calculations; assignment operators store results; comparison operators enable validation logic; logical operators would combine conditions in Chapter 17; see how all 4 types work together in real code; understand chapter progression toward control flow.


Safety Note: As you test the calculator, you might encounter ZeroDivisionError or TypeError. These are learning opportunities, not failures. Ask your AI: "What does this error mean and how do I prevent it?" Error handling will be taught in Chapter 21, but understanding errors now prepares you for that chapter.


Chapter 15 Complete

Congratulations! You've mastered all four operator types: arithmetic, comparison, logical, and assignment. You understand how to combine them, validate types, and recognize Python's language boundaries (keywords).

What's Next (Chapter 16): Strings and text manipulation—you'll see that operators work with strings too (concatenation with +, repetition with *).

Looking Ahead (Chapter 17): Control flow and loops—you'll use comparison and logical operators in if statements and loops, applying everything you learned here to make decisions and repeat code.

Your foundation is solid. Keep this chapter's concepts close as you move forward.