Multiple Parameters

Multiple Parameters

A function can take several parameters, separated by commas. Arguments are matched to parameters by position — first argument to first parameter, second to second:

def describe(name, age):
    return f"{name} is {age} years old."

print(describe("Parsnip", 36))
print(describe(36, "Parsnip"))

Output:

Parsnip is 36 years old.
36 is Parsnip years old.

The second call is legal Python but wrong: the arguments arrived in the wrong order, so name got 36 and age got "Parsnip". Python matches by position, not by meaning.

Arguments can also be passed by name, which removes the ordering problem:

print(describe(age=36, name="Parsnip"))

Output:

Parsnip is 36 years old.

Exercise

  1. Define a function named trip_cost with three parameters: distance, price_per_km, and passengers.
  2. It returns the total cost: distance times price_per_km, divided by passengers — the cost per person.

For example, trip_cost(100, 3.0, 2) returns 150.0.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestTripCost(unittest.TestCase):
    def test_100_km_at_3_kroner_for_2_passengers(self):
        self.assertAlmostEqual(trip_cost(100, 3.0, 2), 150.0)

    def test_50_km_at_2_kroner_for_1_passenger(self):
        self.assertAlmostEqual(trip_cost(50, 2.0, 1), 100.0)

    def test_parameter_order_matters(self):
        self.assertAlmostEqual(trip_cost(10, 5.0, 4), 12.5)
def trip_cost(distance, price_per_km, passengers):
    return distance * price_per_km / passengers


print(trip_cost(100, 3.0, 2))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.