Function Parameters
So far, we have only created functions without input. Thanks to parameters, we can provide different inputs to the function and thus influence its behavior.
We specify the parameters in parentheses after the function name during its definition, and in the function body, we use them as normal variables. For example:
def greet(name):
print("Hello, " + name)
greet("Carl") # Outputs: Hello, Carl
greet("Jane") # Outputs: Hello, Jane
This function has one parameter: name
. When we call the function using greet("Karel")
, we assign the value "Karel"
to the parameter name
, which we then print using the print
command. Similarly with greet("Jana")
.
A function can also have multiple parameters. Let's look at an example:
def multiply(a, b):
result = a * b
print(result)
multiply(2, 3) # Outputs: 6
multiply(5, 10) # Outputs: 50
This code defines a function multiply
with two parameters a
and b
. The function calculates and prints their product. It is important to realize that the order in which we write the parameters in the function definition is the same order we use when calling the function. Simply, with multiply(2, 3)
, 2
is substituted for a
and 3
is substituted for b
.
Instructions
Create a function named sum
that has two parameters x
and y
. The function should print the sum of these two arguments.
Call this function with parameter values 3
and 4
.
Call the sum
function again with parameter values 10
and 15
.
Start programming for free
4/7