Pulsars
0 %
Log inSign up

Parameters, Return Values, and Scope

Parameters and Arguments

Parameters and Arguments

A function becomes much more useful when it can receive information to adapt its behavior. This information is called parameters.

A parameter is a variable declared between the function's parentheses, when it is defined:

def say_hello(name):
    print("Hello", name)

Here, name is a parameter: a kind of empty slot that the function will fill in on each call. The value actually passed when calling the function is called an argument:

say_hello("Sam")    # ("Sam" is the argument passed to the name parameter)
say_hello("Alex")   # (here the argument is "Alex")

A function can have several parameters, separated by commas. You then need to respect the order when calling it:

def add(a, b):
    print(a + b)

add(3, 5)   # (prints 8: a is 3, b is 5)

A parameter can also have a default value, used if no argument is provided for it in the call:

def say_hello(name="friend"):
    print("Hello", name)

say_hello()         # (prints Hello friend)
say_hello("Sam")    # (prints Hello Sam)

Common mistake: confusing the number of expected parameters with the number of arguments provided. If a function expects two parameters and you only give it one argument when calling it (with no default value), Python displays an error of the type missing 1 required positional argument.