🐍Intro to Python Programming
Python Syntax Rules
Study smarter with Fiveable
Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.
Why This Matters
Python's reputation as a "readable" language isn't accidental—it's enforced through strict syntax rules that shape how you write every line of code. Understanding these rules isn't just about avoiding error messages; it's about grasping why Python was designed this way. You're being tested on your ability to write syntactically correct code, debug common mistakes, and explain the reasoning behind Python's design choices.
The syntax rules you'll learn here fall into three categories: structure and whitespace, naming and style conventions, and data representation. Each rule connects to Python's core philosophy of readability and simplicity. Don't just memorize what the rules are—understand what problem each rule solves and how breaking it affects your code's behavior.
Structure and Whitespace
Python uses whitespace as syntax, not just formatting. Unlike languages that use braces or keywords to define code blocks, Python makes indentation meaningful—this forces readable code by design.
Indentation Defines Code Blocks
- Four spaces per indentation level—this is the standard convention that most Python code follows
- Mixing tabs and spaces causes errors—Python 3 raises
TabErrorwhen you inconsistently mix them in the same block - Indentation determines scope—code at the same indentation level belongs to the same block, making nested logic visually obvious
Colons Introduce New Blocks
- A colon (
:) signals "here comes an indented block"—required afterif,for,while,def,class, and similar statements - Forgetting the colon triggers
SyntaxError—one of the most common beginner mistakes - The colon-plus-indent pattern is universal—once you recognize it, you'll read Python control flow instantly
Line Endings Replace Semicolons
- Newlines end statements automatically—no semicolon required, which reduces visual clutter
- Semicolons are legal but discouraged—you can use them to put multiple statements on one line, but this hurts readability
- Long lines can use backslash (
\) or parentheses for continuation—keeps code readable when expressions get complex
Compare: Python's indentation-based blocks vs. languages using braces {}—both define scope, but Python enforces visual structure. If you're asked why Python code "looks cleaner," this is your answer.
Naming and Style Conventions
Python has strong opinions about how you name things. These aren't just suggestions—following them makes your code recognizable to other Python developers and helps you avoid subtle bugs.
Case Sensitivity Matters
Variableandvariableare completely different identifiers—Python distinguishes uppercase and lowercase letters- This causes hard-to-find bugs—accidentally capitalizing a variable name creates a new variable instead of referencing the existing one
- Built-in names use specific casing—
True,False, andNoneare capitalized; most functions and methods are lowercase
Snake_case Is Standard
- Use
snake_casefor variables and functions—lowercase words separated by underscores (e.g.,user_name,calculate_total) - This follows PEP 8, Python's official style guide—consistent naming makes code easier to read and maintain
- Classes use
PascalCaseinstead—capitalizing each word without underscores (e.g.,UserAccount) distinguishes classes from functions
Comments Use # and Triple Quotes
- Single-line comments start with
#—everything after the hash on that line is ignored by Python - Triple quotes (
'''or""") create multi-line strings—often used as docstrings to document functions and classes - Comments explain why, not what—good comments clarify intent, not obvious syntax
Compare: snake_case for functions vs. PascalCase for classes—both improve readability, but the distinction helps you identify what kind of object you're working with at a glance.
Data Representation
Python is dynamically typed, meaning you don't declare variable types—Python figures them out from the values you assign. Understanding how to represent different data types correctly is essential.
Variables Are Created on Assignment
- No declaration needed—writing
x = 5creates the variablexand assigns it the value5in one step - Dynamic typing means types can change—the same variable can hold an integer, then a string, then a list
- This flexibility requires careful attention—you won't get compiler warnings if you accidentally change a variable's type
Strings Use Matching Quotes
- Single (
') or double (") quotes both work—but they must match (start and end with the same type) - Triple quotes allow multi-line strings—useful for long text or docstrings
- Escape characters handle special cases—use
\'or\"when you need quotes inside a string
Data Types Have Distinct Syntax
- Integers are whole numbers without quotes—
42,-7,0are all integers - Floats include a decimal point—
3.14,2.0,-0.5are floats (note:2.0is a float, not an integer) - Booleans are capitalized keywords—
TrueandFalse(nottrueorTRUE)
Compare: "5" (string) vs. 5 (integer) vs. 5.0 (float)—they look similar but behave completely differently in operations. Mixing them up causes TypeError in many situations.
Function and Expression Syntax
Parentheses serve multiple purposes in Python. Understanding when they're required versus optional helps you write correct code and read others' code accurately.
Parentheses Are Required for Function Calls
- Every function call needs parentheses—even with no arguments, write
print()notprint - Without parentheses, you reference the function object itself—
printis the function,print()calls the function - Arguments go inside the parentheses—separated by commas for multiple arguments
Parentheses Control Order of Operations
- Group expressions to override default precedence—
(2 + 3) * 4gives20, while2 + 3 * 4gives14 - Standard math precedence applies—multiplication before addition, exponents before multiplication
- When in doubt, use parentheses for clarity—even when not strictly necessary, they make intent obvious
Compare: my_function vs. my_function()—the first is a reference to the function object (useful for passing functions as arguments), the second actually executes the function. This distinction trips up many beginners.
Quick Reference Table
| Concept | Key Rules |
|---|---|
| Code Block Structure | Indentation (4 spaces), colons before blocks |
| Statement Endings | Newlines end statements, semicolons optional |
| Variable Naming | snake_case, case-sensitive |
| Class Naming | PascalCase |
| String Syntax | Matching quotes (' or "), triple quotes for multi-line |
| Numeric Types | No quotes for numbers, decimal point makes float |
| Boolean Values | True and False (capitalized) |
| Function Calls | Always use parentheses, even with no arguments |
| Comments | # for single-line, ''' or """ for multi-line |
Self-Check Questions
-
What two syntax elements work together to define a code block in Python, and why does this design enforce readable code?
-
You see
TypeErrorwhen trying to concatenate a variable. The variable was assigned ascount = "5"earlier. What's the likely issue, and how would you fix it? -
Compare
my_listandmy_list()—what does each expression do, and when would you use each one? -
A classmate's code uses both
userNameanduser_nameas variables. What two problems might this cause? -
Why does Python distinguish between
5,5.0, and"5"? Give an example of an operation that would work with one but fail with another.