In this Python tutorial, we will learn about Python Return Function. Also, we will cover these topics.
- Python Return Function Explained
- Python Return Function Name
- Python Return Function Example
- Python Return Function With Arguments
- Python Return Function From Function
- Python Return Function Object
- Python Return Function Value
- Python Return Function Not Working
Python Return Function Explained
In this section, we will learn about the return function in python. We will understand its meaning, purpose, and syntax.
- Functions are created to perform some task and this entire process is divided into three parts.
- accepting argument
- processing the argument
- producing result
- Return function is used at the third step that is producting or returning result. This result is also called ‘value’ or return.
- Function return None by default, in other words, if the programmer do not specify return value then None is returned.
Syntax:
def somefunction():
-- some operations here --
return value
Python Return Function name
In this section, we will learn about the python return function name.
- Using
__name__
method, we can return the function name in the python program. - In our example, we have created a function with the name ‘basket’ and then we have returned
basket.__name__
. - Everytime this function will be called function name will be printed on the display screen.
- Here is the implementation of the above example.
def basket():
return basket.__name__
print(basket())
Output:
In this output, you can see that the function name is a basket and when the function is called it returned the output as the basket which is the function name.
Python Return Function Example
In this section, we will see the python return function example.
- In our example, we have created a function that accepts two numbers and checks if both the numbers are even then add them otherwise multiplies them.
def addEven(n, m):
if n%2 == 0 and m%2 == 0:
return n+m
else:
return n*m
print(addEven(2,2))
print(addEven(2,3))
Output:
Read Python built-in functions with examples
Python Return Function with Arguments
In this section, we will learn about the python return function with arguments.
- Arguments refer to parameter provided by user. At times, function needs user input to fulfill the process requirement.
- At that time argument is created and user has to provide the requested value while calling the function.
- In our example, we have created a function that accepts two numbers as an arguments anc checks if these numbers are even then adds them otherwise multiplies them.
Source Code:
In this code, a function is created with the name addEven(). This function accepts 2 arguments.
If both the arguments are even then the function returns the addition of those numbers otherwise the function returns the multiplication of numbers.
def addEven(n, m):
if n%2 == 0 and m%2 == 0:
return n+m
else:
return n*m
print(addEven(2,2))
print(addEven(2,3))
Output:
In this output, addEven() function accepts two numbers. If these numbers are even then both the numbers will be added otherwise numbers will be multiplied.
In Line 8, we have provided even arguments so their result is 4 (2+2). In line 9, we have provided odd arguments so their result is 6 (2*3).
Read Function in Python
Python Return Function From Function
In this section, we will learn how to call a python return function from a function.
- This method is not similar to function calling function because in that same function is called within that function.
- In this we have two or more functions and we will call other functions with the first function.
- This technique is widely used in object oriented programming wherein main function calls other functions in a sequence.
- In our example, we will create 3 functions:
- main function
- add function
- subtract function
- the main function will accept argument and depending upon that it will call any one function out the two.
- The program name is ‘Money Tracker’, user will provide two inputs as an argument.
- amount is the money he want to credit or debit.
- ‘+‘ or ‘–‘ signs, ‘+’ will add the entered amount whereas ‘-‘ will subtract the amount.
Source Code:
In this code, we have declared the total balance as $565. three functions are created addMoney(), subMoney(), main()
- addMoney() function will accept the amount from user, add it to the current balance, and return the message displaying updated current balance.
- subMonet() function will accept the amount from user, subtract the amount from current balance, and return the message displaying updated current balance.
- main() function accepts two arguments, amount and sign. Sign could be positive(+) or Negative(-). If sign is possitive(+) than addMoney() function will be called inside the main() function and amount will credited to current blance. Otherwise if sign is negative (-) than subMoney() function will be called and amount will be debited from current balance.
bal = 565
print(f'''
+-------------------------+
Total Balance: ${bal}
+-------------------------+
''')
def addMoney(m):
global bal
bal += m
return f'Current Balance: ${bal}'
def subMoney(m):
global bal
bal -= m
return f'Current Balance: ${bal}'
def main(m, s):
global bal
if s == '-':
return subMoney(m)
elif s == '+':
return addMoney(m)
else:
return print('incorrect input!')
amt = int(input('Enter Amount: '))
sign = input('Debit(-) or Credit(+): ')
print(main(amt, sign))
Output:
In this output, $200 has been debited from the total balance. Marking shows the user input and output as the current balance.
Python Return Function Object
In this section, we will learn about the python return function objects.
- Objects are created during object-oriented programming (Oops). Object is the instance of class.
- Using return keyword followed by ‘
self.value
‘ we can return object in Python. - In our example, we have created a Animal class. In this class we have created method and other functions that are the attributes of an animal.
- Common attributes of animal are they have name, they are carnvior, omnivor or herbivor, they attack in different ways & they all make sound.
- Object is created with the name given to that animal like cooper in our case.
- finally when the progam will be run it display a complete message. Here is source code.
class Animal:
def __init__(self, name, type, attack, sound):
self.name = name
self.type = type
self.attack = attack
self.sound = sound
def sound(self):
return self.sound
def type(self):
return self.type
def attack(self):
return self.attack
def name(self):
return self.name
cooper = Animal('dog', 'carnvior', 'sharp teeth', 'bark' )
print(f'{cooper.name} is a {cooper.type} animal, who {cooper.sound} & tear down enemies with {cooper.attack}' )
Output:
In this output, using all the objects a meaningful message is created.
Check out, Python input and raw_input function
Python Return Function Value
In this section, we will learn about the python return function value.
- Value is the final output that you want to display when the function is called.
- Value can be of any data type (String, Integer, Boolean)
- Function processes the information and generates an output which is called value. Return keyword is used before the value
- In our example, we have performed sum of digits.
Source Code:
def sum_of_digits(n):
t = 0
while n != 0:
r = n%10
t = t + r
n = n//10
return t
print(sum_of_digits(1123))
Output:
In this output, the function is returning the sum of digits. If the number is 1123 then the output will be 1+1+2+3=7. There is more than one possibility of returning the other values like r, n, t but we have returned the value of t.
Read Python Tkinter Map() Function
Python Return Function Not Working
In this section, we will cover solutions for the python return function not working. There could be various reasons why the function is not returning desirable results. But we are assuming that the source code for the logic is correct.
- Indentation misplacement: Indentation plays an important role in python. Indentation tells the intepreter that this part of code belongs to this statement. While coding a function at times we put the return value at wrong indentation due to which unexpected results appear.
- In the above example, return is placed inside the loop and the output is 0. This is because return runs only once so whatever the output appear in the first iteration of the loop is returned as a result.
- The result is 0 because res = 10 * 0, Here i=0. Though the loops runs 5 times but result is produced for the first iteration only.
- In this way, you might be expecting result as 40 (10*0, 10*1, 10*2, 10*3, 10*4). But the program gave you 0. By placing return outside the loop will fix this issue. Here is an example of python return function after rectifying indentation.
2. SyntaxError: ‘return’ outside function: If you are seeing this error that means you have placed the return statement parallel to function.
res = 0
def multiply_five_times(n):
global res
for i in range(5):
res = n * i
return res
- In the above code, return is placed paralley to the function. In other words, it is outside the function.
- To fix this issue, shift the return function inwards. Here is how you can fix it.
res = 0
def multiply_five_times(n):
global res
for i in range(5):
res = n * i
return res
3. Function created but not called: This is the most common mistake that we all have done at least once in our programming career. Once you have created a function, you have to use it by calling it in the program wherever it is required. This is not an error but you won’t see any results after running the program.
You may also like the following Python tutorials:
- Python Turtle Write Function
- If not condition in python
- Python Dictionary duplicate keys
- Python Tkinter Filter Function()
- How to use filter function in Python
- Python Tkinter add function with examples
- Python zip() Function Examples
- Download zip file from URL using python
- How to Drop Duplicates using drop_duplicates() function in Python Pandas
In this tutorial, we have learned about Python Return Function. Also, we have covered these topics.
- Python Return Function Explained
- Python Return Function Name
- Python Return Function Example
- Python Return Function With Arguments
- Python Return Function From Function
- Python Return Function Object
- Python Return Function Value
- Python Return Function Not Working
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.