Introduction
In this lab, you will learn how to check if a function returns None in Python. The lab guides you through understanding function return values by creating a simple Python script with a function that returns the sum of two numbers. You will then execute the script and observe the output.
The lab continues by modifying the function to return different data types, and ultimately focuses on scenarios where a function might not explicitly return a value, resulting in a None return. You will learn how to capture the return value of a function and then check if that value is None using the is operator.
Learn About Function Return Values
In this step, you'll learn about function return values in Python. Functions are reusable blocks of code that perform specific tasks. Often, you'll want a function to give you back a result after it finishes its work. This result is called the return value.
Let's start by creating a simple Python script that defines a function with a return value.
Open the VS Code editor in the LabEx environment.
Create a new file named
calculate.pyin the~/projectdirectory.~/project/calculate.pyAdd the following code to
calculate.py:def add(x, y): """This function adds two numbers and returns the result.""" sum = x + y return sum ## Call the function and print the returned value result = add(5, 3) print(result)In this code:
- We define a function called
addthat takes two arguments,xandy. - Inside the function, we calculate the sum of
xandyand store it in a variable calledsum. - The
return sumstatement specifies that the function should return the value ofsumwhen it's called. - Outside the function, we call the
addfunction with the arguments5and3, and store the returned value in a variable calledresult. - Finally, we use the
print()function to display the value ofresult.
- We define a function called
Save the
calculate.pyfile.Open a terminal in the WebIDE.
Run the script using the following command:
python calculate.pyYou should see the following output:
8This output shows that the
addfunction correctly calculated the sum of 5 and 3, and returned the value 8, which was then printed to the console.
Now, let's modify the function to return a different type of value, such as a string.
Open the
calculate.pyfile in VS Code.Modify the code to the following:
def greet(name): """This function returns a greeting message.""" message = "Hello, " + name + "!" return message ## Call the function and print the returned value greeting = greet("LabEx User") print(greeting)In this code:
- We define a function called
greetthat takes one argument,name. - Inside the function, we create a greeting message by concatenating the string "Hello, ", the value of the
nameargument, and the string "!". - The
return messagestatement specifies that the function should return the greeting message. - Outside the function, we call the
greetfunction with the argument"LabEx User", and store the returned value in a variable calledgreeting. - Finally, we use the
print()function to display the value ofgreeting.
- We define a function called
Save the
calculate.pyfile.Run the script again using the following command:
python calculate.pyYou should see the following output:
Hello, LabEx User!This output shows that the
greetfunction correctly created a greeting message and returned it, which was then printed to the console.
Capture the Return Value
In the previous step, you learned how to define functions that return values. Now, you'll learn how to capture and use those return values in your programs. Capturing the return value means storing the value returned by a function in a variable so you can use it later.
Let's continue with the calculate.py file you created in the previous step. We'll modify the script to perform more operations and capture the return values.
Open the
calculate.pyfile in VS Code.Modify the code to the following:
def add(x, y): """This function adds two numbers and returns the result.""" sum = x + y return sum def subtract(x, y): """This function subtracts two numbers and returns the result.""" difference = x - y return difference ## Call the functions and capture the return values num1 = 10 num2 = 5 sum_result = add(num1, num2) print("The sum of", num1, "and", num2, "is:", sum_result) difference_result = subtract(num1, num2) print("The difference between", num1, "and", num2, "is:", difference_result)In this code:
- We define two functions:
addandsubtract. - We call the
addfunction with the argumentsnum1andnum2, and store the returned value in a variable calledsum_result. - We call the
subtractfunction with the argumentsnum1andnum2, and store the returned value in a variable calleddifference_result. - We use the
print()function to display the values ofsum_resultanddifference_result, along with descriptive text.
- We define two functions:
Save the
calculate.pyfile.Run the script using the following command:
python calculate.pyYou should see the following output:
The sum of 10 and 5 is: 15 The difference between 10 and 5 is: 5This output shows that we successfully captured the return values of the
addandsubtractfunctions and used them in our program.
Now, let's create a more complex example where we use the return value of one function as an argument to another function.
Open the
calculate.pyfile in VS Code.Modify the code to the following:
def add(x, y): """This function adds two numbers and returns the result.""" sum = x + y return sum def multiply(x, y): """This function multiplies two numbers and returns the result.""" product = x * y return product ## Call the functions and capture the return values num1 = 5 num2 = 3 sum_result = add(num1, num2) product_result = multiply(sum_result, 2) ## Use the return value of add as an argument to multiply print("The sum of", num1, "and", num2, "is:", sum_result) print("The product of the sum and 2 is:", product_result)In this code:
- We define two functions:
addandmultiply. - We call the
addfunction with the argumentsnum1andnum2, and store the returned value in a variable calledsum_result. - We call the
multiplyfunction with the argumentssum_resultand2. This demonstrates how the return value ofaddcan be used as an input tomultiply. We store the returned value in a variable calledproduct_result. - We use the
print()function to display the values ofsum_resultandproduct_result, along with descriptive text.
- We define two functions:
Save the
calculate.pyfile.Run the script using the following command:
python calculate.pyYou should see the following output:
The sum of 5 and 3 is: 8 The product of the sum and 2 is: 16This output shows that we successfully used the return value of one function as an argument to another function, demonstrating the power and flexibility of function return values.
Check If the Return Value Is None
In some cases, a function might not always return a meaningful value. In such situations, it can return None. None is a special value in Python that represents the absence of a value. It's important to check if a function returns None before using its return value to avoid errors.
Let's modify the calculate.py file to include a function that might return None.
Open the
calculate.pyfile in VS Code.Modify the code to the following:
def divide(x, y): """This function divides x by y and returns the result. If y is 0, it returns None to avoid division by zero errors. """ if y == 0: return None else: return x / y ## Call the function and check if the return value is None numerator = 10 denominator = 0 result = divide(numerator, denominator) if result is None: print("Cannot divide by zero!") else: print("The result of", numerator, "/", denominator, "is:", result) denominator = 2 result = divide(numerator, denominator) if result is None: print("Cannot divide by zero!") else: print("The result of", numerator, "/", denominator, "is:", result)In this code:
- We define a function called
dividethat takes two arguments,xandy. - Inside the function, we check if
yis equal to 0. If it is, we returnNoneto avoid a division by zero error. - If
yis not 0, we calculate the result ofx / yand return it. - Outside the function, we call the
dividefunction with a denominator of 0. - We check if the returned value is
Noneusing theisoperator. - If the returned value is
None, we print an error message. - Otherwise, we print the result of the division.
- We then call the
dividefunction again with a valid denominator and print the result.
- We define a function called
Save the
calculate.pyfile.Run the script using the following command:
python calculate.pyYou should see the following output:
Cannot divide by zero! The result of 10 / 2 is: 5.0This output shows that the program correctly handled the case where the denominator was 0 and printed an appropriate error message. It also shows that the program correctly calculated and printed the result when the denominator was not 0.
It's important to use the is operator to check if a value is None because None is a singleton object in Python. This means that there is only one instance of None in the entire program. Using the == operator might not always work correctly because it compares the values of the objects, not the objects themselves.
Summary
In this lab, you learned about function return values in Python. You created a function called add that takes two arguments, calculates their sum, and returns the result. You then called the function, stored the returned value in a variable, and printed it to the console.
The lab demonstrated how functions can return values of different types, such as integers. This allows functions to perform calculations or operations and provide the results back to the calling code for further use.



