Python's syntax fits on one page. The twelve concepts below cover roughly 90% of the code beginners write in their first three months. Every section has a runnable example you can copy into a Python file and execute. At the end, a 20-line mini project uses every concept together. For the bigger picture of where syntax fits in your learning arc, see our complete Python beginner guide.![Python code on a laptop screen showing functions, loops, and variable definitions]()
Common operations beginners reach for:
Key Takeaways
- Python's design philosophy is summed up in PEP 20, The Zen of Python: "Readability counts. Simple is better than complex. There should be one — and preferably only one — obvious way to do it."
- Indentation is part of the syntax. PEP 8, the official style guide, specifies 4 spaces per indentation level and forbids mixing tabs with spaces.
- Six core data types cover almost every beginner script:
int,float,str,bool,list,dict. - The official Python tutorial at python.org remains the authoritative reference; this article condenses it into a one-read format.
- Even professional developers look up syntax daily. Fluency means recognizing the patterns, not memorizing every method name.
What Does This Tutorial Cover (and What Doesn't It)?
This is the syntax map, not the project handbook. The twelve concepts below — variables, types, operators, control flow, loops, functions, lists, dicts, tuples, files, errors, and one integration project — cover what you need to read and write Python at a beginner-to-intermediate level. They do NOT cover: object-oriented programming beyond surface-level mention, async/await, decorators, generators, or any framework (Django, Flask, pandas). Those come after this foundation. Pair this read with hands-on practice. Reading syntax explains the rules. Writing code builds the muscle memory. Across CodeGym's Python cohort, learners who pair the tutorial with daily code-writing reach basic fluency in 3-6 weeks. Learners who only read take 3-6 months for the same level of fluency.
Variables and Data Types
A variable is a labeled box that stores a value. Python figures out the type from the value — you don't declare it.name = "Sara" # str (string)
age = 30 # int (integer)
height = 1.68 # float
is_student = False # bool (boolean)
hobbies = ["reading", "hiking"] # list
profile = {"city": "Paris", "year": 2026} # dict
The six types above handle almost every situation you'll meet in the first months. Convert between types explicitly when needed: int("30"), str(30), float("1.68"). Implicit conversions are rare in Python — PEP 20 says "Explicit is better than implicit."Operators and Expressions
Arithmetic is what you'd expect, with two beginner traps. Integer division is//, regular division is /, and exponentiation is **:
10 / 3 # 3.3333... (float)
10 // 3 # 3 (integer division)
10 % 3 # 1 (remainder)
10 ** 3 # 1000 (exponentiation)
String concatenation uses +, but f-strings (formatted string literals) are the modern, readable way to mix variables and text:
name = "Sara"
age = 30
message = f"{name} is {age} years old"
print(message) # Sara is 30 years old
Comparison operators (==, !=, <, >, <=, >=) return True or False. Logical operators (and, or, not) combine boolean expressions. Note: Python uses the words, not symbols like && or ||.How Do if, else, and elif Work?
Branching code based on conditions. Watch the colon at the end of each branch and the 4-space indentation of the body:temperature = 22
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Pleasant")
elif temperature > 10:
print("Cool")
else:
print("Cold")
Python evaluates the conditions top to bottom. The first true branch runs; the rest are skipped. elif is short for "else if" and you can chain as many as you want. For single-line conditions, the ternary form works: label = "adult" if age >= 18 else "minor".
One beginner-specific note: any non-empty string, non-zero number, or non-empty list is "truthy" in a condition. if my_list: is the Pythonic way to check that a list has elements.How Do for and while Loops Work?
Thefor loop iterates over a sequence. The while loop repeats until a condition flips false.
# for loop with range
for i in range(5):
print(i) # prints 0, 1, 2, 3, 4
# for loop over a list
for hobby in ["reading", "hiking", "coding"]:
print(f"I enjoy {hobby}")
# while loop with a counter
count = 0
while count < 3:
print(f"Attempt {count}")
count += 1
Two useful tools inside loops: break exits the loop immediately, and continue skips the rest of the current iteration. Use for when you know the sequence to iterate. Use while when the stopping condition depends on something inside the loop (user input, an external state change). The official Python tutorial on control flow covers the edge cases.How Do You Write Python Functions?
Functions are reusable named code. Define withdef, return values with return:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sara")) # Hello, Sara!
print(greet("Sara", "Olá")) # Olá, Sara!
Two beginner traps to know about up front. First, return is not the same as print. return sends a value back to whatever called the function; print shows text on screen and returns None. New coders confuse these constantly. Second, never use a mutable default like def add(item, items=[]) — the list is created once when the function is defined and shared across all calls, which surprises everyone exactly once. Use items=None and initialize inside the function. The full pattern collection is in common Python mistakes to avoid.When Should You Use Lists, Dicts, or Tuples?
Three core data structures with overlapping uses. The decision rule fits in a small table.| Structure | Use when | Example |
|---|---|---|
| list | Order matters and you'll change the contents | ["a", "b", "c"] |
| dict | You have labeled data (key-to-value pairs) | {"name": "Sara", "age": 30} |
| tuple | You have a fixed group that shouldn't change | (48.8566, 2.3522) (a coordinate) |
# list
items = ["apple", "banana"]
items.append("cherry") # add to end
items[0] # "apple" (zero-indexed)
len(items) # 3
"apple" in items # True
# dict
person = {"name": "Sara", "age": 30}
person["city"] = "Paris" # add key
person.get("phone", "n/a") # safe lookup with default
for key, value in person.items():
print(key, value)
# tuple (read-only)
point = (48.8566, 2.3522)
latitude, longitude = point # unpackingHow Do You Read and Write Files in Python?
Thewith open(...) pattern is the idiomatic way. It automatically closes the file when the block ends, even if an error happens:
# Write a file
with open("notes.txt", "w") as f:
f.write("First line\n")
f.write("Second line\n")
# Read the whole file as one string
with open("notes.txt", "r") as f:
content = f.read()
print(content)
# Read line by line (memory-friendly for big files)
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
Two gotchas. First, file modes: "r" read, "w" write (overwrites), "a" append. Beginners often want "a" when they accidentally use "w". Second, on Windows, default encoding is sometimes cp1252 instead of utf-8; specify encoding="utf-8" explicitly if your file has non-ASCII text.How Do You Read Python Error Tracebacks?
Python errors are descriptive multi-line messages. The trick is reading them bottom-up.Traceback (most recent call last):
File "expense.py", line 12, in <module>
total = sum_expenses(my_data)
File "expense.py", line 5, in sum_expenses
return sum(item["cost"] for item in items)
KeyError: 'cost'
The last line tells you what went wrong: KeyError: 'cost' means a dictionary was missing the "cost" key. The lines above tell you where it happened: line 5 in sum_expenses, which was called from line 12. The five most common beginner errors are NameError (variable not defined), TypeError (wrong type used), IndexError (list index out of range), KeyError (dict key missing), and IndentationError. Each one tells you which is which in the last line.
Wrap risky code in try / except to handle errors gracefully:
try:
age = int(input("Your age: "))
except ValueError:
print("That wasn't a valid number.")
age = NoneA 20-Line Mini Project That Uses Everything
A simple expense tracker. Every concept above is in here: variables, types, control flow, while loop, function, list of dicts, file I/O via JSON, and error handling. Paste it into a file namedexpenses.py and run it.
import json
def load_expenses(filename):
try:
with open(filename, "r", encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_expenses(filename, expenses):
with open(filename, "w", encoding="utf-8") as f:
json.dump(expenses, f, indent=2)
expenses = load_expenses("expenses.json")
while True:
item = input("Item (or 'quit'): ")
if item == "quit":
break
try:
cost = float(input("Cost: "))
except ValueError:
print("Skipping — not a number.")
continue
expenses.append({"item": item, "cost": cost})
save_expenses("expenses.json", expenses)
total = sum(e["cost"] for e in expenses)
print(f"Total: {total:.2f} across {len(expenses)} entries")
Run it, add a few entries, type quit to exit. Run it again and your previous entries are still there. Twenty lines, every fundamental in play.Drill These Patterns on CodeGym Python
800+ small graded tasks built around exactly these concepts. Write a few lines, see if they pass, fix, advance. The shortest feedback loop in Python practice. First level free on the Python course →, full curriculum on the pricing page.What Should You Practice Next?
Three concrete drills before moving on. Each one takes 30-90 minutes and uses only the syntax above.- Word counter: Read a text file, count how many times each word appears, print the top 10. Uses file I/O, dicts, sorting.
- FizzBuzz with twists: Classic FizzBuzz (multiples of 3 print Fizz, of 5 print Buzz, of both print FizzBuzz, otherwise the number). Then add a fourth multiple. Uses control flow, loops.
- Mini contacts book: Add, list, search contacts. Save to a JSON file between runs. Uses everything in the mini project above plus a search function.
Frequently Asked Questions
Should I learn Python 2 or Python 3 syntax?
Python 3 only. Python 2 reached end-of-life in January 2020 and is no longer maintained or patched for security. All new projects, all official tutorials, and all major libraries use Python 3. When tutorials or books say "Python," they mean Python 3.x — currently 3.12 or 3.13 in production.Do I need to memorize all this Python syntax?
No. Memorize the patterns (the if/else shape, the for loop structure, the def function signature) and look up the details. Even professional developers Google syntax 5-10 times a day. The goal is fluency in reading and writing the patterns, not perfect recall of every method name. If you're worried you don't remember enough, see whether Python is hard to learn for honest expectations.What text editor should I use to write Python?
VS Code is the most-used editor among Python developers, according to the JetBrains Python Developers Survey 2024, which polled over 30,000 Python users globally. PyCharm Community Edition is a strong alternative built specifically for Python. Both are free. Avoid plain Notepad for anything beyond hello world — you'll miss syntax highlighting and indentation help.Where should I practice these syntax patterns?
The python.org official tutorial has runnable examples for every concept. For graded practice with instant feedback, task-based platforms like CodeGym's Python track structure thousands of small exercises around exactly these patterns. The key is daily repetition: 30 minutes a day beats 4 hours on Sunday.The Bottom Line: One Page of Syntax, Months of Practice
You now have the twelve syntax fundamentals on one page. The patterns won't change. What's left is the part the page can't give you: writing code every day for the next 3-6 months until these patterns feel automatic. Pick the mini project above, type it into a file, run it, and start practicing. For where syntax sits in the broader learning arc — what to learn after, how long it takes, what jobs it leads to — start with our complete Python beginner guide.Learn more about our mission and terms of service. Published article was last reviewed on 2026-05-12.
GO TO FULL VERSION