Quick Start
Want to get productive with Python fast? This Quick Start teaches you the essential syntax and core patterns you need to read Python code and try simple examples independently. You’ll understand Python’s approach to simplicity and readability.
For comprehensive coverage and hands-on practice, see the Complete Beginner’s Guide. For practical patterns and recipes, check out the Python Cookbook and How-To Guides.
πΊοΈ Python Learning Touchpoints
This Quick Start gives you exposure to Python’s core concepts in order of importance:
%% Color Palette: Blue #0173B2, Orange #DE8F05, Teal #029E73
graph TD
A[Variables & Types] --> B[Control Flow]
B --> C[Functions]
C --> D[Lists & Dictionaries]
D --> E[String Formatting]
E --> F[Error Handling]
F --> G[List Comprehensions]
G --> H[Modules]
H --> I[Ready to Explore!]
style A fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style B fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style C fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style D fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style E fill:#DE8F05,stroke:#000000,color:#FFFFFF,stroke-width:2px
style F fill:#DE8F05,stroke:#000000,color:#FFFFFF,stroke-width:2px
style G fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style H fill:#0173B2,stroke:#000000,color:#FFFFFF,stroke-width:2px
style I fill:#029E73,stroke:#000000,color:#FFFFFF,stroke-width:3px
Each section introduces ONE essential concept with ONE example. After completing all touchpoints, you’ll understand Python’s philosophy and can start experimenting independently.
π Prerequisites
- Basic programming knowledge in any language
- Python installed (version 3.12 or later recommended - see Initial Setup if you haven’t installed Python yet)
π€ Variables and Types
Python uses dynamic typing with type hints for clarity:
name = "Alice"
age = 30
height = 1.65
is_active = True
city: str = "Jakarta"
count: int = 42
price: float = 99.99
x, y, z = 10, 20, 30
MAX_RETRIES = 3
API_URL = "https://api.example.com"
print(name, age, height, is_active)Key Types:
str- Textint- Whole numbers (unlimited precision!)float- Decimal numbersbool-True/False(capitalized)None- Absence of value (likenullin other languages)
Python uses duck typing: “If it walks like a duck and quacks like a duck, it’s a duck.” For deeper coverage of types and type hints, see the Beginner tutorial and Use type hints effectively.
π Control Flow
Python uses indentation (not braces) for code blocks:
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
for i in range(3):
print(i) # Prints: 0, 1, 2
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
count = 0
while count < 3:
print(count)
count += 1
for i in range(10):
if i == 3:
continue # Skip 3
if i == 5:
break # Stop at 5
print(i) # Prints: 0, 1, 2, 4Key Points:
- Indentation is syntax (4 spaces standard, not tabs)
range(n)generates numbers from 0 to n-1for item in collectionis the Pythonic way
For advanced control flow patterns, see Use control structures effectively and Python Best Practices.
π§ Functions
Functions are first-class objects in Python:
def greet(name):
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
def power(base, exponent=2):
return base ** exponent
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
square = lambda x: x ** 2
print(greet("Alice")) # Hello, Alice
print(add(5, 3)) # 8
print(power(5)) # 25 (default exponent=2)
print(power(5, 3)) # 125
q, r = divide(10, 3)
print(q, r) # 3 1
print(square(4)) # 16Key Points:
- No explicit
returntype in basic syntax (but type hints help) - Default arguments must come after required arguments
- Functions can return multiple values (tuples)
- Lambdas are concise one-line functions
Deep dive into functions in the Beginner tutorial or explore patterns in Write effective functions.
π Lists and Dictionaries
Python’s built-in collections are powerful:
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Add to end
numbers.insert(0, 0) # Insert at position
first = numbers[0] # Access by index
last = numbers[-1] # Negative indexing
slice_nums = numbers[1:4] # Slicing [1, 2, 3]
print(numbers) # [0, 1, 2, 3, 4, 5, 6]
person = {
"name": "Alice",
"age": 30,
"city": "Jakarta"
}
print(person["name"]) # Alice
print(person.get("age")) # 30 (safe access)
person["email"] = "alice@example.com"
person["age"] = 31
for key, value in person.items():
print(f"{key}: {value}")Key Points:
- Lists are indexed from 0, support negative indices
- Slicing:
list[start:end](end is exclusive) - Dictionaries are unordered (Python 3.7+ maintains insertion order)
- Use
.get(key)to avoid KeyError
For more collection patterns, see Work with lists effectively and Work with dictionaries effectively.
π¬ String Formatting
Python has multiple ways to format strings:
name = "Alice"
age = 30
price = 19.99
print(f"Hello, {name}!")
print(f"{name} is {age} years old")
print(f"Price: ${price:.2f}") # Format to 2 decimal places
print("Hello, {}!".format(name))
print("{} is {} years old".format(name, age))
print("Hello, %s!" % name)
message = f"""
Dear {name},
You are {age} years old.
Your order total is ${price:.2f}.
Best regards
"""
print(message)Key Points:
- f-strings are the modern, readable way
:.2fformats floats to 2 decimal places- Triple quotes (
"""or''') for multi-line strings
β οΈ Basic Error Handling
Python uses exceptions for error handling:
try:
number = int("abc") # This will raise ValueError
except ValueError as e:
print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 10: 'abc'
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
else:
# Runs if no exception
content = file.read()
print(content)
finally:
# Always runs (cleanup)
if 'file' in locals():
file.close()
try:
value = my_dict["key"]
except KeyError:
value = "default"
if "key" in my_dict:
value = my_dict["key"]
else:
value = "default"Key Points:
- Python encourages EAFP (try first, handle errors)
- Specific exceptions before general ones
finallyblock always executes (cleanup code)
For comprehensive error handling strategies, see Handle errors effectively and Intermediate tutorial.
π List Comprehensions
Concise way to create lists:
squares = []
for i in range(10):
squares.append(i ** 2)
squares = [i ** 2 for i in range(10)]
print(squares)
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares)
squares_dict = {i: i ** 2 for i in range(5)}
print(squares_dict)
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix)Key Points:
- Comprehensions are more concise than loops
- Format:
[expression for item in iterable if condition] - Works for lists, dicts, sets
π Modules and Imports
Python code is organized in modules:
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
from math import pi, sqrt
print(pi) # 3.141592653589793
print(sqrt(16)) # 4.0
import datetime as dt
now = dt.datetime.now()
print(now)
from math import *
print(cos(0)) # 1.0
import os # Operating system functions
import sys # System-specific parameters
import json # JSON parsing
import random # Random number generation
import re # Regular expressions
random_number = random.randint(1, 10)
current_dir = os.getcwd()
print(f"Random: {random_number}, Directory: {current_dir}")Key Standard Library Modules:
math- Mathematical functionsdatetime- Date and time handlingos- Operating system interfacesys- System-specific parametersjson- JSON encoding/decodingre- Regular expressionsrandom- Random number generationcollections- Specialized data structures
π File Input/Output
Reading and writing files is simple in Python:
with open('data.txt', 'w') as f:
f.write("Hello, file!\n")
f.write("Second line\n")
with open('data.txt', 'r') as f:
content = f.read()
print(content)
with open('data.txt', 'r') as f:
for line in f:
print(line.strip()) # strip() removes newline
with open('data.txt', 'a') as f:
f.write("Appended line\n")File Modes:
'r'- Read (default)'w'- Write (overwrites existing file)'a'- Append (adds to end of file)'r+'- Read and write'rb'- Read binary'wb'- Write binary
Best Practices:
- Always use
withstatement - automatically closes files - Use
pathlib.Pathfor cross-platform path handling - Handle file exceptions with try/except
from pathlib import Path
file_path = Path('data') / 'users.txt'
if file_path.exists():
text = file_path.read_text()
print(text)ποΈ Working with JSON
JSON is Python’s most common data interchange format:
import json
data = {
'name': 'Alice',
'age': 30,
'skills': ['Python', 'JavaScript'],
'active': True
}
json_string = json.dumps(data, indent=2)
print(json_string)
with open('user.json', 'w') as f:
json.dump(data, f, indent=2)
with open('user.json', 'r') as f:
loaded_data = json.load(f)
print(loaded_data['name']) # Alice
json_text = '{"status": "success", "count": 42}'
result = json.loads(json_text)
print(result['count']) # 42Key Functions:
json.dumps()- Convert Python object to JSON stringjson.dump()- Write Python object to file as JSONjson.loads()- Parse JSON string to Python objectjson.load()- Read JSON file to Python object
JSON Type Mapping:
- Python
dictβ JSON object - Python
listβ JSON array - Python
strβ JSON string - Python
int/floatβ JSON number - Python
True/Falseβ JSON true/false - Python
Noneβ JSON null
π§ Virtual Environments
Virtual environments isolate project dependencies:
python -m venv venv
venv\Scripts\activate
source venv/bin/activate
pip install requests
pip list
pip freeze > requirements.txt
pip install -r requirements.txt
deactivateWhy Use Virtual Environments?:
- Each project has its own dependencies
- Avoid version conflicts between projects
- Easy to reproduce exact environment
- Don’t pollute global Python installation
For more details, see Use virtual environments and Manage Python packages effectively.
Best Practice: Create a new venv for every project.
π¨ Common Patterns
Enumerate for Index + Value
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")Zip for Parallel Iteration
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
user_dict = dict(zip(names, ages))
print(user_dict) # {'Alice': 25, 'Bob': 30, 'Charlie': 35}Any and All
numbers = [1, 2, 3, 4, 5]
has_even = any(n % 2 == 0 for n in numbers) # True
all_positive = all(n > 0 for n in numbers) # True
is_empty = not any(numbers) # FalseDefault Dictionary Values
config = {'timeout': 30}
timeout = config.get('timeout', 10) # 30
retries = config.get('retries', 3) # 3 (default)
config.setdefault('retries', 3) # Sets retries=3 if not exists
print(config) # {'timeout': 30, 'retries': 3}π Pythonic Style Tips
Use in for Membership:
if name == 'Alice' or name == 'Bob' or name == 'Charlie':
print("Known user")
if name in ['Alice', 'Bob', 'Charlie']:
print("Known user")Use with for Resources:
f = open('file.txt', 'r')
try:
content = f.read()
finally:
f.close()
with open('file.txt', 'r') as f:
content = f.read()Use Comprehensions:
squares = []
for i in range(10):
squares.append(i**2)
squares = [i**2 for i in range(10)]Use Multiple Assignment:
temp = a
a = b
b = temp
a, b = b, aβ Next Steps
You now have touchpoints across Python’s core concepts! To deepen your knowledge:
Try the examples: Copy and run each code snippet. Modify them and experiment.
Read the docs: Visit docs.python.org to explore in depth or check our Python Resources.
Complete the Beginner tutorial: Complete Beginner’s Guide to Python covers everything comprehensively with:
- Classes, objects, and inheritance
- Decorators and context managers
- File I/O and working with APIs
- Virtual environments and package management
- Testing with pytest
- 4 levels of practice exercises
Explore practical recipes: Python Cookbook has 30+ copy-paste-modify solutions.
Deepen specific topics: How-To Guides provide focused tutorials on specific techniques.
Learn best practices: Python Best Practices and Anti-Patterns show what to do (and what to avoid).
π― Self-Assessment
After completing this Quick Start, you should be able to:
- Read and understand basic Python syntax
- Write simple functions with parameters and return values
- Handle errors with try/except blocks
- Use lists and dictionaries to store collections
- Format strings with f-strings
- Write list comprehensions for concise data transformations
- Import and use standard library modules
- Understand Python’s approach to simplicity and readability
If you can do these, you’re ready to explore Python code and try simple examples independently!