22. Calling Functions

Quiz: 0/6

In Python, calling a function means executing the code inside it to perform its defined task. When we call a function, we "activate" it, asking it to perform its job.

Basic syntax of a function call

To call a function, write its name followed by parentheses (). If the function accepts parameters, include the required arguments inside the parentheses.

def greet():
    print("Hello!")

greet()  # This is calling the function

Explanation:

  • greet() calls the greet function, so Python executes the code inside it.
  • The output is:
    Hello!
    

Calling a function with arguments

When a function has parameters, you must provide arguments to match those parameters during the function call. These arguments are the actual values the function uses to perform its task.

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

greet("Alice")  # Output: Hello, Alice!
greet("Bob")    # Output: Hello, Bob!

Explanation:

  • The greet function has one parameter, name.
  • When we call greet("Alice"), the value Alice is passed as an argument to name, resulting in the output:
    Hello, Alice!
    

Using return values from function calls

A function can return a value that can be stored in a variable or used in an expression.

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

result = add(5, 3)  # Calls the function and stores the result in 'result'
print(result)       # Output: 8

Explanation:

  • add(5, 3) calls the function with arguments 5 and 3.
  • The function returns the sum (8), which is stored in the result variable.
  • Printing result outputs:
    8
    

Calling functions with default parameters

A function can have default parameter values. If no argument is provided for a parameter, the default value is used.

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

greet()            # Output: Hello, stranger!
greet("Charlie")   # Output: Hello, Charlie!

Explanation:

  • When greet() is called without arguments, the default value stranger is used.
  • When greet("Charlie") is called, the default is overridden with Charlie.

Calling functions with multiple arguments

For functions with multiple parameters, provide arguments in the correct order or use keyword arguments to specify them explicitly.

Positional arguments example:

def subtract(a, b):
    return a - b

result1 = subtract(10, 5)   # Output: 5 (10 - 5)
result2 = subtract(5, 10)   # Output: -5 (5 - 10)
print(result1, result2)

Keyword arguments example:

def subtract(a, b):
    return a - b

result = subtract(b=5, a=10)  # Output: 5
print(result)

Explanation:

  • Positional arguments must follow the order of parameters.
  • Keyword arguments let you specify which value corresponds to which parameter, regardless of order.

Function calls within expressions

Since function calls can return values, you can use those values in expressions or pass them to other functions.

def square(x):
    return x * x

def add_squares(a, b):
    return square(a) + square(b)

result = add_squares(3, 4)  # Output: 25 (9 + 16)
print(result)

Explanation:

  • add_squares(3, 4) calls square(3) and square(4).
  • Their results (9 and 16) are added together, returning 25.

Summary

  • Calling a function executes its code using function_name(arguments).
  • Arguments must match the parameters in number and order unless you use keyword arguments.
  • Functions can return results, which you can store or use directly in expressions.
  • Default parameters allow flexibility, letting you omit arguments when calling the function.
  • Functions are reusable building blocks that make complex programs simpler and more efficient.

Hands-On Practise

Exercise: Practice calling functions

Objective:

Write a program that demonstrates your understanding of function calls, arguments, return values, and default parameters.

Problem statement:

Create the following functions:

  1. introduce(name, age):

    • Takes two arguments: name (a string) and age (an integer).
    • Prints: Hi, my name is <name> and I am <age> years old.
  2. multiply(a, b):

    • Takes two arguments: a and b (both integers).
    • Returns the product of the two numbers.
  3. greet_with_time(name, time_of_day="morning"):

    • Takes a required argument name (a string) and an optional argument time_of_day (default is "morning").
    • Prints: Good <time_of_day>, <name>!
  4. circle_area(radius):

    • Takes one argument radius (a float or integer).
    • Returns the area of a circle with the given radius (area = π * radius²). Use 3.14159 as the value of π.

Tasks:

  1. Call the introduce function with your name and age.
  2. Call the multiply function with any two numbers, store the result, and print it.
  3. Call the greet_with_time function:
    • Once with only the name argument.
    • Once with both name and a custom time_of_day (e.g., "afternoon").
  4. Call the circle_area function with a radius of 5, store the result, and print it.

Challenge (Optional):

Modify the circle_area function to accept multiple radii as a list, calculate the area for each radius, and return the results in a list.

Output:

Quizzes: 0/6

Question 1:

What is the correct syntax to call a function in Python?

  • function_name{}
  • function_name()
  • call function_name()
  • call function_name{}

Question 2:

What happens when you call a function without providing required arguments?

  • An error is raised.
  • The function returns None.
  • The function uses default values, if defined.
  • The function does nothing.

Question 3:

What is the result of the following function call? add(5, 3) where add is defined as def add(a, b): return a + b?

  • Error, as the function is missing return values.
  • 8
  • None
  • 5

Question 4:

Which of the following is the correct way to call a function with default parameters?

  • function_name()
  • function_name('value')
  • function_name('value', 'value2')
  • function_name(default_value)

Question 5:

What is the purpose of using keyword arguments in a function call?

  • To ensure arguments are passed in the correct order.
  • To allow arguments to be passed in any order.
  • To prevent errors in the function.
  • To specify the function's return value.

Question 6:

What will the following code print? greet_with_time('Alice', 'evening') where the function greet_with_time is defined as def greet_with_time(name, time_of_day='morning'): print(f'Good {time_of_day}, {name}!')?

  • Good morning, Alice!
  • Good evening, Alice!
  • Good Alice!
  • Alice evening!

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonFunctions in PythonNext lessonUnderstanding positional and keyword arguments