In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook("02_python_basics.ipynb")
In [ ]:
# Validation: Check Python version and file location
import os
import sys

# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"

if current_version not in SUPPORTED_VERSIONS:
    raise EnvironmentError(
        f"Python version mismatch!\n"
        f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
        f"Found: {current_version}\n"
        f"Please use Python 3.12 or 3.13 for this course."
    )
print(f"Python version: {current_version}")

# Expected filename for this assignment
EXPECTED_FILE = "02_python_basics.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)

if required_path_segment not in current_path and not in_allowed_env:
    raise EnvironmentError(
        f"File location error!\n"
        f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
        f"Current location: {current_path}\n"
        f"Please move this file to the correct directory."
    )

# Verify directory name and filename (skip in grading/development environments)
if not in_allowed_env:
    if not os.path.exists(EXPECTED_FILE):
        notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
        raise EnvironmentError(
            f"Filename mismatch!\n"
            f"Expected: {EXPECTED_FILE}\n"
            f"Found notebooks: {notebooks}\n"
            f"Please rename your notebook to '{EXPECTED_FILE}'."
        )

print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")

Python Basics

Goal: Learn how to store data, handle different types of information, and interact with the user via input and output.

Programming comes down to two things:

  1. Data - Information we store in variables
  2. Actions - Things we do with that data (using functions)

Today we will learn the building blocks: how to display information, store it, and get it from users.


Comments: Notes for Humans

Before we dive in, let's learn about comments. A comment is a note in your code that Python ignores completely. Comments are for humans, not the computer.

Single-Line Comments

Use the # symbol to create a comment. Everything after # on that line is ignored:

# This is a comment - Python ignores this line
print("Hello")  # This comment is after code

Why Use Comments?

  1. Explain your thinking - Help others (and future you) understand your code
  2. Leave notes - Remind yourself what to do next
  3. Disable code temporarily - "Comment out" code to skip it without deleting it

Commenting Out Code

You can disable a line of code by putting # in front of it:

# print("This line will NOT run")
print("This line WILL run")

This is useful for testing or temporarily removing code without losing it.

In [ ]:
# This is a comment - Python skips this line completely
print("This line runs!")  # Comments can go after code too

# The line below is "commented out" - it will NOT run
# print("This line is disabled")

print("Done!")

1. Output: The print() Function

The print() function sends messages to the screen. It is how your program "talks" to the user (at least for now!).

Basic Syntax

print("Your message here")

The text inside the quotes is called a string. Let's try it:

In [ ]:
# Demo: A simple print statement
print("Welcome to CSC115")
In [ ]:
# You can print multiple things on separate lines
print("Line 1")
print("Line 2")
print("Line 3")

Different Ways to Print

There are several ways to combine text and data in print statements:

Method 1: Multiple Arguments (comma-separated)

Print automatically adds spaces between items.

In [ ]:
name = "Alex"
age = 19
print("Name:", name, "Age:", age)

Method 2: String Concatenation (using +)

You can glue strings together with +. Note: you must convert numbers to strings first.

In [ ]:
name = "Alex"
age = 19
print("Name: " + name + " Age: " + str(age))

Method 3: f-strings (RECOMMENDED)

f-strings are the modern, preferred way to format output in Python. Put an f before the opening quote, then use {curly braces} to insert variables directly.

f"Text {variable} more text"
In [ ]:
name = "Alex"
age = 19
print(f"Name: {name} Age: {age}")
In [ ]:
# f-strings can even do math inside the braces!
price = 4.50
quantity = 3
print(f"Total: ${price * quantity}")

Practice: Print Your Hometown

Run the cell below. There is no autograder here - just practice!

In [ ]:
# ✏️ Practice: Print a message about your hometown
# If you're from Miami, print something you like about it
# If you're not from Miami, print how many hours it takes to get here

# Example: print(f"I'm from Chicago, it takes about 3 hours to fly to Miami")
# Your code below:

2. Variables: Storing Information

A variable is like a labeled box that holds data. You create a variable using the = sign (called the assignment operator).

Syntax

variable_name = value

The name goes on the left, the value goes on the right.

In [ ]:
# Creating variables
course_name = "CSC115"
student_count = 30
is_fun = True

print(course_name)
print(student_count)
print(is_fun)

Reassigning Variables

You can change what a variable holds by assigning it a new value. The old value is replaced.

In [ ]:
score = 10
print(f"Score is: {score}")

score = 25  # Reassign to a new value
print(f"Score is now: {score}")

score = score + 5  # Use the old value to calculate the new value
print(f"After adding 5, score is: {score}")

Variable Naming Rules

  1. Must start with a letter or underscore (_)
  2. Can contain letters, numbers, and underscores
  3. Cannot contain spaces or special characters
  4. Cannot be a Python keyword (like if, for, while)
  5. Are case-sensitive (Name and name are different variables)

Reserved Words (Keywords)

Python has reserved words that have special meaning and cannot be used as variable names. These include:

False    True     None     and      or       not
if       else     elif     for      while    break
continue def      return   class    import   from
try      except   finally  raise    pass     lambda

If you try to use one of these as a variable name, Python will give you a syntax error.

Built-in Names to Avoid

In addition to reserved words, Python has built-in names for types and functions. These are not technically reserved, but using them as variable names will override their original meaning and cause confusing bugs:

Name What It Does Why Not to Use It
str The string type str = "hello" breaks str() conversion
int The integer type int = 5 breaks int() conversion
float The decimal type float = 3.14 breaks float() conversion
list The list type list = [1,2,3] breaks list() function
print Output function print = "hi" breaks print()
input Input function input = "test" breaks input()
type Type checker type = "string" breaks type()

Rule of thumb: If a name appears in a different color in your code editor, do not use it as a variable name.

Naming Convention: snake_case

In Python, we use snake_case for variable names: all lowercase with underscores between words.

# Good names (snake_case)
first_name = "Alex"
total_price = 19.99
is_student = True

# Bad names (avoid these)
FirstName = "Alex"      # This is called PascalCase, used for classes
totalPrice = 19.99      # This is called camelCase, used in other languages
x = "Alex"              # Too vague - what does x mean?
str = "Alex"            # Shadows the built-in str type!

Question 1: Create Variables

Create two variables:

  1. first_name - set it to your first name (as a string)
  2. current_year - set it to the current year (as a number, not a string)
In [ ]:
# ✏️ YOUR ANSWER HERE
first_name = ...
current_year = ...
In [ ]:
grader.check("q1_variables")

3. Data Types: Flavors of Data

Computers treat different kinds of data differently. The three basic types we will use are:

Type Name Example Description
str String "Hello" Text, always in quotes
int Integer 42 Whole numbers (no decimal)
float Float 3.14 Decimal numbers

Important: Quotes Matter!

  • "5" is a string (text that happens to look like a number)
  • 5 is an integer (an actual number you can do math with)

You can use single quotes 'Hello' or double quotes "Hello" for strings - both work the same. However, do not use backticks (`) - those do not create strings in Python.

In [ ]:
# Examples of each type
my_string = "University of Miami"
my_integer = 100
my_float = 3.14159

print(f"String: {my_string}")
print(f"Integer: {my_integer}")
print(f"Float: {my_float}")

The type() Function

Use type() to check what type a value or variable is:

In [ ]:
print(type("Hello"))  # <class 'str'>
print(type(42))  # <class 'int'>
print(type(3.14))  # <class 'float'>
print(type("42"))  # <class 'str'> - it's in quotes!

Type Hints (Best Practice)

Python lets you add type hints to make your code clearer. This tells readers what type a variable should hold:

age: int = 18
name: str = "Alex"
gpa: float = 3.75

Type hints are optional and do not change how Python runs your code. They are like labels that help humans (and tools) understand your intentions.

In [ ]:
# With type hints
student_name: str = "Jordan"
credits_completed: int = 45
gpa: float = 3.85

print(f"{student_name} has completed {credits_completed} credits with a {gpa} GPA")

Question 2: Identify Types

For each value below, set the corresponding variable to the type of that value.

Use the built-in type names (without quotes): str, int, or float

For example: type_a = str (not type_a = "str")

Value Variable to Set
"Python" type_a
3.0 type_b
100 type_c
"100" type_d
7.5 type_e
In [ ]:
# ✏️ YOUR ANSWER HERE
type_a = ...
type_b = ...
type_c = ...
type_d = ...
type_e = ...
In [ ]:
grader.check("q2_types")

4. Input: Listening to the User

The input() function pauses your program and waits for the user to type something.

Syntax

variable = input("Prompt message: ")

The prompt message appears, then the program waits. When the user presses Enter, whatever they typed is stored in the variable.

In [ ]:
# Demo: Getting user input
# Run this cell and type your name when prompted
user_name = input("What is your name? ")
print(f"Hello, {user_name}!")

Important Note About input() in Notebooks

When you run a cell with input(), the notebook waits for you to type something and press Enter.

If you run multiple cells at once, each input() must be completed before the next cell runs. This can be confusing if you click "Run All" - the notebook will appear stuck until you provide input for each input() call in order.

Tip: Run cells with input() one at a time.

The Input "Trap": Everything is a String!

input() always returns a string, even if the user types a number.

This causes problems when you want to do math:

In [ ]:
# This will NOT work as expected!
# Uncomment and run to see the problem:

# num = input("Enter a number: ")
# print(type(num))  # It's a string!
# print(num + 5)    # Error! Can't add string and int

Solution: Type Conversion (Casting)

Convert the string to a number using int() or float():

text_number = "42"
real_number = int(text_number)  # Now it's an integer: 42

text_decimal = "3.14"
real_decimal = float(text_decimal)  # Now it's a float: 3.14
In [ ]:
# The correct way to get a number from input
age_text = input("Enter your age: ")
age = int(age_text)  # Convert string to integer

print(f"You are {age} years old.")
print(f"In 10 years, you will be {age + 10} years old.")
In [ ]:
# You can also convert in one line:
price = float(input("Enter a price: $"))
print(f"With 10% tax, the total is: ${price * 1.10}")

Practice: Calculate Your Age

Write code that:

  1. Asks the user for their birth year
  2. Converts it to an integer
  3. Calculates their approximate age (current year minus birth year)
  4. Prints a message with their age

This is practice - no autograder (since input() would cause it to hang).

In [ ]:
# ✏️ Practice: Calculate age from birth year
# Your code below:

5. Capstone: The Campus Coffee Shop

Let's combine everything we have learned to build a simple cashier program!

Scenario: You are building a receipt system for a campus coffee shop.

Work through each step below. These cells use input(), so they are not autograded - run them one at a time and check your output.

Step 1: Greet the Customer

Print a welcome message for the coffee shop.

In [ ]:
# ✏️ Step 1: Print a welcome message
# Example output: "Welcome to Campus Coffee Shop!"
# Your code below:

Step 2: Get the Customer's Name

Ask for the customer's name and store it in a variable called customer_name.

In [ ]:
# ✏️ Step 2: Ask for the customer's name
# Store it in: customer_name
# Your code below:

Step 3: Get the Coffee Price

Ask for the price of one coffee. Remember: prices have decimals, so convert to float!

Store it in a variable called coffee_price.

In [ ]:
# ✏️ Step 3: Ask for the price of one coffee
# Convert to float and store in: coffee_price
# Your code below:

Step 4: Get the Number of Cups

Ask how many cups the customer wants. This should be a whole number, so convert to int.

Store it in a variable called num_cups.

In [ ]:
# ✏️ Step 4: Ask for the number of cups
# Convert to int and store in: num_cups
# Your code below:

Step 5: Calculate the Total

Calculate the total cost by multiplying coffee_price by num_cups.

Store the result in a variable called total.

In [ ]:
# ✏️ Step 5: Calculate the total
# total = coffee_price * num_cups
# Your code below:

Step 6: Print the Receipt

Print a formatted receipt using an f-string. Include:

  • Customer name
  • Number of cups
  • Price per cup
  • Total

Example output:

=== RECEIPT ===
Customer: Alex
Cups: 2 x $4.50
Total: $9.00
===============
In [ ]:
# ✏️ Step 6: Print the receipt
# Use f-strings to format the output nicely
# Your code below:

Question 3: Complete Coffee Shop Function

Now let's write the calculation part as a testable function (without input()).

Complete the function calculate_total that:

  • Takes price_per_cup (a float) and num_cups (an int) as parameters
  • Returns the total cost as a float
In [ ]:
# ✏️ YOUR ANSWER HERE
def calculate_total(price_per_cup: float, num_cups: int) -> float:
    """
    Calculate the total cost for a coffee order.

    Args:
        price_per_cup: The price of one cup of coffee
        num_cups: The number of cups ordered

    Returns:
        The total cost as a float
    """
    total = ...
    ...
In [ ]:
grader.check("q3_capstone_function")

Question 4: Format the Receipt

Complete the function format_receipt that creates a receipt string.

The function should return a string in this exact format:

Customer: [name]
Total: $[total]

For example, format_receipt("Alex", 9.0) should return:

Customer: Alex
Total: $9.0
In [ ]:
# ✏️ YOUR ANSWER HERE
def format_receipt(customer_name: str, total: float) -> str:
    """
    Create a formatted receipt string.

    Args:
        customer_name: The customer's name
        total: The total cost

    Returns:
        A formatted receipt string
    """
    receipt = ...
    ...
In [ ]:
grader.check("q4_receipt_string")

6. Summary

Today you learned the building blocks of Python:

Concept What It Does Example
# Create a comment (ignored by Python) # This is a note
print() Display output to the screen print("Hello")
Variables Store data with a name name = "Alex"
str Text data (in quotes) "Hello"
int Whole numbers 42
float Decimal numbers 3.14
type() Check the type of a value type(42) → int
input() Get text from the user name = input("Name: ")
int() Convert to integer int("42") → 42
float() Convert to decimal float("3.14") → 3.14
f-strings Format strings with variables f"Hello {name}"

Key Takeaways

  1. Use comments to explain your code and leave notes for yourself
  2. Use f-strings for formatting output - they are the cleanest way to combine text and variables
  3. input() always returns a string - convert with int() or float() when you need numbers
  4. Use descriptive variable names in snake_case
  5. Quotes matter - "5" is text, 5 is a number

You have completed the Python Basics lecture notebook.


To double-check your work, the cell below will rerun all of the autograder tests.

In [ ]:
grader.check_all()