Python Syntax and Variables
Python Syntax and Variables
Code That Reads Naturally
Python was designed so that code looks clean and organized. One of its defining rules is indentation: blocks of code are grouped by consistent spacing rather than by curly braces. A standard is four spaces per level, and your editor can handle that automatically. Mixing tabs and spaces causes errors, so pick one kind of indentation and stay consistent.
Comments start with a hash symbol. Anything after the hash on that line is ignored by Python.
# This is a comment
age = 25 # This is also a comment
Variables Hold Values
A variable is a name that points to a value. You create one with a single equals sign. Python is dynamically typed, which means you do not declare the type ahead of time; the interpreter infers it from the value you assign.
name = "Ada"
age = 36
height = 1.68
is_teacher = True
Here name holds a string, age a whole number, height a decimal number, and is_teacher a boolean. Later you can reassign any variable to a different value, even a different type.
Naming Rules and Conventions
Variable names can contain letters, digits, and underscores, but they cannot start with a digit and cannot be reserved words such as if or for. Use lowercase letters for variables and separate words with underscores, a style known as snake_case. Names should describe what they hold, so line_count is better than x.
Remember that Python is case-sensitive: Total and total are two different variables. A common beginner mistake is writing True as true, which crashes because True is a reserved boolean value and true is undefined.
Python Keywords You Will Meet
Keywords are reserved words that have special meaning. Early on you will use if, else, elif, for, while, def, return, import, and from. If you ever need the full list, run the following in your REPL:
import keyword
print(keyword.kwlist)
Key Points
- Python groups blocks with indentation, and four spaces is the standard.
- Comments begin with a hash symbol and explain code to readers.
- Variables are created with a single equals sign and need no type declaration.
- Use snake_case names, avoid reserved words, and respect case sensitivity.
- Keywords like def and if cannot be used as variable names.