PY-1.1-BP6-MQ20

Our Goal: Make a Function to Multiply Numbers!

Hello! In this quest, we're going to make another special helper in Python, just like our add function. This time, it will be a multiply function!

Our multiply function will take two numbers and give us back their product (that's what you get when you multiply them). We'll put this function in a file called operations.py.

Write Your Code: Make the `multiply` Function!

Now it's your turn to write the code! We need to make the multiply function inside operations.py work.

Remember, a function is like a mini-program that does a specific job. Our multiply function needs to take two numbers and give back their product.

Here's an example of how you might make a function that adds two numbers. You can use this idea to help you with your multiply function:

def add(num1, num2):
    # This function takes two numbers and adds them.
    total = num1 + num2
    return total

Your task is to complete the multiply function so it correctly multiplies the two numbers it receives.

Write Your Tests: Check Your `multiply` Function!

Now that you've started your multiply function, it's time to write your own tests! This is a very important step because it helps you make sure your code works correctly.

Create a new file called test_operations.py in the same folder as your operations.py file.

Inside test_operations.py, you'll write test functions that check if your multiply function gives the right answers. Here are some ideas for tests you should write:

  • Test positive numbers: Make sure multiply(2, 3) gives 6 and multiply(10, 5) gives 50.
  • Test negative numbers: Check if multiply(-2, -3) gives 6 and multiply(-4, -5) gives 20.
  • Test positive and negative numbers: See if multiply(5, -2) gives -10 and multiply(-3, 4) gives -12.
  • Test with zero: What happens when you multiply by zero? Check multiply(0, 7), multiply(9, 0), and multiply(0, 0). They should all give 0.
  • Test with decimal numbers: Try multiply(2.5, 2.0) which should give 5.0, and multiply(1.5, 3.0) which should give 4.5.

Remember to use assert to check if your function's answer matches what you expect!

# Example of a test function structure
import pytest # You'll need this if you use pytest.approx()
from operations import multiply # This brings your multiply function into the test file

def test_example_case():
    # Call your function and check the result
    assert multiply(some_number, another_number) == expected_answer

Once you've written your tests, save the test_operations.py file. You're doing great!

Check Your Work: Did It Pass?

Now that you've written your multiply function and created your own tests in test_operations.py, let's run the tests to see if everything is working correctly!

Open your terminal and type this command: pytest module-1.1/blueprint-6/quest-20

What you should see:

  • ✅ All your tests should pass!

If all your tests show ✅, it means your multiply function is working perfectly and your tests are doing a great job of checking it!

Review Your Code

Now, let's review your code with your mentor. Be ready to talk about:

  • How you wrote the multiply function.
  • How you created your test_operations.py file.
  • What different kinds of tests you wrote (like for positive numbers, negative numbers, or zero).
  • How each test checks a different part of your multiply function.
  • How running the tests helped you know your code was working.

Documentation

Python Functions and Basic Testing Cheat Sheet

This document provides a quick reference for defining Python functions and writing basic tests using pytest.

Defining a Python Function

A function is a block of code that performs a specific task. You define a function using the def keyword.

def function_name(parameter1, parameter2):
    """
    This is a docstring. It explains what the function does.
    Args:
        parameter1: Description of the first parameter.
        parameter2: Description of the second parameter.
    Returns:
        Description of the value the function returns.
    """
    # Function body starts here, indented
    # Code to perform the task
    result = parameter1 + parameter2
    return result # Use return to send a value back
  • def: Keyword to start a function definition.
  • function_name: Choose a descriptive name.
  • (parameter1, parameter2): Input values the function accepts. Can be zero or more.
  • :: Marks the end of the function header.
  • Docstring ("""..."""): Explains the function's purpose, arguments (Args), and return value (Returns). Good practice for documentation.
  • Indented block: The code that runs when the function is called.
  • return: Sends a value back from the function. If return is not used, the function returns None by default.

Image showing the structure of a Python function definition with labels for def, name, parameters, colon, docstring, indented body, and return statement.

Introduction to Testing with Pytest

Testing helps verify that your code works as expected. pytest is a framework for writing and running tests in Python.

  • Test files should be named starting with test_ or ending with _test.py.
  • Test functions inside these files should be named starting with test_.

GIF showing the pytest command being run in a terminal.

Writing a Basic Test Function

A test function calls the code you want to test and uses assert statements to check if the results are correct.

# Example test function structure
def test_something():
    # Call the function you are testing
    actual_result = your_function(input_value)
    # Use assert to check if the actual result matches the expected result
    assert actual_result == expected_result
  • def test_...: Defines a test function. pytest finds and runs functions named this way.
  • assert condition: Checks if condition is True. If it's False, the test fails.

Image showing a simple pytest test function using assert to compare a function call result to an expected value.

Testing Multiple Scenarios

You can include multiple assert statements within a single test function to check different inputs or cases for the same function.

# Example test function with multiple assertions
def test_example_function():
    # Test case 1: Positive input
    assert example_function(5) == 25

    # Test case 2: Negative input
    assert example_function(-3) == 9

    # Test case 3: Zero input
    assert example_function(0) == 0

This approach helps ensure your function handles various situations correctly. If any assert fails, the test function stops and is marked as failed.

Image showing a pytest test function with several assert lines, each checking a different input value for the function being tested.

Running Pytest

Navigate to your project directory in the terminal and run the command:

pytest

pytest will discover and run your test files and functions, reporting the results (PASSED, FAILED, etc.).

GIF showing pytest output in the terminal, showing both PASSED and FAILED states.