Python Functions and Return Values
Let’s take a closer look at functions in the Python programming language and also talk about their return values.
From a high level, a function can be viewed as a reusable block of code to perform specific actions or tasks.
There are various built-in Python functions.
# Print text to the console
print("Let's learn some Python!")
# Output
# Let's learn some Python!
# Return an object's data type
number = 1
print(type(number))
# Output
# <class 'int'>
# Convert object to string
number = str(number)
print(type(number))
# Output
# <class 'str'>Note: in older Python versions (before version 3), print built-in function didn’t use parentheses (and was written as a statement).
Defining Functions
Apart from built-in functions, we can create our own functions. To define a function a def keyword is used at the start of the function block.
# Function definition
def how_to_succeed(tip_1, tip_2):
# Function body
print("Tip 1: " + tip_1 + ".")
print("Tip 2: " + tip_2 + ".")
# Calling the function
how_to_succeed("Work", "Work harder")
# Output
# Tip 1: Work.
# Tip 2: Work harder.Functions can use arguments (information you pass to it to modify in a certain way): in the example above “Work” and “Work harder” are arguments for the function how_to_succeed (when the function is defined, they are called its parameters: tip_1, tip_2 in the example above; to simplify: parameters are a general name before using exact values, while arguments are related to specific values passed to a function).
To get values out of functions, return values can be used.
Return is a reserved keyword that sends a result from a function so that it can be saved for later use. If a function doesn’t have a return statement, by default it returns None.
def celsius_to_fahrenheit(celsius_temp):
return (celsius_temp * 1.8) + 32
water_freeze_celsius = 0
water_freeze_fahrenheit = celsius_to_fahrenheit(water_freeze_celsius)
# Convert float to string to combine it with the rest of the text.
print("Water freezes at " + str(water_freeze_fahrenheit) + " degrees Fahrenheit.")
# Output
# Water freezes at 32.0 degrees Fahrenheit.This also demonstrates the concept of reusability (defining code once and using it later without the need to write it again) and modularity (writing code in separate components that can work together and be reused for other programs). Both can be applied to programming in general and not only Python.
water_boil_celsius = 100
water_boil_fahrenheit = celsius_to_fahrenheit(water_boil_celsius)
print("Water boils at " + str(water_boil_fahrenheit) + " degrees Fahrenheit.")
# Output
# Water boils at 212.0 degrees Fahrenheit.Concepts and Terminology
While talking about functions, it can be worth it to mention several concepts and terminology related to them.
The process of restructuring code while maintaining its original functionality is called refactoring. Here we can also mention self-documenting code which relates to the code that is written in a readable way that makes its purpose clear. An example of it can be selecting easy-to-understand variables names or using comments in the code with “#” sign (the line that starts with that character will be ignored when the code is running, hence it’s used for descriptions, clarifications, etc.). Following these principles reduces errors, speeds up the work process, and helps with collaboration when working in a team.
Get Dimterion’s stories in your inbox
Join Medium for free to get updates from this writer.
Working with functions also relates to algorithms — sets of instructions to solve a problem or accomplish a task. To make it easier to do, every function can be split into smaller parts that work together. Comments can be used to describe what each part does. You can also add the comments first, before writing any code, to demonstrate what your goal is in human-readable language. That is called writing pseudocode. Once you have written it, you can begin adding the actual code to perform each step.
# Pseudocode example
def fahrenheit_to_celsius(fahrenheit_temp):
# Subtract 32 from fahrenheit temp
# Multiply the result by 5
# Divide the result by 9
# Show the final result# Final code example
def fahrenheit_to_celsius(fahrenheit_temp):
# Subtract 32 from fahrenheit temp
first_action = fahrenheit_temp - 32
# Multiply the result by 5
second_action = first_action * 5
# Divide the result by 9
third_action = second_action / 9
# Show the final result
print(third_action)
# Water freeze temp
fahrenheit_to_celsius(32)
# Output
# 0.0The above logic is split into several parts for demonstrative purposes. The final function can be simplified to just one line of code inside the function.
def fahrenheit_to_celsius(fahrenheit_temp):
print((fahrenheit_temp - 32) * 5 / 9)
# Water boil temp
fahrenheit_to_celsius(212)
# Output
# 100.0A string at the beginning of a function’s body that summarizes its behavior and describes its arguments and return values is called a docstring. It starts and ends with three quotation marks (single or double quotes).
def fahrenheit_to_celsius(fahrenheit_temp):
"""
Convert a Fahrenheit temperature to Celsius
and return the result.
Parameter:
fahrenheit_temp (float): temperature in Fahrenheit
Returns:
celsius_temp (float): temperature in Celsius
"""
celsius_temp = ((fahrenheit_temp - 32) * 5 / 9)
return celsius_temp
print(fahrenheit_to_celsius(212))
# Output
# 100.0Functions and Methods
It’s important to distinguish functions from methods.
Methods are a specific type of functions. They are functions that belong to an object or class and can be used by calling them with a dot notation.
# Splitting a string into multiple strings with built-in split() method
to_do_things = "read remember repeat"
print(to_do_things.split())
# Output
# ['read', 'remember', 'repeat']
# Using the above method in a function
def tasks(to_dos):
print(to_dos.split())
tasks("learn grow prosper")
# Output
# ['learn', 'grow', 'prosper']Standalone functions don’t belong to any class and are often used with different types of objects.
sum_numbers = sum([4, 5])
print(sum_numbers)
# Output
# 9Python’s built-in functions can be found in the appropriate docs section.
Final Notes
To sum up, here are a few takeaways based on what we’ve discussed in this post:
- Python allows you to define and call functions.
- Function’s main components are: definition statement, body, and optional return statement (print can be used to display a value).
- Function header includes the def keyword, followed by the function’s name, parentheses, and a colon.
- Function body includes a block of code with instructions on what to do when the function is called.
- The return value is the result of function’s execution that it sends back when it’s called.
- Functions allow you to reuse common code.
- Functions can accept single or multiple parameters.
- Python built-in functions, like round(), can be used to simplify the logic and make the results easier to read.
- Comments explain how the code works and what the intended results are.
These were some of the basics of Python’s functions, return values, and general concepts around them. Hopefully, this was helpful.
Thank you for reading.







