DEV Community

Cover image for Learning Python- Intermediate course: Day 2, returning values from methods.
Aatmaj
Aatmaj

Posted on • Updated on

Learning Python- Intermediate course: Day 2, returning values from methods.

Today we will learn how to return values from user defined functions.


In the previous part, we covered user-defined functions which did not return any value. But today we will learn how to make functions that return Python data types. This means that now instead of just printing the values, we will now use them in our main code!

Returning values.

When we say return a value, it simply means- give the final result back to the part of code which called the function.
The return statements can be only called from within a function. After the return statement is called, the function code terminates. This means that the statements after the return statement are not run!
Here is the syntax

def fun(..,..,..):
    ...
    ...
    ...
    return ...

Enter fullscreen mode Exit fullscreen mode

Sample question - Write a function isodd() to check parity of numbers.

def isodd(a):
    if(a%2==0):
        return True
    else:
        return False
print(isodd(5))
Enter fullscreen mode Exit fullscreen mode
False
Enter fullscreen mode Exit fullscreen mode

Run the code yourself and check for different values.

Exercise 1- What will happen if the else statement is removed in the above code? Answer


Returning multiple values

We cannot directly return multiple values in Python, but there are many hacks The best among them is returning a list of values.

Sample question 2- Write a function to return the smallest two entries from a given list

def SmallestTwo(a):
    a.sort()
    return [a[0],a[1]]
myList=[1,4,13,7,5,9,12,3,6]
print(SmallestTwo(myList))
Enter fullscreen mode Exit fullscreen mode
[1, 3]
Enter fullscreen mode Exit fullscreen mode

Exercise 2- Write a function to reverse a string. Answer

Oldest comments (0)