Python Reference
A practical guide to the Python syntax, built-in functions, and programming concepts used in everyday development.
Variables & Data Types
Variables
Store data that can be used and updated throughout a program.
trail_name = "Eagle Peak"
elevation = 2450
has_bear = Truetype() & Conversion
Check a value’s type or convert it to another data type.
type(trail_name)
int("850")
str(42)
float("12.7")Constants (convention)
Python doesn’t enforce constants, but uppercase names are the standard convention.
MAX_GROUP_SIZE = 12Output & Input
print()
Displays text or variable values in the console.
print("Trail:", trail_name, "Elevation:", elevation, "m")input()
Reads input from the user and returns it as a string.
difficulty = input("How difficult is the trail? ")f-strings
Insert variables directly into strings using readable syntax.
f"Welcome to {trail_name}! Elevation: {elevation}m"Numbers & Math
Operators
Perform mathematical calculations with numbers.
distance + 4.2
total_time - 30
elevation * 2
distance / 5
hours // 2
steps % 1000
2 ** 4Built-in Math Functions
Built-in functions for common mathematical tasks.
round(12.78)
abs(-450)
max(1200, 2450, 890)
min(5, 18, 3)
sum([4, 7, 12])import math
Provides additional mathematical functions and constants.
import math
math.sqrt(225)
math.piStrings
String Methods
Modify, search, or format string values.
trail.upper()
" muddy path ".strip()
description.replace("bear", "deer")
"lake,forest,peak".split(",")len() & Checking
Measure string length or check whether a value exists.
len("Waterfall Trail")
"rain" in forecastConditions
if / elif / else
Run different code depending on whether conditions are true or false.
if elevation >= 2000:
print("High altitude trail!")
elif weather == "Rain":
print("Trail may be slippery")
else:
print("Good conditions")Comparisons & Logic
Compare values and combine conditions with logical operators.
distance >= 10 and has_water == TrueLoops
for Loop
Repeat code for each item in a sequence.
for i in range(1, 6):
print("Checkpoint", i)
for animal in wildlife:
print(animal)while Loop
Repeat code while a condition remains true.
while energy > 0:
energy -= 10Control Statements
Control how loops behave during execution.
break
continueFunctions
def
Create reusable blocks of code that perform specific tasks.
def calculate_pace(distance, time):
return distance / timeLambda
Create small anonymous functions in a single expression.
double = lambda x: x * 2
is_steep = lambda slope: slope > 20Lists
List Basics
Store ordered collections of items that can be modified.
trails = ["Pine Ridge", "Lake View"]
trails.append("Summit Loop")
trails.pop()
len(trails)List Comprehensions
Create new lists using a compact, readable syntax.
elevations = [x * 100 for x in range(5)]Common Methods
Frequently used methods for managing list data.
distances.sort()
sorted(distances)Dictionaries
Dictionary Basics
Store related information as key-value pairs.
trail = {
"name": "Bear Canyon",
"length": 14.5,
"difficulty": 7
}
trail["water"] = TrueDictionary Methods
Access or work with dictionary data.
trail.keys()
trail.get("difficulty")
for key, value in trail.items():File Handling
Reading & Writing
Read from or write to files using context managers.
with open("trails.txt", "r") as f:
data = f.read()
with open("log.txt", "w") as f:
f.write("Hike completed!")Modules & Imports
import
Load Python modules so their features can be used.
import random
import math
from datetime import datePopular Built-ins
Frequently used standard library modules.
random.randint(1, 20)
math.sqrt(64)Error Handling
try / except / finally
Handle runtime errors without stopping the program.
divisor = 0
try:
result = distance / divisor
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Hike log saved")