Python Quick Reference
This page is a small companion page for Python practice. It does not replace the course materials, but it is useful when you want to quickly recall the shape of a construct.
Read the Structure First
Before focusing on syntax, ask three small questions:
- What is the program supposed to do?
- What input does it need, and what output does it produce?
- What is the shape — linear, branching, or looping?
That habit becomes especially useful once functions, loops, and files appear.
Printing and Asking for Input
print("Hello, world!")
name = input("What is your name? ")print(f"Hello, {name}!")Common notes:
printdisplays its argument.inputalways returns text, even when the user types digits.- f-strings (
f"...") are the preferred way to include a variable’s value in a piece of text.
Variables and Assignment
minutes = 45subject = "Math"= is assignment, not equality. A variable is created the first time you assign to it, and you can reassign it later.
Type Conversion
minutes_text = input("Minutes: ")minutes = int(minutes_text)total = minutes + 15Use int(...), float(...), or str(...) to convert between types. int("forty-five") raises ValueError.
f-strings
subject = "Math"minutes = 45print(f"Logged {minutes} minutes of {subject}.")Inside { }, any expression works:
print(f"That is {minutes / 60} hours.")Joining Strings with +
first_name = "Ada"last_name = "Lovelace"full_name = first_name + " " + last_name+ joins two strings end-to-end. Use it when you have two existing string values you want to join, and prefer f-strings when you are inserting values into a fixed sentence. + between a string and a number raises TypeError.
Common String Methods
name = " Ada Lovelace "clean = name.strip() # "Ada Lovelace"upper = name.upper() # " ADA LOVELACE "swapped = name.replace("Ada", "Grace")Each method returns a new string. The original is unchanged.
if / elif / else
if minutes < 15: print("Short session.")elif minutes <= 90: print("Solid session.")else: print("Long session.")Common notes:
<is strict,<=includes the boundary.elifchains continue checking only if previous conditions failed.elseruns when all of the above were false.
Boolean Operators
minutes = 45answer = "quit"
if minutes >= 15 and minutes <= 90: print("Solid session.")
if answer == "done" or answer == "quit": print("Finished.")and, or, and not combine boolean expressions.
for Loop Over a List
subjects = ["Math", "Physics", "History"]for subject in subjects: print(subject)The loop variable (subject) is set to each item in turn.
for Loop with range
for i in range(5): print(i)This prints 0, 1, 2, 3, 4. range(n) produces numbers from 0 up to but not including n. range(start, end) and range(start, end, step) are also available.
while Loop
while True: answer = input("Subject (or 'done' to finish): ").strip().lower() if answer == "done": break print(f"Logged: {answer}")while True: runs until something inside the loop ends it. break ends the loop immediately.
Common List Operations
minutes_list = [45, 30, 60]
# Lengthn = len(minutes_list) # 3
# Access by indexfirst = minutes_list[0] # 45last = minutes_list[-1] # 60
# Add an item to the endminutes_list.append(15)
# Check membership"Math" in subjects # True or False
# Sum, max, mintotal = sum(minutes_list)longest = max(minutes_list)shortest = min(minutes_list)max and min raise ValueError on an empty list.
Defining a Function
def classify_session(minutes): """Return a short label for a session length.""" if minutes < 15: return "short" elif minutes <= 90: return "solid" else: return "long"Common notes:
defintroduces a function definition.- The parameter
minutesis local to the function. - The function ends as soon as a
returnruns. - The triple-quoted string just below
defis a docstring: a short description of what the function does.
Calling a Function
label = classify_session(45)print(label) # "solid"Returning More Than One Value
def get_session(): subject = input("Subject: ").strip().lower() minutes = int(input("Minutes: ").strip()) return subject, minutes
subject, minutes = get_session()The function returns a tuple; the caller unpacks it into two variables.
Testing a Function with assert
def total_minutes(minutes_list): total = 0 for m in minutes_list: total += m return total
assert total_minutes([]) == 0assert total_minutes([45]) == 45assert total_minutes([45, 30, 60]) == 135print("All tests passed.")Each assert checks a specific case. The empty case and the single-element case are often the most informative.
Raising an Exception
def average_minutes(minutes_list): if len(minutes_list) == 0: raise ValueError("cannot average an empty list") return sum(minutes_list) / len(minutes_list)Raise an exception when a function receives input it cannot handle.
Catching an Exception with try / except
while True: minutes_text = input("Minutes: ").strip() try: minutes = int(minutes_text) break except ValueError: print("Please enter a whole number.")Catch specifically (except ValueError:), not broadly. A bare except: is almost always a bug.
Reading an Error
When Python prints a traceback:
Traceback (most recent call last): File "main.py", line 3, in <module> minutes = int("forty-five")ValueError: invalid literal for int() with base 10: 'forty-five'Read the last line first: the exception type (ValueError) and the message tell you what went wrong. The lines above show where in the program it happened.
Clause Patterns at a Glance
A program with input, branching, looping, and a function call looks roughly like this:
def classify_session(minutes): if minutes < 15: return "short" elif minutes <= 90: return "solid" else: return "long"
while True: subject = input("Subject (or 'done'): ").strip().lower() if subject == "done": break minutes = int(input("Minutes: ").strip()) label = classify_session(minutes) print(f" {label.capitalize()} session on {subject}.")Three patterns are visible at once: a function definition, a while True: loop with a break, and an if/elif/else chain inside the function.
Safe Working Habits
- Read each line carefully before running it.
- Predict the output before pressing run.
- For loops, predict what happens on the empty input.
- For conditions, predict what happens at the exact boundary.
- Use
try/exceptaround input that may be malformed; raise exceptions for inputs you do not want to handle. - Run tests after every change that could break something.
- When a piece of code surprises you, simplify it until the surprise goes away.