top of page
Search
  • Writer's pictureHarshit Sharma

Function in Python

What are functions?

We have some predefined functions like the print function which is used to perform the function of printing a statement similarly we can create a function based upon our needs these are called as functions. The functions basically help us to reuse code.

The own function can be created by using the def statement in python.

Syntax: def functionname():

Statements

Example:

def onefunc():

print(“My first function”)

onefunc()

Calling function:The calling of the function is used to call the function is used to call by the name of the functionname() wherever you want to call the function.We must define the functions before calling the functions similar to the way like we declare variables.

Function Arguments: The function definition which we defined included no paremeters but when we define a function we can also provide some paremeters to the function.The parameters are known as arguments to the function which are added in the paranthesses of the function().

Syntax: def functionname(arguments list):

We can give as many arguments as we wish based upon our need in the function.

Example: def add(x,y)

print(x+y)

add(5,8)

add(10,6)

Whenever we use some function argument we can only use the arguments within the function but not outside the function.

Returning functions: The functions like integer and string types return some value which mean if we define some functions with int and str then it will return some values and so we use the return statement.

Example:

def largestno(a,b):

if a>=b:

return a

else:

return b

print(largestno(4,11))

As soon as the value will get return from the function the execution of the program will be terminated.

Function as objects:

Function can also be used as object by a means we can assign value to a variable which gets the data from the function and its parameters and stores in a variable .

Example:

def product(f,g):

return f*g

f=10

g=20

store=product

print(store(f,g))

Modules:The way we call functions in similar way like if we want to perform some operations without defining a function we can also use it with the help of modules through which we import a module and perform the task based on it as it is already defined in python library.

Syntax: from module_name import variable.

Or

import module_name

Example:

from math import sqrt as square_root

print(square_root(100))

1 view0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page