👋 Welcome to Python!
You're about to learn one of the most powerful—and surprisingly friendly—programming languages in the world. Python isn't just for computer scientists in lab coats. It's the language that data analysts use to find patterns in millions of customer transactions, that automation engineers use to eliminate hours of repetitive work, and that machine learning engineers use to build recommendation systems you interact with every day.
Here's what makes this journey different: You're not starting with abstract theory. You're learning Python the way professionals actually use it—through real problems, relatable examples, and hands-on practice. By the end of this week, you'll write programs that actually do useful things. By Week 12, you'll have portfolio projects that prove to employers you can solve real problems with code.
Job Market Stats: Python is the #2 most in-demand programming language (after JavaScript). Over 50,000 Python developer jobs are posted monthly in the US alone, with entry-level salaries starting at $60K-$80K.
What Companies Want:
- Data Analysts at Amazon, Netflix, Spotify use Python daily to analyze user behavior and make data-driven decisions
- Automation Engineers at tech startups write Python scripts that save companies thousands of hours annually
- Machine Learning Engineers at Google, Meta, Tesla use Python libraries (TensorFlow, PyTorch) to build AI systems
- Backend Developers at Instagram, Pinterest, Dropbox use Python frameworks (Django, Flask) to power web applications serving millions
The Bottom Line: Learning Python isn't just about "knowing how to code." It's about qualifying for careers with economic stability, growth potential, and the flexibility to work remotely. Companies value Python skills because Python solves real problems efficiently.
By the end of Week 1, you'll be able to:
- Set up a professional Python development environment (Python 3.9+, pip, VS Code) on your computer
- Write and run Python scripts that use variables, data types, and operators to perform calculations
- Control program flow with if/elif/else statements and for/while loops to make decisions and repeat actions
- Define and call functions with parameters and return values to organize reusable code
- Debug programs using print statements, error messages, and try/except blocks
- Portfolio Outcome: Create your first Python script that you can showcase on GitHub to demonstrate foundational programming skills
name = "Alice"
def function_name():
for loops iterate over sequences, while loops repeat until a condition is false.
try/except blocks to prevent crashes.
Think of programming like learning to cook:
- Variables = Labeled Containers: Just like you store flour in a labeled jar and milk in a labeled carton, variables store different types of data with names you choose:
player_score = 100oruser_name = "Alex" - Functions = Recipes: A recipe takes ingredients (inputs), follows steps, and produces a dish (output). A function takes parameters, executes code, and returns a result. Both are reusable—you don't rewrite the recipe every time you cook!
- Loops = Repetitive Tasks: Chopping 10 onions? You repeat the same action 10 times. In Python,
for i in range(10):repeats code 10 times without typing it 10 times - If/Else = Decision Points: "If the sauce is too salty, add sugar. Else, add more salt." Programming uses the same logic:
if temperature > 100:then do this,else:do that - Debugging = Taste Testing: Professional cooks taste as they go and adjust. Programmers test code frequently, read error messages (the "taste"), and fix issues before serving the final product
The Point: Programming isn't mystical or impossible. It's logical problem-solving using tools that, once you learn the basics, become second nature. You're not trying to memorize everything—you're building a mental model of how things work, just like you did when you learned to cook, drive, or use a smartphone.
Python's Philosophy: "Code should be readable, simple, and beautiful." If you can read English, you can often guess what Python code does. Compare Python to other languages:
if age >= 18:
print("You can vote!")
This does exactly what it reads: "If age is greater than or equal to 18, print 'You can vote!'" No cryptic symbols, no confusing syntax. Python reads like English with punctuation.
Real-World Applications (Where the Jobs Are):
- Data Analysis (Entry: $60K-$75K): Netflix analyzes billions of viewing records with Python to decide which shows to produce. Retail analysts use Python to predict inventory needs and optimize pricing.
- Automation (Entry: $55K-$70K): Companies hire Python developers to write scripts that automate repetitive tasks—data entry, file processing, email reports—saving thousands of employee hours yearly.
- Web Development (Entry: $65K-$85K): Instagram, Pinterest, and Spotify are built with Python frameworks. Web developers use Django and Flask to build backends that handle millions of users.
- Machine Learning (Mid-Level: $90K-$120K): Self-driving cars, recommendation systems (Amazon, YouTube), fraud detection (credit cards)—all powered by Python libraries like TensorFlow and scikit-learn.
Career Path Example: Start as Data Analyst → Learn pandas, SQL, visualization → Transition to Data Engineer → Specialize in Machine Learning. Many of our graduates land $60K+ roles within 6 months of completing this program.
You're not in college anymore. Adult learners succeed differently than traditional students. Here's what works:
1. Type Every Example (Don't Copy-Paste)
Your fingers need to learn Python syntax just like they learned to text without looking. Typing print("Hello") 50 times builds muscle memory. Copy-pasting teaches you nothing.
2. Break Things on Purpose
Change examples and see what happens. Forget a colon? Remove indentation? Add extra parentheses? Every error message is a learning opportunity. Pro developers break code all day—it's called "testing edge cases."
3. Use the Interactive Python Shell
Type python in your terminal and hit Enter. Now you can test ideas instantly: >>> 5 + 3 → 8. No need to create files for every experiment. Think of it as a calculator that speaks Python.
4. Read Error Messages (They're Helpful, I Promise)
Python tells you exactly what went wrong and on which line. SyntaxError: invalid syntax (line 5) means "check line 5 for a typo." Compare this to real life: imagine if your car broke down and the dashboard said "Engine problem, check spark plug 3." That's Python's error messages!
5. Ask Questions (No Shame, Only Growth)
Stuck for 15 minutes? Ask on Slack. Every developer—even 20-year veterans—uses Google, Stack Overflow, and colleagues constantly. Programming is collaborative problem-solving, not solitary genius.
6. Study in Short Bursts (Not Marathon Sessions)
Your brain absorbs programming better in 25-minute focused sessions with 5-minute breaks. Three 30-minute sessions (morning, lunch, evening) beats one 6-hour cramming session. You're working full-time and have responsibilities—optimize for retention, not hours logged.
⚙️ Environment Setup
Before we code, let's set up your development environment.
1. Install Python
Download Python from python.org. This course requires Python 3.9 or newer.
# Verify Python installation
python --version
# Output: Python 3.11.5
# Or on some systems:
python3 --version
- PATH Not Set (Windows): During installation, check "Add Python to PATH". Without it, terminal won't find
pythoncommand. - Python 2 vs Python 3: Python 2 is deprecated. Always use Python 3. Check version with
python --version. - Multiple Python Versions: If
pythonpoints to Python 2, usepython3command explicitly. - VS Code Not Finding Python: Install Python extension from VS Code marketplace and select the correct interpreter (Ctrl+Shift+P → "Python: Select Interpreter").
2. Install pip
pip is Python's package installer, included with Python 3.4+.
# Verify pip installation
pip --version
# Output: pip 23.2.1 from ...
# Or on some systems:
pip3 --version
3. Install VS Code
Visual Studio Code is a free, powerful code editor. Download from code.visualstudio.com.
Recommended Extensions:
- Python (by Microsoft) - Essential for Python development
- Pylance - Advanced language server for better IntelliSense
- Code Runner - Run Python files with a single click
4. Your First Python Program
Let's verify everything works by creating and running your first Python script!
# My first Python program
# Save this as hello.py and run it
print("Hello, Python!")
print("Welcome to Code the Dream!")
print("You just wrote your first program 🎉")
# Let's do some math
print("Quick math:", 42 + 8) # Should print 50
Step 1: Create a new file in VS Code called hello.py
Step 2: Type the code above (don't copy-paste!)
Step 3: Run it using one of these methods:
- Click the "Run" button (▶️) in VS Code top-right
- Right-click in editor → "Run Python File in Terminal"
- In terminal:
python hello.py
Success! If you see output, you're ready for Week 1!
Modify your script to:
- Print your name instead of "Python"
- Print today's date
- Calculate your birth year (current year - your age)
- Print a fun fact about yourself
💡 This is your first GitHub-worthy code! Save it and we'll push it to GitHub later.
5. Interactive Python Shell
The Python shell is your playground for experimenting with code instantly.
# Start the interactive shell
> python
Python 3.11.5 (main, Sep 11 2023, 13:54:46)
>>> 5 + 3
8
>>> "Hello" + " World"
'Hello World'
>>> len("Python")
6
>>> exit() # Exit the shell
Pro Tip: Use the shell for quick experiments—test ideas before writing full scripts. Type help(function_name) to learn about any function!
🔤 Python Basics
Let's write your first Python code! Think of this section as learning the alphabet before writing sentences. You'll learn how to store information (variables), understand what type of information you're working with (data types), and perform calculations (operators).
Every program you'll ever write—web apps, data pipelines, automation scripts—stores and manipulates data. User profiles on Instagram? Variables storing names, photos, follower counts. Shopping carts on Amazon? Variables tracking items, prices, quantities. Salary calculators? Variables holding hourly rates, hours worked, tax percentages.
On the job: Data analysts store CSV data in variables to analyze sales trends. Backend developers store user login info in variables to validate credentials. Machine learning engineers store millions of data points in variables to train models. This is day-one, fundamental stuff—but it's what separates "can code a little" from "can build production systems."
Variables & Data Types: The Building Blocks
Analogy: Variables are Labeled Boxes
Imagine you're organizing a storage unit. You have boxes labeled "Winter Clothes," "Tax Documents 2024," "Birthday Decorations." Each box holds different types of items, and the label tells you what's inside without opening it.
Variables work the same way: player_name is a box labeled "player_name" that stores text. player_score is another box storing a number. Python remembers what's in each box, so you can use that data later.
# Variables - storing data in labeled "boxes"
name = "Alice" # str (string) - text data
age = 25 # int (integer) - whole numbers
height = 5.6 # float (decimal) - numbers with decimals
is_student = True # bool (boolean) - True or False
# Print to console - see what's stored
print(f"Name: {name}") # Output: Name: Alice
print(f"Age: {age}") # Output: Age: 25
print(f"Is student: {is_student}") # Output: Is student: True
What just happened? You created four variables and printed their values. The f before the string makes it an "f-string" (formatted string), which lets you embed variables inside curly braces {}. This is how modern Python displays dynamic data.
# User profile data (like what Instagram stores)
username = "@coder_alex"
followers = 1523
avg_likes_per_post = 87.5
verified_account = False
# Display profile summary
print(f"Profile: {username}")
print(f"Followers: {followers}")
print(f"Avg Likes: {avg_likes_per_post}")
print(f"Verified: {verified_account}")
# Change data (variables are mutable - they can change)
followers = 1524 # Someone new followed!
print(f"Updated Followers: {followers}")
Real-World Connection: Every social media app stores millions of user profiles exactly like this. Instagram has variables for each user storing username, bio, follower count, post data, etc. When you follow someone, the backend code updates their followers variable. This is literally how tech companies build features.
# E-commerce shopping cart calculation
item_name = "Wireless Mouse"
item_price = 24.99
quantity = 2
tax_rate = 0.08 # 8% sales tax
free_shipping = True
# Calculate costs
subtotal = item_price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
# Display receipt
print(f"=== RECEIPT ===")
print(f"Item: {item_name}")
print(f"Price: ${item_price} x {quantity}")
print(f"Subtotal: ${subtotal:.2f}") # .2f = 2 decimal places
print(f"Tax (8%): ${tax:.2f}")
print(f"Total: ${total:.2f}")
print(f"Free Shipping: {free_shipping}")
# Output:
# === RECEIPT ===
# Item: Wireless Mouse
# Price: $24.99 x 2
# Subtotal: $49.98
# Tax (8%): $4.00
# Total: $53.98
# Free Shipping: True
Portfolio Moment: This is interview-worthy code. You just demonstrated you understand variables, data types, arithmetic operations, and formatted output—skills every entry-level developer needs. Add this to GitHub with comments explaining your logic.
Challenge: Create variables for your monthly income and expenses (rent, food, transportation, entertainment). Calculate total expenses and remaining money. Print a formatted budget summary.
Starter Code:
# Your monthly budget
monthly_income = 3500
rent = 1200
food = ? # Fill in your estimate
transportation = ?
entertainment = ?
# Calculate total expenses and remaining
# (You write this part!)
# Print budget summary
# (You write this part!)
Goal: Get comfortable creating variables, doing math, and printing results. Spend 5-10 minutes experimenting. There's no "wrong" answer—this is practice!
💡 Hint: You'll need addition (+) and subtraction (-) operators. Look at the shopping cart example above for formatting tips.
| Type | Example | When to Use |
|---|---|---|
str |
"Hello", 'Python' |
Text, names, messages, anything with letters |
int |
42, -17, 0 |
Whole numbers, counts, ages, quantities |
float |
3.14, -0.5, 2.0 |
Decimals, prices, measurements, percentages |
bool |
True, False |
Yes/no questions, on/off states, conditions |
Pro Tip: Use type(variable_name) to check what type a variable is. Example: type(age) returns <class 'int'>. Useful when debugging!
Operators: Making Python Do Math (and Logic)
Think of operators as action words: + means "add these," > means "is this bigger?", == means "are these equal?" Just like English has verbs (run, jump, eat), Python has operators that perform actions on data.
# Arithmetic operators - Python as calculator
x = 10
y = 3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.333... (always returns float)
print(x // y) # Floor division: 3 (rounds down to nearest integer)
print(x % y) # Modulo (remainder): 1 (10 ÷ 3 = 3 remainder 1)
print(x ** y) # Exponent: 1000 (10^3 = 10 × 10 × 10)
Real-World Use Case: Modulo (%) is super useful for checking if numbers are even/odd (num % 2 == 0 means even), or for rotating through lists (like displaying 7 days of the week in cycles).
# Comparison operators - return True or False
age = 25
voting_age = 18
print(age > voting_age) # True (25 is greater than 18)
print(age < voting_age) # False (25 is not less than 18)
print(age >= 25) # True (25 is greater than or equal to 25)
print(age <= 30) # True (25 is less than or equal to 30)
print(age == 25) # True (age IS equal to 25)
print(age != 30) # True (age is NOT equal to 30)
⚠️ Common Mistake: = assigns values (age = 25 means "set age to 25"). == compares values (age == 25 means "is age equal to 25?"). Mixing these up causes bugs!
# E-commerce discount logic
customer_age = 22
is_premium_member = True
purchase_amount = 150.00
# Business rules: 10% discount if premium OR spent over $100
qualifies_for_discount = is_premium_member or (purchase_amount > 100)
print(f"Customer Age: {customer_age}")
print(f"Premium Member: {is_premium_member}")
print(f"Purchase Amount: ${purchase_amount}")
print(f"Qualifies for Discount: {qualifies_for_discount}") # True
# Calculate discount
if qualifies_for_discount:
discount = purchase_amount * 0.10
final_price = purchase_amount - discount
print(f"Discount Applied: ${discount:.2f}")
print(f"Final Price: ${final_price:.2f}")
Career Connection: This is exactly how e-commerce backends work. Amazon, eBay, Shopify—all use comparison operators and boolean logic to determine pricing, shipping costs, tax rates, and promotional eligibility. You're learning production-level logic patterns.
Challenge: You're dining out. The bill is $67.50. Calculate a 18% tip and the total amount you'll pay. Then calculate a 20% tip to compare.
Requirements:
- Create a variable for the bill amount
- Calculate tip at 18% (multiply by 0.18)
- Calculate total (bill + tip)
- Print results with 2 decimal places:
${amount:.2f} - Bonus: Compare 18% vs 20% tip amounts
💡 Real-World Skill: This type of calculation appears in payment processing systems, invoice generators, and financial apps. Employers value candidates who can break down real problems into code.
- Naming Variables: Use descriptive names.
ageis better thana. Can't start with numbers or use spaces. - = vs ==:
=assigns values (x = 5).==compares values (x == 5is True/False). - Type Confusion:
"5" + 5causes TypeError. String + integer doesn't work. Convert:int("5") + 5. - Indentation Matters: Python uses indentation (4 spaces recommended) to define code blocks. Inconsistent indentation causes errors.
🔀 Control Flow
Control flow statements let your program make decisions and repeat actions.
Think of if/elif/else like a role‑playing game dialogue tree. The player’s choice and stats decide which branch runs. If you have enough XP, you unlock a special response; if not, you follow a different path. Programs do the same: they evaluate conditions and branch to the matching outcome.
Conditional Statements (if/elif/else)
age = 18
if age >= 18:
print("You can vote!")
elif age >= 16:
print("You can drive!")
else:
print("You're still young!")
# Age verification with multiple thresholds
age = 20
if age >= 21:
print("Full access: vote, drive, and purchase alcohol.")
elif age >= 18:
print("Access: vote and drive.")
elif age >= 16:
print("Access: learner’s permit to drive.")
else:
print("Access: supervised activities only.")
# Grade calculator: A/B/C/D/F
score = 87
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
else:
letter = 'F'
print(f"Letter grade: {letter}")
# Tiered discounts: membership + purchase amount
is_premium = True
amount = 180.00
if is_premium and amount >= 150:
discount = 0.20
elif is_premium:
discount = 0.15
elif amount >= 100:
discount = 0.10
else:
discount = 0.00
final = amount * (1 - discount)
print(f"Discount: {discount*100:.0f}% | Total: ${final:.2f}")
Loops
# for loop - iterate over a sequence
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# range() - generate numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# while loop - repeat until condition is False
count = 0
while count < 5:
print(count)
count += 1
# break - exit loop early
for i in range(10):
if i == 5:
break # Stop at 5
print(i)
# continue - skip to next iteration
for i in range(5):
if i == 2:
continue # Skip 2
print(i) # Prints 0, 1, 3, 4
Convert Celsius to Fahrenheit and back. Requirements:
- Ask for a number input in Celsius
- Compute Fahrenheit:
F = C * 9/5 + 32 - Print both values with two decimals
- Bonus: Support Fahrenheit input and convert to Celsius
The Classic Interview Question: Print numbers 1 to 20, but:
- For multiples of 3, print "Fizz"
- For multiples of 5, print "Buzz"
- For multiples of both, print "FizzBuzz"
Expected Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz
💡 Hint: Use % (modulo) to check divisibility. Order matters—check "both" first!
Build a simple game:
- The computer picks a random number 1-10
- The player guesses until correct
- Give hints: "Too high!" or "Too low!"
- Count and display number of guesses
Starter Code:
import random
secret = random.randint(1, 10)
guess_count = 0
# Your code here: while loop, get input, compare, give hints
Advanced Exercise: Check if a password meets security requirements.
- At least 8 characters long
- Contains at least one digit
- Contains at least one uppercase letter
- Rate as: "Weak", "Medium", or "Strong"
💡 Hint: Use any(c.isdigit() for c in password) to check for digits
Open notebook-sessions/week1/session1_intro_to_python.ipynb and implement the grade calculator and discount tiers with your own values.
Tiered pricing logic powers promotions at Amazon and Target. Age and eligibility checks appear in fintech onboarding flows. Control flow decisions like these run on every checkout and registration pipeline.
- Infinite Loops:
while True:loops forever unless youbreak. Always ensure condition becomes False eventually. - Forgetting Colons: Every
if,for,whileneeds a colon:at the end. Python won't work without it. - Indentation Errors: Code inside if/for/while must be indented (4 spaces). Mixed tabs/spaces cause errors.
- range() Exclusivity:
range(5)gives 0-4, not 0-5. Upper bound is exclusive.
⚡ Functions
Functions are reusable blocks of code that perform specific tasks.
A function is a recipe. Ingredients are parameters you pass in, the steps are the function body, and the dish is the value you return. Printing is like shouting in the kitchen—no one can reuse that result. Returning is plating the dish so other parts of your program can serve it.
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call the function
message = greet("Alice")
print(message) # Hello, Alice!
# Function with multiple parameters
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Default parameters
def greet_with_time(name, time="day"):
return f"Good {time}, {name}!"
print(greet_with_time("Bob")) # Good day, Bob!
print(greet_with_time("Bob", "morning")) # Good morning, Bob!
# Progressive: calculator functions
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def calc_tax(amount, rate=0.08):
return amount * rate
total = add(50, 20)
tax = calc_tax(total)
print(f"Total: ${total:.2f} | Tax: ${tax:.2f}")
# Data validation: return vs print
def is_valid_email(email):
return '@' in email and '.' in email
result = is_valid_email('alice@example.com')
if result:
print("Email looks valid.")
else:
print("Please check the address.")
Create calc_total_with_tax(subtotal, rate) that returns the final amount. Requirements:
- Default tax rate 8%
- Round to two decimals
- Return the value (don’t print)
- Bonus: Validate inputs are numbers
Create functions for basic math operations:
add(a, b)- returns a + bsubtract(a, b)- returns a - bmultiply(a, b)- returns a * bdivide(a, b)- returns a / b (handle division by zero!)
# Local vs Global Variables
message = "I'm global" # Global - accessible everywhere
def greet():
message = "I'm local" # Local - only inside this function
print(message)
greet() # Output: I'm local
print(message) # Output: I'm global
# Functions can return multiple values
def get_stats(purchases):
total = sum(purchases)
count = len(purchases)
return total, count
purchases = [29.99, 49.99, 9.99]
total, count = get_stats(purchases)
print(f"Total: ${total:.2f}, Items: {count}")
Build a BMI calculator: Create calculate_bmi(weight_kg, height_m) and get_bmi_category(bmi) to categorize as Underweight/Normal/Overweight/Obese.
Open notebook-sessions/week1/session1_intro_to_python.ipynb and build the calculator and validation examples with your own data.
- Forgetting return: Without
return, function returnsNone. Usereturnto send values back to caller. - Calling Before Definition: Define functions before you call them. Python reads top-to-bottom.
- Mutable Default Arguments: Don't use
def func(items=[]):. The list is shared across calls, causing bugs. UseNoneinstead. - Parameter Order: Required parameters must come before optional (default) parameters in definition.
🐛 Debugging & Error Handling
Even the best programmers write code with bugs. Learning to debug is a critical skill!
Debugging is detective work: collect clues (error messages), form a hypothesis, run experiments, and confirm the culprit. It’s also like medicine: symptoms → diagnosis → treatment. Read the traceback, isolate the issue, and apply the fix.
Error Handling with try/except
# Handle errors gracefully
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
Common Error Types and Fixes
| Error | Cause | Fix |
|---|---|---|
| SyntaxError | Missing colon, bad indentation | Add :, use 4‑space indentation |
| TypeError | Wrong types (e.g., string + int) | Convert types: int("5") + 5 |
| NameError | Variable not defined | Define before use; check spelling |
| ZeroDivisionError | Dividing by zero | Guard inputs; handle 0 explicitly |
| ValueError | Invalid conversion (e.g., int('abc')) | Validate input; wrap in try/except |
Debugging with Print Statements
def calculate_average(numbers):
print(f"DEBUG: numbers = {numbers}") # See what we're working with
total = sum(numbers)
print(f"DEBUG: total = {total}") # Check intermediate result
count = len(numbers)
print(f"DEBUG: count = {count}") # Verify count
average = total / count
return average
result = calculate_average([5, 10, 15])
print(f"Average: {result}")
Read the Error Message: Python tells you what went wrong and on which line. Start there!
Use Print Statements: Add print() to see variable values at different points in your code.
Check Your Assumptions: Is the variable what you think it is? Print it and verify.
Divide and Conquer: Comment out half your code. If error disappears, the bug is in the commented part.
Google the Error: Copy-paste error messages into Google. Chances are someone else solved it!
Open notebook-sessions/week1/session2_intro_to_python_group.ipynb and collaboratively reproduce error types, then document fixes.
❌ Common Mistakes
❌ Wrong:
def add(a, b):
print(a + b) # prints but returns None
✅ Correct:
def add(a, b):
return a + b # returns value to caller
❌ Wrong:
def append_item(item, items=[]):
items.append(item)
return items
✅ Correct:
def append_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
❌ Wrong:
total = "5" + 5
✅ Correct:
total = int("5") + 5 # convert string to int
✅ Best Practices
- Use descriptive snake_case names:
total_price,customer_count. - Write small, single-purpose functions; avoid side effects.
- Return values instead of printing inside functions.
- Validate inputs and handle errors with
try/except. - Prefer f-strings for formatting:
f"Total: {total:.2f}". - Consistent 4-space indentation; follow PEP 8 basics.
- Use
pathlibfor cross-platform file paths.
🛠️ Mini-Project: Username Validator
Goal: Build a CLI tool that validates usernames for a registration system.
Requirements:
- Minimum length 3 characters
- Alphanumeric only (letters and numbers)
- Clear feedback messages
- Bonus: Retry loop until valid; collect summary
def validate_username(username):
if len(username) < 3:
return False, "Username must be at least 3 characters"
if not username.isalnum():
return False, "Username can only contain letters and numbers"
return True, "Valid username!"
name = input("Enter a username: ")
ok, msg = validate_username(name)
print(msg)
Example Output: Username must be at least 3 characters or Valid username!
📜 Week 1 Cheat Sheet
# ═══ VARIABLES ═══
name = "Alice"
age = 25
height = 5.6
is_student = True
# ═══ OPERATORS ═══
x + y # Addition
x - y # Subtraction
x * y # Multiplication
x / y # Division
x // y # Floor division
x % y # Modulo (remainder)
x ** y # Exponent
# ═══ CONTROL FLOW ═══
if condition:
# do something
elif other_condition:
# do something else
else:
# do default
for item in sequence:
# repeat for each item
while condition:
# repeat while True
# ═══ FUNCTIONS ═══
def function_name(param1, param2="default"):
# do something
return result
# ═══ ERROR HANDLING ═══
try:
# risky code
except ErrorType:
# handle error
- Python is Readable: Code should be clear and easy to understand. Use descriptive variable names.
- Indentation Matters: Python uses indentation (4 spaces) to define code blocks. Consistency is critical.
- Variables Store Data: Use variables to store values you'll use later. Choose meaningful names.
- Functions Make Code Reusable: Write once, use many times. Functions should do one thing well.
- Errors Are Normal: Read error messages carefully. They tell you what's wrong and where.
- Print for Debugging:
print()is your best debugging tool. Use it to inspect variable values. - Practice Daily: Programming is a skill. The more you practice, the better you get.
- Ask Questions: No question is too basic. Use Slack, forums, and your mentor for help.