Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Function Body | What is a Function in Python?
Python Functions Tutorial
course content

Course Content

Python Functions Tutorial

Python Functions Tutorial

1. What is a Function in Python?
2. Positional and Optional Arguments
3. Arbitrary Arguments
4. Function Return Value Specification
5. Recursion and Lambda Functions

book
Function Body

The function body refers to the block of code contained within a function. It is part of the function definition where you write the instructions or statements that define the function's behavior.

Previously, we used mathematical formulas and the print() function as the body in earlier chapters. However, the function body can be more complex, containing loops, if-else statements, keywords, or other code to implement necessary logic.

We must use one indentation to define the function body. Indentation in Python refers to the spacing of code lines to define the structure and hierarchy of the code. In the context of functions, indentation defines the function's body, including all the statements executed when the function is called.

Example: Cat's Health Level

Write a function that determines a cat's health level based on the amount of calories it consumes daily. Consider the following conditions:

  • If the cat consumes less than 200 calories per day, the health level is "low".
  • If the cat consumes between 200 and 400 calories per day, the health level is "average".
  • If the cat consumes more than 400 calories per day, the health level is "high".
12345678910111213141516
def health_level_for_cat(calories_per_day): # Use one indentation to create function body if calories_per_day < 200: health_level = 'Low' elif 200 <= calories_per_day <= 400: health_level = 'Average' else: health_level = 'High' message = f"The cat's health level based on calorie intake is {health_level}." return message # Example usage of the function print("Cat Felix:", health_level_for_cat(187)) print("Cat Tom:", health_level_for_cat(301)) print("Cat Oggy:", health_level_for_cat(404))
copy

The function's body begins with the function definition. Inside, an if-else statement determines the cat's health level based on daily calorie intake. After evaluating the condition, the function constructs a message reflecting the health level and returns it as the function's output.

In this example, the function assesses the cat's health level based on calorie consumption and generates a corresponding message, which is then printed as the function's output.

What is the purpose of the function body in Python?

What is the purpose of the function body in Python?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt