Week 2 Code Examples

Python Fundamentals — Variables, Conditionals, Loops & Input

This page walks through every lecture topic from Week 2 with working code examples. These are the building blocks of every Python program you'll ever write — getting these solid now pays off all semester.

How to use this page: Copy any example into a .py file and run it. Change the values and see what happens — that's the fastest way to build intuition.

1. Variables and Data Types

A variable is a named container that stores a value. Python figures out the data type automatically based on what you assign.

Key concept: Variables are how programs remember things. Every piece of information your program works with — a name, a score, a yes/no answer — lives in a variable.

The four basic types

name = "Alice" # str — text, always in quotes age = 17 # int — whole number height = 5.6 # float — decimal number is_ready = True # bool — True or False (capital T/F, no quotes) print(name) # Alice print(age) # 17 print(height) # 5.6 print(is_ready) # True # Check what type a variable is print(type(name)) # print(type(age)) # print(type(is_ready)) #

Variables can change

score = 0 print(score) # 0 score = score + 10 # add 10 to whatever score currently is print(score) # 10 score += 5 # shorthand for score = score + 5 print(score) # 15 score -= 3 print(score) # 12
Common mistake: score = score + 1 is NOT the same as math's "score equals score plus one." In Python, the right side is evaluated first, then stored in the variable on the left. So it means "take the current value of score, add 1, and store the result back in score."

Type conversion

input() always returns a string — even if the user types a number. Use int() or float() to convert.

raw = "42" # this is the string "42", NOT the number 42 number = int(raw) # now it's the integer 42 print(raw + raw) # "4242" — string concatenation! print(number + number) # 84 — numeric addition # The typical pattern for numeric input: age_str = input("How old are you? ") # returns a string age = int(age_str) # convert to int so you can do math print(f"Next year you'll be {age + 1}")

2. String Formatting

f-strings (formatted string literals) let you embed variables directly inside a string. Put an f before the opening quote and use {curly braces} around any variable or expression.

name = "Bob" score = 87 grade = "B+" # Old way — error-prone and hard to read print("Hello " + name + ", you scored " + str(score) + " (" + grade + ")") # f-string — clean and readable print(f"Hello {name}, you scored {score} ({grade})") # Expressions work too — not just variables print(f"Double your score: {score * 2}") print(f"Your name has {len(name)} letters")

Formatting numbers

price = 4.9999 balance = 1234567.5 print(f"Price: ${price:.2f}") # Price: $5.00 (2 decimal places) print(f"Balance: ${balance:,.2f}") # Balance: $1,234,567.50 (commas + 2dp) print(f"Percent: {0.876:.1%}") # Percent: 87.6%

3. Boolean Logic and Comparisons

Comparisons produce True or False. These are the building blocks of every decision your program makes.

x = 10 print(x == 10) # True — equal to print(x != 5) # True — not equal to print(x > 8) # True — greater than print(x < 8) # False — less than print(x >= 10) # True — greater than or equal to print(x <= 10) # True — less than or equal to
Watch out: = assigns a value. == compares two values. Using = when you mean == is one of the most common beginner bugs.

Combining conditions with and / or / not

age = 20 has_id = True # and — both must be True print(age >= 18 and has_id) # True # or — at least one must be True print(age < 16 or has_id) # True # not — flips True to False and vice versa print(not has_id) # False # Real-world example temperature = 72 is_raining = False if temperature > 65 and not is_raining: print("Good weather for a walk!") else: print("Maybe stay inside.")

4. If / Elif / Else — Making Decisions

Conditionals let your program take different paths based on a condition. Python uses indentation (4 spaces) to define what's inside each branch.

Key concept: Only one branch runs. Python checks conditions top to bottom and executes the first one that is True, then skips the rest.

Basic if / elif / else

score = 82 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") # ← this runs because 82 >= 80 elif score >= 70: print("Grade: C") else: print("Grade: F") # Only ONE of these prints — the first true condition wins

Nested conditionals

age = 20 has_ticket = True if age >= 18: if has_ticket: print("Welcome — enjoy the show!") else: print("You're old enough, but you need a ticket.") else: print("Sorry, this event is 18+.")

Checking membership with in

valid_colors = ["red", "green", "blue"] choice = "green" if choice in valid_colors: print(f"{choice} is a valid color") else: print(f"{choice} is not valid")

5. Getting User Input

input() pauses the program, shows a prompt, and waits for the user to type something and press Enter. It always returns a string.

name = input("What is your name? ") print(f"Hello, {name}!") # Validate input — keep asking until they give something valid color = input("Pick red, green, or blue: ").lower() while color not in ["red", "green", "blue"]: print("That's not a valid choice.") color = input("Pick red, green, or blue: ").lower() print(f"You picked {color}.")

Input validation in action

This pattern — ask, validate, loop back if invalid — is something you'll use constantly. Here it is with a numeric input:

while True: raw = input("Enter a number between 1 and 10: ") try: number = int(raw) if 1 <= number <= 10: break # valid — exit the loop else: print("Out of range. Try again.") except ValueError: print("That's not a number. Try again.") print(f"You entered: {number}")

6. While Loops — Repeating Until a Condition is Met

A while loop keeps running its body as long as the condition is True. Use it when you don't know in advance how many times you'll need to loop.

Key concept: The loop checks its condition before every iteration. As soon as the condition becomes False, the loop stops and Python moves on.

Basic while loop

countdown = 5 while countdown > 0: print(f"T-minus {countdown}...") countdown -= 1 # IMPORTANT: always move toward the exit condition print("Liftoff!") # Output: # T-minus 5... # T-minus 4... # T-minus 3... # T-minus 2... # T-minus 1... # Liftoff!
Infinite loops: If the condition never becomes False, the loop runs forever and freezes your program. Always make sure something inside the loop moves you toward the exit condition. Press Ctrl+C to stop a runaway loop.

while True with break

A common pattern: loop forever on purpose, and use break to exit when you're ready.

total = 0 count = 0 while True: raw = input("Enter a number (or 'done' to stop): ") if raw.lower() == "done": break # exit the loop immediately total += int(raw) count += 1 if count > 0: print(f"Sum: {total}, Average: {total / count:.1f}") else: print("No numbers entered.")

7. The random Module

Python's random module generates unpredictable values — essential for games, simulations, and testing.

import random # random.randint(a, b) — random integer between a and b, inclusive dice = random.randint(1, 6) print(f"You rolled a {dice}") # random.choice(list) — pick one item from a list at random options = ["heads", "tails"] flip = random.choice(options) print(f"Coin flip: {flip}") # random.random() — random float between 0.0 and 1.0 chance = random.random() print(f"Random float: {chance:.4f}") # random.shuffle(list) — shuffle a list in place deck = ["Ace", "King", "Queen", "Jack", "10"] random.shuffle(deck) print(f"Shuffled deck: {deck}")

8. Putting It All Together — A Complete Example

Here's a number guessing game that uses variables, input, conditionals, a while loop, and random together. Notice how each concept plays its own role.

import random secret = random.randint(1, 20) # computer picks a number guesses = 0 max_guesses = 5 print("I'm thinking of a number between 1 and 20.") print(f"You have {max_guesses} guesses.") while guesses < max_guesses: raw = input("\nYour guess: ") try: guess = int(raw) except ValueError: print("Please enter a whole number.") continue # skip the rest of this loop iteration, go back to top guesses += 1 remaining = max_guesses - guesses if guess == secret: print(f"Correct! You got it in {guesses} guess(es).") break elif guess < secret: print(f"Too low. {remaining} guess(es) left.") else: print(f"Too high. {remaining} guess(es) left.") else: # The 'else' on a while loop runs only if the loop finished naturally (no break) print(f"\nOut of guesses! The number was {secret}.") # Output (example run): # I'm thinking of a number between 1 and 20. # You have 5 guesses. # # Your guess: 10 # Too high. 4 guess(es) left. # # Your guess: 5 # Too low. 3 guess(es) left. # # Your guess: 7 # Correct! You got it in 3 guess(es).
Notice: The try/except block handles bad input gracefully. The continue keyword skips the rest of the loop body when input is invalid. The break keyword exits immediately when the player wins. These small tools make programs much more robust.