In [ ]:
%pip install -q otter-grader
In [ ]:
# 1. Download the file using gdown (which handles Google Drive links perfectly)
# We pass the file ID directly to it.
!gdown "FILE_ID_HERE" -O assignment.zip

# 2. Unzip the file silently into the current Colab directory
!unzip -q -o assignment.zip

# 3. (Optional) Verify the tests folder is there
!ls -l tests/
In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook()

Welcome to Jupyter Notebooks!

What You'll Learn

By the end of this notebook, you will be able to:

  • Navigate the Jupyter Notebook interface
  • Execute code cells using Shift+Enter
  • Write and format text using Markdown cells
  • Use interactive widgets to explore Python concepts
  • Understand the basics of Python programming

Estimated Time: 30-40 minutes


Let's Get Started!

The most important thing to know about Jupyter Notebooks is how to run code. Here's the magic formula:

Shift + Enter = Run the Cell

Try it now! Click on the cell below and press Shift + Enter.

Understanding Cells

Jupyter Notebooks are made up of cells. There are two main types:

  1. Markdown Cells: For text, explanations, and formatting (like this one!)
  2. Code Cells: For Python code that you can execute

Run the next cell to see some basic Python in action!

In [ ]:
# This is a comment - Python ignores it
# Comments help explain what code does

# Let's do some math!
result = 5 + 3
print(f"5 + 3 = {result}")

# Python can also work with text (called "strings")
name = "Python Learner"
print(f"Hello, {name}! Welcome to programming!")

Your Turn! Fill in the Blanks

In the cell below, replace the ___ with your own values and run the cell.

In [ ]:
# Replace ___ with your information
my_name = ...
my_age = ...
my_major = ...

# Now let's see your personalized message!
print(f"Hi! My name is {my_name}.")
print(f"I am {my_age} years old.")
print(f"My major is {my_major}.")
In [ ]:
grader.check("q1")

Interactive Python with Widgets

One of the coolest features of Jupyter is that you can create interactive elements! Let's explore Python with some interactive widgets.

Run the next cell to see your first interactive widget!

In [ ]:
from ipywidgets import interact, widgets


def greet(name="Friend") -> str:
    """Display a personalized greeting"""
    print(f"Hello, {name}! Nice to meet you!")
    return name


# Create an interactive text box
interact(greet, name=widgets.Text(value="Friend", description="Your Name:"));

Exploring Math with Sliders

Let's use sliders to explore addition interactively. Move the sliders and watch the result change!

In [ ]:
from ipywidgets import IntSlider, interact


def add_numbers(a=5, b=3):
    """Add two numbers and display the result"""
    result = a + b
    print(f"{a} + {b} = {result}")
    print("=" * 30)
    print("💡 Try different values to see how addition works!")


interact(
    add_numbers,
    a=IntSlider(min=0, max=20, step=1, value=5, description="First number:"),
    b=IntSlider(min=0, max=20, step=1, value=3, description="Second number:"),
);

Exploring Different Operations

Python can do many math operations. Let's explore them interactively!

In [ ]:
from ipywidgets import Dropdown, IntSlider, interact


def calculate(a=10, b=5, operation="+"):
    """Perform different math operations"""
    if operation == "+":
        result = a + b
        op_name = "Addition"
    elif operation == "-":
        result = a - b
        op_name = "Subtraction"
    elif operation == "*":
        result = a * b
        op_name = "Multiplication"
    elif operation == "/":
        result = a / b if b != 0 else "Cannot divide by zero!"
        op_name = "Division"

    print(f"Operation: {op_name}")
    print(f"{a} {operation} {b} = {result}")
    print("=" * 40)


interact(
    calculate,
    a=IntSlider(min=0, max=50, step=1, value=10, description="First:"),
    b=IntSlider(min=0, max=50, step=1, value=5, description="Second:"),
    operation=Dropdown(
        options=["+", "-", "*", "/"], value="+", description="Operation:"
    ),
);

Visualizing Data with Plots

Python is excellent for creating visualizations. Let's create an interactive plot that changes based on your input!

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import Dropdown, FloatSlider, interact


def plot_function(function="Linear", slope=1.0, intercept=0.0):
    """Plot different mathematical functions"""
    x = np.linspace(-10, 10, 100)

    if function == "Linear":
        y = slope * x + intercept
        title = f"y = {slope:.1f}x + {intercept:.1f}"
    elif function == "Quadratic":
        y = slope * x**2 + intercept
        title = f"y = {slope:.1f}x² + {intercept:.1f}"
    elif function == "Cubic":
        y = slope * x**3 + intercept
        title = f"y = {slope:.1f}x³ + {intercept:.1f}"

    plt.figure(figsize=(10, 6))
    plt.plot(x, y, linewidth=2, color="blue")
    plt.grid(True, alpha=0.3)
    plt.axhline(y=0, color="black", linewidth=0.5)
    plt.axvline(x=0, color="black", linewidth=0.5)
    plt.title(title, fontsize=14, fontweight="bold")
    plt.xlabel("x", fontsize=12)
    plt.ylabel("y", fontsize=12)
    plt.ylim(-50, 50)
    plt.show()


interact(
    plot_function,
    function=Dropdown(
        options=["Linear", "Quadratic", "Cubic"],
        value="Linear",
        description="Function:",
    ),
    slope=FloatSlider(min=-5, max=5, step=0.1, value=1.0, description="Slope:"),
    intercept=FloatSlider(
        min=-10, max=10, step=0.5, value=0.0, description="Intercept:"
    ),
);

Interactive Color Mixer

Let's explore how colors work by mixing Red, Green, and Blue (RGB) values!

In [ ]:
import matplotlib.patches as patches
from ipywidgets import IntSlider, interact


def mix_colors(red=255, green=128, blue=0):
    """Mix RGB colors and display the result"""
    # Normalize values to 0-1 range for matplotlib
    r_norm = red / 255
    g_norm = green / 255
    b_norm = blue / 255

    # Create a figure to show the color
    fig, ax = plt.subplots(figsize=(8, 4))

    # Create a colored rectangle
    rect = patches.Rectangle((0, 0), 1, 1, facecolor=(r_norm, g_norm, b_norm))
    ax.add_patch(rect)

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.axis("off")

    # Display RGB values
    color_code = f"RGB({red}, {green}, {blue})"
    hex_code = f"#{red:02x}{green:02x}{blue:02x}".upper()

    # Choose text color based on brightness
    brightness = (red + green + blue) / 3
    text_color = "white" if brightness < 128 else "black"

    ax.text(
        0.5,
        0.6,
        color_code,
        ha="center",
        va="center",
        fontsize=16,
        fontweight="bold",
        color=text_color,
    )
    ax.text(0.5, 0.4, hex_code, ha="center", va="center", fontsize=14, color=text_color)

    plt.title("Your Mixed Color", fontsize=14, pad=10)
    plt.tight_layout()
    plt.show()

    print(f"🎨 RGB: ({red}, {green}, {blue})")
    print(f"🔖 Hex: {hex_code}")


interact(
    mix_colors,
    red=IntSlider(min=0, max=255, step=1, value=255, description="Red:"),
    green=IntSlider(min=0, max=255, step=1, value=128, description="Green:"),
    blue=IntSlider(min=0, max=255, step=1, value=0, description="Blue:"),
);

Interactive Quiz

Let's test your understanding with an interactive quiz!

In [ ]:
from IPython.display import clear_output, display
from ipywidgets import Button, Output, RadioButtons, VBox, interact

# Quiz questions and answers
questions = [
    {
        "question": "What key combination runs a cell in Jupyter?",
        "options": ["Ctrl+R", "Shift+Enter", "Alt+R", "Ctrl+Enter"],
        "correct": "Shift+Enter",
        "explanation": "Shift+Enter runs the current cell and moves to the next one!",
    },
    {
        "question": "What are the two main types of cells in Jupyter?",
        "options": [
            "Text and Code",
            "Markdown and Code",
            "Input and Output",
            "Python and HTML",
        ],
        "correct": "Markdown and Code",
        "explanation": "Markdown cells contain formatted text, and Code cells contain executable Python!",
    },
    {
        "question": "What is the result of: 10 + 5 * 2 in Python?",
        "options": ["30", "20", "25", "15"],
        "correct": "20",
        "explanation": "Python follows order of operations: 5 * 2 = 10, then 10 + 10 = 20!",
    },
]

current_question = 0
score = 0
output = Output()


def create_quiz():
    global current_question, score

    if current_question >= len(questions):
        with output:
            clear_output()
            print("=" * 50)
            print(f"🎉 Quiz Complete! You scored {score}/{len(questions)}!")
            print("=" * 50)
            if score == len(questions):
                print("Perfect score! You're a Jupyter expert! 🌟")
            elif score >= len(questions) / 2:
                print("Great job! You're learning well! 👍")
            else:
                print("Keep practicing! You'll get better! 💪")
        return

    q = questions[current_question]

    radio = RadioButtons(options=q["options"], description="", disabled=False)

    button = Button(description="Submit Answer", button_style="success")

    def on_button_click(b):
        global current_question, score

        with output:
            clear_output()
            if radio.value == q["correct"]:
                print("✅ Correct!")
                score += 1
            else:
                print(f"❌ Not quite. The correct answer is: {q['correct']}")
            print(f"\n💡 {q['explanation']}\n")
            print(f"Score: {score}/{current_question + 1}")
            print("\nClick to continue to the next question...\n")

        button.description = "Next Question"
        button.button_style = "info"
        button.on_click(next_question)

    def next_question(b):
        global current_question
        current_question += 1
        with output:
            clear_output()
        create_quiz()

    button.on_click(on_button_click)

    with output:
        clear_output()
        print("=" * 50)
        print(f"Question {current_question + 1} of {len(questions)}")
        print("=" * 50)
        print(f"\n{q['question']}\n")

    display(VBox([radio, button, output]))


# Start the quiz
create_quiz()

Text Input Widget

Let's create a fun text-based interaction. Type your message and click the button!

In [ ]:
from ipywidgets import Output, Text

# Create widgets
text_input = Text(
    value="",
    placeholder="Type something here...",
    description="Message:",
    disabled=False,
)

button = Button(
    description="Transform!",
    button_style="success",
    tooltip="Click to transform your text",
)

output = Output()


def on_button_click(b):
    """Transform the input text in various ways"""
    with output:
        output.clear_output()
        message = text_input.value

        if message:
            print("Original:", message)
            print("Uppercase:", message.upper())
            print("Lowercase:", message.lower())
            print("Reversed:", message[::-1])
            print("Length:", len(message), "characters")
            print("Word count:", len(message.split()), "words")
        else:
            print("Please enter some text first!")


button.on_click(on_button_click)

# Display widgets
display(VBox([text_input, button, output]))

Interactive Pattern Generator

Let's create some ASCII art patterns! Adjust the size and character to see different patterns.

In [ ]:
from ipywidgets import Dropdown, IntSlider, interact


def create_pattern(size=5, pattern_type="Square", character="*"):
    """Generate different ASCII patterns"""
    print(f"Pattern Type: {pattern_type}")
    print("=" * 40)

    if pattern_type == "Square":
        for i in range(size):
            print(character * size)

    elif pattern_type == "Triangle":
        for i in range(1, size + 1):
            print(character * i)

    elif pattern_type == "Pyramid":
        for i in range(1, size + 1):
            spaces = " " * (size - i)
            stars = character * (2 * i - 1)
            print(spaces + stars)

    elif pattern_type == "Diamond":
        # Top half
        for i in range(1, size + 1):
            spaces = " " * (size - i)
            stars = character * (2 * i - 1)
            print(spaces + stars)
        # Bottom half
        for i in range(size - 1, 0, -1):
            spaces = " " * (size - i)
            stars = character * (2 * i - 1)
            print(spaces + stars)

    elif pattern_type == "Hollow Square":
        for i in range(size):
            if i == 0 or i == size - 1:
                print(character * size)
            else:
                print(character + " " * (size - 2) + character)


interact(
    create_pattern,
    size=IntSlider(min=3, max=15, step=1, value=5, description="Size:"),
    pattern_type=Dropdown(
        options=["Square", "Triangle", "Pyramid", "Diamond", "Hollow Square"],
        value="Square",
        description="Pattern:",
    ),
    character=Dropdown(
        options=["*", "#", "@", "+", "◆", "●", "■"], value="*", description="Character:"
    ),
);

Temperature Converter

Let's build a practical tool - a temperature converter that converts between Celsius and Fahrenheit!

In [ ]:
from ipywidgets import Dropdown, FloatSlider, interact


def convert_temperature(value=0.0, convert_from="Celsius"):
    """Convert temperature between Celsius and Fahrenheit"""

    if convert_from == "Celsius":
        fahrenheit = (value * 9 / 5) + 32
        print(f"🌡️  {value:.1f}°C = {fahrenheit:.1f}°F")

        # Add some context
        if value <= 0:
            print("❄️  Freezing or below!")
        elif value < 15:
            print("🧊  Cold")
        elif value < 25:
            print("😊  Comfortable")
        elif value < 35:
            print("☀️  Warm")
        else:
            print("🔥  Hot!")

    else:  # Fahrenheit to Celsius
        celsius = (value - 32) * 5 / 9
        print(f"🌡️  {value:.1f}°F = {celsius:.1f}°C")

        # Add some context
        if celsius <= 0:
            print("❄️  Freezing or below!")
        elif celsius < 15:
            print("🧊  Cold")
        elif celsius < 25:
            print("😊  Comfortable")
        elif celsius < 35:
            print("☀️  Warm")
        else:
            print("🔥  Hot!")

    print("\n💡 Fun Facts:")
    print("   • Water freezes at 0°C (32°F)")
    print("   • Water boils at 100°C (212°F)")
    print("   • Normal body temperature is 37°C (98.6°F)")


interact(
    convert_temperature,
    value=FloatSlider(
        min=-50, max=150, step=0.5, value=0.0, description="Temperature:"
    ),
    convert_from=Dropdown(
        options=["Celsius", "Fahrenheit"], value="Celsius", description="Convert from:"
    ),
);

Practice: Create Your Own Interactive Widget!

Now it's your turn! Below is a template for creating an interactive widget. Try modifying it to create your own calculator, converter, or tool.

Ideas to try:

  • A tip calculator (calculate tips for restaurant bills)
  • A currency converter
  • A grade calculator
  • A BMI calculator
  • Anything you can imagine!
In [ ]:
from ipywidgets import FloatSlider, interact


def my_function(value1=10, value2=5):
    """Your function description here"""

    # Add your calculations here
    result = value1 + value2  # Modify this!

    # Display your results
    print(f"Result: {result}")

    # Add more functionality here!


# Create the interactive widget
interact(
    my_function,
    value1=FloatSlider(min=0, max=100, step=1, value=10, description="Value 1:"),
    value2=FloatSlider(min=0, max=100, step=1, value=5, description="Value 2:"),
);

Jupyter Keyboard Shortcuts

Here are some helpful keyboard shortcuts to make you more efficient:

Command Mode (press Esc to enter)

  • A: Insert cell above
  • B: Insert cell below
  • DD: Delete cell (press D twice)
  • M: Change cell to Markdown
  • Y: Change cell to Code
  • Z: Undo cell deletion

Edit Mode (press Enter to enter)

  • Shift + Enter: Run cell and move to next
  • Ctrl + Enter: Run cell and stay in place
  • Alt + Enter: Run cell and insert new cell below
  • Tab: Code completion/indent
  • Shift + Tab: Show function help

Try these out! Press Esc to enter Command Mode, then press B to create a new cell below this one.

Tips for Success with Jupyter

  1. Run cells in order: Jupyter notebooks work best when you run cells from top to bottom
  2. Save often: Click the save button or press Ctrl+S (Cmd+S on Mac)
  3. Restart if confused: If things aren't working, try "Kernel > Restart & Run All" from the menu
  4. Experiment freely: You can't break anything! Try changing code and see what happens
  5. Read error messages: They often tell you exactly what's wrong
  6. Use comments: Add comments to explain your code (lines starting with #)
  7. Keep it organized: Use Markdown cells to add explanations and structure

Conclusion

Congratulations! You've learned:

  • ✅ How to run cells with Shift+Enter
  • ✅ The difference between Markdown and Code cells
  • ✅ How to use interactive widgets
  • ✅ Basic Python programming concepts
  • ✅ How to create visualizations
  • ✅ Useful keyboard shortcuts

You're now ready to start learning Python! The best way to learn is by doing, so keep experimenting and don't be afraid to try new things.


Final Challenge

Create a new code cell below (press B in command mode) and write code that:

  1. Creates a variable named new_name with your name as the value
  2. Creates a variable named grad_year with your graduation year
  3. Prints a message using both variables

Happy coding! 🎉

In [ ]:
# Your solution here
new_name = ...
grad_year = ...

...
In [ ]:
grader.check("q2")

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

In [ ]:
grader.check_all()