Giving Functions Information: Parameters

Parameters

A function becomes much more useful when you can give it information. The names inside the brackets are parameters:

def greet(name):
    print(f"Hello, {name}!")

greet("Asha")
greet("Ravi")

Output

Hello, Asha!
Hello, Ravi!

When you call greet("Asha"), the value "Asha" (called an argument) is put into the parameter name.

More than one parameter

def show_price(item, price, quantity):
    print(f"{quantity} x {item} = {price * quantity} rupees")

show_price("pen", 10, 3)
show_price("notebook", 45, 2)

Output

3 x pen = 30 rupees
2 x notebook = 90 rupees

Arguments are matched to parameters in order: first to first, second to second.

Default values

Give a parameter a default value, and it becomes optional:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Asha")
greet("Ravi", "Good morning")

Output

Hello, Asha!
Good morning, Ravi!

Keyword arguments

You can also name the arguments when you call a function. Then the order doesn't matter:

def make_profile(name, age, city):
    print(f"{name} ({age}) from {city}")

make_profile(city="Mumbai", name="Kabir", age=19)

Output

Kabir (19) from Mumbai

Remember: Parameter = the name in the def line. Argument = the actual value you pass in.

HOME LEARN COMMUNITY DASHBOARD