Functions in Python
A function is a block of organized, reusable code which only runs when it is called. You can pass data or parameters into a function.
Syntax to create a function:
def name_of_function(arg1,arg2,arg3):
# Do coding here
# Return statement
It begins with def followed by function name.
args1,args2,args3 are the arguments which are input to the function. Indentation is very important. Then you can write a code inside it.
Let’s see an example:
- Print “hello world!”
def hello(): #hello.py
print('hello world!')hello() #call to a functionOutput:
hello world!
2. Using parameters:
def hello(name): #hello.py
print('hello',name)hello('john') #calling a functionOutput:
hello john
While calling hello function, we are passing ‘john’ as a parameter. ‘john’ will be copied into ‘name’ parameter of hello function and same is printed on console.
what if we don’t use parameter while calling a function ?
Let’s see…
def hello(name): #hello.py
print('hello',name)hello() #calling a function with no parameterOutput:
Traceback (most recent call last):
File "/home/main.py", line 11, in <module>
hello() #calling a function with no parameter
TypeError: hello() missing 1 required positional argument: 'name'
Let’s store the output of hello function hello into a variable.
def hello(name): #hello.py
print('hello',name)result=hello('john') # storing output of hello function to resultprint(result)
print(type(result)) #printing the type of resultOutput:
hello john
None
<class 'NoneType'>
What happened here ? ‘None’ is getting printed instead of ‘hello john’ .
Reason is function hello() is not returning any value and that’s why nothing is getting stored in result. Here, hello() function only printing a string. Now, question is, how to return value ?
Add ‘return’ statement at the end of function.
def hello(name): #hello.py
print(name)
return name #returning a string result=hello('john')print(type(result))Output:
john
<class 'str'>
Let’s write a function to identify if the number prime or not.
def is_prime(num):
for n in range(2,num):
if num % n == 0:
print(num,'is not prime')
break
else:
print(num,'is prime!')is_prime(17)
is_prime(4)Output:
17 is prime!
4 is not prime!
return statement appears only once in a function as function execution ends when return statement is reached.
Now, You have basic understanding of writing your own function and reuse it!
Happy Coding!