20
Learning Python- Intermediate course: Day 2, returning values from methods.
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!
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 ...
def isodd(a):
if(a%2==0):
return True
else:
return False
print(isodd(5))
False
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
We cannot directly return multiple values in Python, but there are many hacks The best among them is returning a list of values.
def SmallestTwo(a):
a.sort()
return [a[0],a[1]]
myList=[1,4,13,7,5,9,12,3,6]
print(SmallestTwo(myList))
[1, 3]
Exercise 2- Write a function to reverse a string. Answer
20