Skip to content

Python Basic Syntax

This article introduces the fundamental concepts and core syntax of Python, covering variables, data types, operators, formatted output, and encoding. All examples are based on Python 3.10+ and do not cover the end-of-life Python 2.

Introduction to Python

Python is a high-level, general-purpose programming language designed by Guido van Rossum in 1989, renowned for its simplicity and readability. It is an interpreted language that supports multiple programming paradigms — object-oriented, functional, and procedural — and is widely used in web development, data science, automation, and artificial intelligence.

Python Version History

VersionRelease DateKey Features
Python 1.01994-01lambda, map, filter, reduce
Python 2.02000-10Garbage collection, list comprehensions
Python 2.72010-07Last 2.x release; end-of-life January 2020
Python 3.02008-12Breaking redesign; unified strings as Unicode
Python 3.62016-12f-strings, variable annotations
Python 3.82019-10Walrus operator :=, positional-only parameter /
Python 3.92020-10Generic built-in types (list[int]), dict merge operator |
Python 3.102021-10Structural pattern matching match/case, improved error messages
Python 3.112022-1010–60% performance boost, ExceptionGroup
Python 3.122023-10Type parameter syntax, f-strings support nested quotes
Python 3.132024-10Experimental GIL-free mode (--disable-gil), upgraded REPL
Recommended versions: Python 3.12 / 3.13. Python 2 reached end-of-life on January 1, 2020. Use Python 3 for all new projects.

Compiled vs Interpreted Languages

TypeExamplesAdvantagesDisadvantages
CompiledC, Go, RustHigh execution speed; runs without a runtime environmentRequires recompilation per platform; recompile after every change
InterpretedPython, RubyCross-platform; no recompilation needed after editsSlower at runtime; re-interpreted each execution

Classification of Programming Languages

  • Machine language: Programs written directly in binary instructions. Fastest execution, but extremely difficult to write and maintain.
  • Assembly language: Uses mnemonics to represent binary instructions. Still operates close to hardware; steep learning curve.
  • High-level languages: Abstract away hardware details and are closer to human thinking. Divided into compiled and interpreted types.

Execution speed: Machine language > Assembly > High-level (Compiled > Interpreted)

Development speed: Machine language < Assembly < High-level (Compiled < Interpreted)

Python Interpreters

Python the language and the Python interpreter are two distinct concepts:

  • Python language: The syntax specification (PEP standards).
  • Python interpreter: The program that reads and executes Python code. Common implementations include:
InterpreterDescription
CPythonOfficial interpreter written in C; launched by the python command; most widely used
PyPyWritten in Python; uses JIT compilation; fastest at runtime; ideal for compute-intensive tasks
JythonRuns on the JVM; can compile directly to Java bytecode
IronPythonRuns on the .NET platform
MicroPythonDesigned for microcontrollers and embedded devices

Installation and Your First Program

Download the installer from python.org and check Add Python to PATH during setup.

# Verify installation
python --version   # Python 3.13.x

# Interactive mode (great for debugging)
python

# Run a script
python hello.py
# hello.py
print("Hello, World!")

Comments

# Single-line comment: starts with #

"""
Multi-line comment:
wrapped in triple quotes; commonly used as docstrings for functions/classes
"""

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

Variables

Variable Basics

Variables are labels for data stored in memory. In Python, no type declaration is needed — assignment creates the variable.

age = 18           # integer
name = "Alice"     # string
height = 1.75      # float
is_adult = True    # boolean

# Three key attributes of a variable
print(id(age))     # memory address
print(type(age))   # type
print(age)         # value

Naming Rules

  • May only contain letters, digits, and underscores; cannot start with a digit.
  • Case-sensitive: name and Name are two different variables.
  • Cannot use Python keywords (if, for, class, etc.).
  • Convention: use snake_case for variable names; ALL_CAPS for constants like MAX_SIZE.
# Valid variable names
user_name = "Bob"
_private = 42
MAX_RETRY = 3

# Multiple assignment
x = y = z = 0          # Chained assignment; all three point to the same object
a, b = 10, 20          # Unpacking assignment
a, b = b, a            # Swap two variables

# Extended unpacking (Python 3)
first, *rest = [1, 2, 3, 4, 5]
# first=1, rest=[2, 3, 4, 5]

Small Integer Caching

CPython caches integer objects in the range -5 to 256 (the small integer pool), so variables with the same value share the same memory address:

a = 100
b = 100
print(a is b)   # True, shared object

a = 300
b = 300
print(a is b)   # False (in CPython), outside the cached range
Never use is to compare numbers or strings for equality — always use ==. The is operator checks object identity (memory address); == checks value equality.

Basic Data Types

Numeric Types

# int (arbitrary precision, no overflow)
age = 18
big = 10 ** 100          # Supports arbitrarily large integers

# float (64-bit double precision)
pi = 3.14159
sci = 1.5e-3             # Scientific notation: 0.0015

# complex
c = 3 + 4j
print(c.real, c.imag)    # 3.0  4.0

# Type conversion
int("42")        # 42
float("3.14")    # 3.14
int(3.9)         # 3 (truncates, does not round)

String Type

s1 = 'hello'
s2 = "world"
s3 = """multi-line
string"""

# Concatenation and repetition
greeting = "Hello" + ", " + "Alice"
line = "-" * 40

# Indexing and slicing
s = "Python"
print(s[0])      # P (forward index starts at 0)
print(s[-1])     # n (reverse index starts at -1)
print(s[1:4])    # yth
print(s[::-1])   # nohtyP (reversed)

List Type

# Ordered, mutable, elements can be any type
fruits = ["apple", "banana", "cherry"]
print(fruits[0])          # apple
print(fruits[-1])         # cherry

# Nested list
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2])       # 6

Dictionary Type

# Key-value pairs; keys must be immutable
person = {"name": "Alice", "age": 25, "city": "Beijing"}
print(person["name"])     # Alice

# Python 3.9+ dict merge
defaults = {"color": "red", "size": 10}
custom = {"color": "blue"}
merged = defaults | custom   # {'color': 'blue', 'size': 10}

Tuple Type

# Ordered, immutable
coords = (10.0, 20.0)
x, y = coords             # Unpacking

# Single-element tuple requires a trailing comma
single = (42,)            # Without the comma it is just parentheses around 42

Set Type

# Unordered, no duplicates
s = {1, 2, 3, 2, 1}
print(s)                  # {1, 2, 3}

# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)              # Union: {1, 2, 3, 4}
print(a & b)              # Intersection: {2, 3}
print(a - b)              # Difference: {1}

Boolean Type

print(True, False)
print(type(True))         # <class 'bool'>
print(int(True))          # 1
print(int(False))         # 0

# Falsy values
# 0, 0.0, "", [], {}, (), set(), None are all False
if []:
    print("this will not execute")

Type Conversion

# Explicit type conversion
str(123)          # '123'
list("abc")       # ['a', 'b', 'c']
tuple([1, 2, 3])  # (1, 2, 3)
set([1, 1, 2])    # {1, 2}
dict([("a", 1)])  # {'a': 1}

Formatted Output

Python offers three string formatting approaches; f-strings are the recommended choice.

% Formatting (old-style, not recommended)

name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))

str.format()

print("Name: {}, Age: {}".format("Alice", 25))
print("{name} is {age} years old".format(name="Bob", age=30))
print("{0:>10}".format("right"))   # Right-align, width 10
print("{:.2f}".format(3.14159))    # Two decimal places

f-strings (recommended, Python 3.6+)

name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")

# Expressions
print(f"Next year: {age + 1}")
print(f"π ≈ {3.14159:.2f}")

# Python 3.12+: any quote style inside f-strings (no escaping needed)
items = ["apple", "banana"]
print(f"First item: {items[0]!r}")

# Debug output (Python 3.8+, = shows variable name and value)
x = 42
print(f"{x=}")   # x=42

Walrus Operator (Python 3.8+)

The walrus operator := allows assignment inside an expression, useful in while loops or conditionals to avoid redundant computation:

import re

# Traditional approach
data = "Hello 42 World"
m = re.search(r"\d+", data)
if m:
    print(m.group())

# Using the walrus operator
if m := re.search(r"\d+", data):
    print(m.group())   # 42

# Simplify while loops
while chunk := input("Enter text (blank line to stop): "):
    print(f"You entered: {chunk}")

Base Conversion

# Decimal to other bases
print(bin(10))    # 0b1010
print(oct(10))    # 0o12
print(hex(255))   # 0xff

# Other bases to decimal
print(int("1010", 2))    # 10 (binary → decimal)
print(int("ff", 16))     # 255 (hexadecimal → decimal)

# Thousands separator formatting
print(f"{1234567890:,}")   # 1,234,567,890

Operators

Arithmetic Operators

OperatorDescriptionExample (x=9, y=2)
+Additionx+y → 11
-Subtractionx-y → 7
*Multiplicationx*y → 18
/Division (result is float)x/y → 4.5
//Floor divisionx//y → 4
%Modulusx%y → 1
**Exponentiationx**y → 81

Comparison and Logical Operators

# Comparison operators return bool
print(3 > 2)     # True
print(3 == 3.0)  # True (equal values)
print(3 is 3.0)  # False (different types, different objects)

# Chained comparison (Python-specific)
x = 5
print(1 < x < 10)  # True

# Logical operators: not > and > or
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

# Short-circuit evaluation: and/or return the operand that determines the result
print(0 or "default")   # "default"
print(1 and "ok")       # "ok"

Assignment Operators

x = 10
x += 1      # x = 11
x -= 2      # x = 9
x *= 3      # x = 27
x //= 4     # x = 6
x **= 2     # x = 36

Bitwise Operators

a = 60   # 0011 1100
b = 13   # 0000 1101

print(a & b)    # 12   bitwise AND
print(a | b)    # 61   bitwise OR
print(a ^ b)    # 49   bitwise XOR
print(~a)       # -61  bitwise NOT
print(a << 2)   # 240  left shift
print(a >> 2)   # 15   right shift

Mutable vs Immutable Types

# Immutable types: int, float, str, tuple, frozenset
# Changing the value creates a new object (id changes)
a = "hello"
print(id(a))
a = a + "!"
print(id(a))    # id has changed

# Mutable types: list, dict, set
# Modified in-place; id remains the same
lst = [1, 2, 3]
print(id(lst))
lst.append(4)
print(id(lst))  # id unchanged

Character Encoding

import sys
print(sys.getdefaultencoding())   # utf-8

# In Python 3, str is Unicode; bytes is a byte sequence
s = "你好"
b = s.encode("utf-8")             # str → bytes
print(b)                          # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(b.decode("utf-8"))          # bytes → str

# Source files default to UTF-8; no need for # -*- coding: utf-8 -*- at the top

Garbage Collection

CPython uses three mechanisms to manage memory:

  1. Reference counting: Each object tracks how many references point to it; when the count reaches zero, the object is immediately freed.
  2. Mark-and-sweep: Resolves memory leaks caused by circular references.
  3. Generational collection: Objects are grouped into generations 0, 1, and 2 based on how long they have survived, reducing scan frequency and improving efficiency.
import gc

# Trigger garbage collection manually
gc.collect()

# Check reference count
import sys
x = [1, 2, 3]
print(sys.getrefcount(x))   # 2 (x itself + the getrefcount argument)

Common IDEs and Developer Tools

ToolHighlights
PyCharmBy JetBrains; most feature-rich; ideal for large projects
VS CodeLightweight with a rich extension ecosystem; very powerful with the Python extension
Jupyter NotebookFirst choice for data science; mixes code and visualizations
uvModern Python package and project manager; extremely fast
RuffUltra-fast Python linter and formatter (replaces flake8/black)
Last updated on