Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

What are the Python Functions and how to create them?

Functions are the re-usable set of code which helps to organize structure of the code.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
Functions are created so that we can run a  statements multiple times during the program without repeating ourselves.
Creating functions in Python
In Python  def keyword is used to start a function.
def functionname(arg1, arg2, .... argN):
 #statement inside the function
Body of the function can be omitted by using the pass keyword.E.g:
def myfirstfunc():
 pass

def sum(start, end):
 answer = 0
 for i in range(start, end + 1):
 answer += i
 print(result)
 sum(20, 60)

sum(start, end) function calculates the sum of all the numbers starting from start to end.
Function with return value
The return statement sends a result back to the caller and exits the function.
def sum(start, end):
 answer = 0
 for i in range(start, end + 1):
 answer += i
 return answer
 s = sum(20, 60)
print(s)

Return multiple values from Function
Return statement can be used to return multiple values from function by separating them with a comma. 
Multiple values are returned as tuples.
def greater(x, y):    
if x > y:        
return x, y     
else:        
return x, y
 s = greater(5, 10)
print(s)
 print(type(s))
CONTINUE READING
Python
Functions
Python Programming
Ayesha
Tech writer at newsandstory