Python programming example How to use return

Mondo Fashionable Updated on 2024-01-19

In the Python programming language, the return statement has a very important purpose. It is used to return a value from a function in order to get the result when the function is called. The return statement can be used with a variety of data types, such as integers, floats, strings, lists, and so on.

Here are some examples of how to use the return statement:

1.Returns an integer:

def add(a, b):

result = a + b

return result

x = 5y = 3

sum = add(x, y)

print("sum =", sum)

In this example, the function add() takes two integers as arguments, adds them up and returns the result. When the function is called, the return value is stored in the variable sum and printed.

2.Returns a floating-point number:

def multiply(a, b):

result = a * b

return result

x = 5.5

y = 4.0

product = multiply(x, y)

print("product =", product)

In this example, the function multiply() takes two floating-point numbers as arguments, multiplies them and returns the result. When this function is called, the return value is stored in the variable product and printed.

3.Returns a string:

def concatenate(a, b):

result = a + b

return result

x = "hello"

y = "world"

message = concatenate(x, y)

print("message =", message)

In this example, the function concatenate() takes two strings as arguments, concatenates them and returns a result. When the function is called, the return value is stored in the variable message and printed.

4.Back to a list:

def list_sort(lst):

lst.sort()

return lst

numbers = [5, 2, 9, 1, 5, 6]

sorted_numbers = list_sort(numbers)

print("sorted numbers =", sorted_numbers)

In this example, the list sort() function takes a list as a parameter, sorts the list, and returns the sorted result. When the function is called, the return value is stored in the variable sorted numbers and printed.

5.Returns multiple values:

def add_subtract(a, b):

sum = a + b

diff = a - b

return sum, diff

result = add_subtract(10, 5)

print(result) output: (15, 5).

In this example, the function add subtract calculates the sum and difference of two numbers and returns both results by returning a tuple (sum, diff). When we call the function, we assign the resulting tuple to the variable result, and then print the result with print(result).

It's important to note that returning multiple values is not the same as returning a composite type with multiple elements, such as a list or tuple. Returning Multiple Values means that a function directly returns multiple independent values that can be assigned to different variables. Returning a composite value, on the other hand, requires assigning it to a variable, which then uses that variable to access the elements in it.

Related Pages