Before writing complex applications, it is essential to understand precisely what Python is and how it functions. Many beginners conflate the language itself with the interpreter that runs it, but distinguishing between the set of grammatical rules and the program that executes them is the first step toward mastery. This guide demystifies these core concepts and introduces the fundamental building blocks every new programmer needs on day one. From navigating the REPL and understanding the difference between comments and docstrings to mastering variables and the seven essential data types, this overview provides the mental models and practical knowledge required to read, write, and debug Python code with confidence.
1.1 What Python actually is
Python is a language, but "language" is a slippery word. Let's be precise.
Python (the language) is a set of rules for writing text that describes what you want a computer to do. The rules say things like: if must be followed by an indented block, strings can be wrapped in " or ', indentation matters, etc.
Python (the interpreter) is a program someone else wrote that reads your text and does what it says. On Linux and macOS it's usually called python3. On Windows it's usually python or py. When you type python3 shopping_list.py, you are asking the interpreter to read the file and do the things it says.
Analogy
Think of the language as English grammar and the interpreter as a very literal-minded assistant who reads your letter one line at a time and does exactly what each line says. If you misspell a word, the assistant stops and asks "what does this mean?" — that's a syntax error.
What happens when you run python3 shopping_list.py
![427]()
You will occasionally see files named __pycache__/something.cpython-311.pyc appear next to your script. Those are cached bytecode files. You can delete them safely — Python will just recreate them. They exist so that re-running the same script is faster.
The REPL (Read-Eval-Print Loop)
If you type just python3 and press Enter, you get a prompt that looks like this:
Python 3.11.5 (main, ...) [GCC ...] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
That >>> is the REPL. It stands for Read, Eval, Print, Loop. You type an expression, it evaluates it, prints the result, and loops back for more. This is the single best tool you have for learning Python. Use it constantly.
Try this yourself. Open a REPL and type each line, pressing Enter after each:
>>> 2 + 24>>> "hello"'hello'>>> "hello" + " world"'hello world'>>> len("hello")
5>>> exit()
That last one closes the REPL. You can also press Ctrl+D on Linux/macOS or Ctrl+Z then Enter on Windows.
1.2 Comments and docstrings
Look at the top of the shopping list source:
# Shopping List App - Upgraded Version# Features:# - Empty list if no saved file exists# - Menu system
Anything after a # on a line is a comment. The interpreter completely ignores it. Comments exist for humans — for you when you come back in six months, and for anyone else reading your code.
Now look inside clean_text:
def clean_text(text):
"""
Cleans user input and prevents the delimiter from breaking the file format.
"""
return text.replace(DELIMITER, "/").strip()
That triple-quoted string is a docstring (documentation string). It's a regular string, but by convention Python treats the first string inside a function, class, or module as documentation. Tools like help() read it.
Try this yourself. In a REPL:
>>> def greet(name):
... """Say hello to someone."""... return f"Hello, {name}!"
...
>>> help(greet)
You should see the docstring printed as help text.
# vs """...""" — when to use which
| Marker | Purpose | Ignored at runtime? |
|---|
| # | One-line note to a human reader | Yes, completely |
| """...""" at top of function/class/module | Formal documentation, readable by help() | It's stored as __doc__, but not executed as code |
| """...""" anywhere else | It's just a string. Python evaluates it but throws the result away. People sometimes use this as a "block comment" — it works but is not idiomatic. | |
1.3 Variables
A variable is a name pointing at a value. That's it. In Python you don't declare variables ahead of time. You just assign:
x = 5
name = "Apple"
prices = [10, 20, 30]
The = sign is assignment, not equality. Read x = 5 as "let x point at 5", not "x equals 5".
Analogy
Imagine a sticky note with the word x written on it, stuck to the number 5. When you write x = 10, you peel the sticky note off 5 and stick it on 10. The number 5 still exists somewhere in memory — the note just isn't on it anymore. Eventually Python's garbage collector notices that no sticky notes are on 5 and reclaims that memory.
Before: x ────► 5
After
x = 10: x ────► 10 (5 is now unreferenced)
This picture is technically an oversimplification (Python caches small ints in a shared pool, so 5 doesn't get freed), but the mental model is right for teaching purposes.
Constants (a convention, not a rule)
Look at the top of the shopping list source:
FILENAME = "shopping_list.txt"
DELIMITER = "|"
Those are constants — variables the author promises not to change. Python does not enforce constants; the ALL_CAPS name is a convention that says "other programmers, please don't reassign this." If you write FILENAME = "other.txt" further down, Python will happily do it. The rule is social, not technical.
Why have constants at all? Two reasons:
Findability. If you decide to rename the file to list.dat, you change one line at the top instead of hunting through the file.
Meaning. if line.split("|") is mysterious. if line.split(DELIMITER) tells the reader "the pipe character is playing a role — it's a delimiter."
![427-1]()
1.4 Data types - the seven you need on day one
Python has many types. Beginners need seven. Here they are with an example straight from the shopping list app:
| Type | Example from the app | What it is |
|---|
| str | "Apple", "shopping_list.txt" | Text. A sequence of characters. |
| int | 1, 25 (quantities) | Whole numbers. Can be negative. |
| float | not used here, but e.g. 3.14 | Decimal numbers. |
| bool | True, False (returned by is_us_dst) | Truth values. |
| None | default return of pause() | The absence of a value. |
| list | shopping_list = [], CATEGORIES = [...] | Ordered, mutable collection. |
| dict | {"name": "Eastern", "zone": "..."} (each entry in US_ZONES) | Key-value mapping. |
There's also tuple (immutable list), which the app uses briefly in except (TypeError, ValueError): — that parenthesized pair is a tuple.
type() — ask Python what something is
Try this yourself.
>>> type("Apple")
<class 'str'>
>>> type(25)
<class 'int'>
>>> type([1, 2, 3])
<class 'list'>
>>> type({"a": 1})
<class 'dict'>
>>> type(None)
<class 'NoneType'>
>>> type(True)
<class 'bool'>
Strings — the "Apple" type
Strings hold text. You can create them with "..." or '...' — Python doesn't care which, as long as you're consistent inside one string.
>>> s = "hello"
>>> len(s)
5
>>> s[0] # first character
'h'
>>> s[-1] # last character
'o'
>>> s.upper()
'HELLO'
>>> "hello" + " " + "world"
'hello world'
Every string method you'll see in this app is covered in Chapter 5.
Integers — the int type
int is a whole number. In Python 3, int has no size limit other than your computer's memory. You can compute 2 ** 1000 and Python will just give you a 302-digit number. (Try it.)
The shopping list uses int for quantity:
quantity = int(value)
return max(1, quantity)
max(1, quantity) returns whichever is bigger — 1 or the parsed number. So if the user typed -5, the code returns 1 instead. This is the sort of tiny defensive move that separates fragile code from robust code.
Booleans — True and False
Note the capital T and F. true (lowercase) is not a valid Python value — it's a name that isn't defined, so Python raises NameError.
Booleans come from comparisons:
>>> 5 > 3True>>> 5 == 3False>>> "apple" == "apple"True
None — the nothing value
None is Python's official "no value here" marker. It's returned by functions that don't return anything explicitly:
>>> def greet():
... print("hi")
...
>>> result = greet()
hi
>>> print(result)
None
pause() in the shopping list app has no return statement, so it returns None implicitly. Nobody in main() uses the return value, which is fine.
Lists — the workhorse
A list is an ordered, mutable collection of items. "Ordered" means element 0 is always element 0. "Mutable" means you can change it after creating it.
>>> nums = [10, 20, 30]
>>> nums[0]
10>>> nums[1]
20>>> nums.append(40)
>>> nums
[10, 20, 30, 40]
>>> nums[0] = 999>>> nums
[999, 20, 30, 40]
The shopping list itself is a list:
shopping_list = []
Each item in that list is also a list — [name, quantity, category]. This is called a list of lists and gets its own chapter (Chapter 4).
Dictionaries — key-value pairs
A dict maps keys to values. Look at any entry in US_ZONES:
{
"name": "Eastern",
"zone": "America/New_York",
"std_offset": timedelta(hours=-5),
"std": "EST",
"dst": "EDT"
}
To get a value, you use the key like an index:
>>> zone = {"name": "Eastern", "std": "EST"}
>>> zone["name"]
'Eastern'>>> zone["std"]
'EST'
Dicts are unordered conceptually — you look things up by key, not by position. (In Python 3.7+ they preserve insertion order for iteration, but you shouldn't rely on that when writing new code.)
Tuples — immutable lists (briefly)
The line:
except (TypeError, ValueError):
That (TypeError, ValueError) is a tuple. It looks like a list but uses parentheses and can't be modified after creation. Tuples are used when you want a fixed group of things — coordinates (x, y), RGB colors (255, 0, 128), or a list of exception types to catch.
You mostly won't create tuples explicitly for a long time. Just recognize them when you see them.
1.5 Basic arithmetic and string operations
Try this yourself.
>>> 3 + 4
7
>>> 10 - 3
7
>>> 6 * 7
42
>>> 10 / 3 # true division — always float
3.3333333333333335
>>> 10 // 3 # floor division — drops remainder
3
>>> 10 % 3 # modulo — remainder
1
>>> 2 ** 10 # exponent
1024
>>> "ab" * 3 # yes, strings can be multiplied
'ababab'
>>> "hello" + "!"
'hello!'
The one that surprises beginners is 10 / 3 returning a float even though both operands are integers. Python 3 does this on purpose — Python 2 returned 3 and it caused so many bugs that the language was changed.
Mastering Python begins not with memorizing syntax, but with developing accurate mental models of how the language operates. By understanding the distinction between the language and the interpreter, recognizing the specific roles of comments versus docstrings, and internalizing the behavior of variables and core data types, you establish a robust foundation for all future learning. The concepts covered here—from the sticky-note analogy for variable assignment to the defensive use of max() for input validation—are not just theoretical; they are the practical tools that separate fragile scripts from reliable software. As you continue your journey, return to the REPL frequently to experiment with these basics, because a deep, intuitive grasp of these fundamentals is what will ultimately enable you to build sophisticated and resilient Python applications.