Python Functions
What are Functions?
A function is a small piece of code that aims to perform a particular task. Functions take an argument as an input and return an output after completing some set of actions on the input. Once defined, Functions can be called numerous times without defining them repeatedly. Thus, functions make the code reusable.
How to define a function in Python?
In Python, a function can be defined by making use of def keyword. We then specify a function name and write the function code after putting a colon ":" after the function name. Like this
def firstPythonFunction(): #Defining a Function
print("First Python function executed")
myFunction() #Calling a Function
Output:
A function can be defined with the arguments and a return statement, like this
def square(num): #Defining a Function
return num*num
print(square(9)) #Calling a Function
Output:
If there is no return statement in the function's body, then it returns None.
def hello(name): #Defining a Function
print("Hello",name)
print(hello("John")) #Calling a Function
Output:
Note:-The body of the function must be specified with proper indentation.
Function with multiple arguments
In Python, multiple arguments in the function can be specified by separating each argument with the commas ",".
def hello(name, city): #Defining a Function
print("Hello",name,"from", city)
hello("John", "San Francisco") #Calling a Function
Output:
Optional arguments can be specified for a function. The only thing we need to do is specify the default values for arguments.
def hello(name, country="USA"): #Defining a Function
print("Hello",name,"from", country)
hello("John", "San Francisco") #Calling a Function
hello("John") #Calling a Function
Output:
Here you can see, the country argument is optional. If any value is not specified for this argument, the default value "India" will be used. If a value is specified for this argument, the default value gets overwritten by the specified value.
We must define the optional arguments after the non-optional arguments, i.e., all the optional arguments will be on the right hand side of the non-optional arguments. So, something like this can't be done
def hello(name, country="USA", age): #Defining a Function
print("Hello",name,age,"years old","from", country)
hello("John", "San Francisco", 19) #Calling a Function
Output:
The above example can be corrected like this
def hello(name, age,country="USA"): #Defining a Function
print("Hello",name,age,"years old","from", country)
hello("John", 22,"San Francisco") #Calling a Function
Output:
Also, by default, while making a function call, the argument values are assigned to the corresponding argument depending upon the position of the value. Keyword arguments can be used to specify the argument value independent of their position. Like this
def hello(name, age,country="USA"): #Defining a Function
print("Hello",name,age,"years old","from", country)
hello(country="San Francisco", age=22, name="John") #Calling a Function
Output:
The keyword name must be exactly same as the argument name spe cified in the function definition.
Docstring in a Function
A Docstring is a description of the function, class, or module. It briefly explains what a function does. It can be specified using the triple quotation strings right after the function definition. Like this
def hello(name, age,country="USA"): #Defining a Function
'''returns a greet message''' #Function Docstring
print("Hello",name,age,"years old","from", country)
hello(country="San Francisco", age=22, name="John") #Calling a Function
Output:
We can access the Docstring of function using the __doc__ attribute. Like this
def hello(name, age,country="India"): #Defining a Function
'''returns a greet message''' #Function Docstring
print("Hello",name,age,"years old","from", country)
print(hello.__doc__)
Output:
Types of Functions
Functions are basically categorised into two types:
- In-built Functions
- User-defined Functions
Built-in Functions
There are many built-in functions available in Python. These are:
Function | Description |
---|---|
len() | Returns the length of an object |
abs() | Returns absolute value of number |
all() | Returns True if all the elements in an iterable are True else returns False If iterable is empty then also returns True |
any() | Returns True if any elements in the iterable are True else returns False If iterable is empty then also returns False |
ascii() | Returns ASCII representation of an object |
bin() | Returns Binary representation of an object |
bool() | Returns True when the argument is True Returns False when the argument is False |
bytearray() | Returns array having a given size |
bytes() | Returns immutable array having a given size |
hash() | Returns hash of the object |
getattr() | Returns the named attributes of an object |
input() | Takes input from the standard input in the form of a string |
list() | Creates a list from the object given. If no argument is provided, it creates an empty list |
max() | It returns the largest element from an iterable object |
min() | It returns the smallest element from an iterable object |
next() | It returns the next element from the iterator |
open() | It opens a file and also returns a stream fo character. |
pow() | Returns the number raised to a power |
print() | Prints the argument to the standard output or a stream |
reversed() | It returns a reverse iterator for a sequence |
set() | Creates a set from the object given. If no argument is provided, it creates an empty set |
slice() | Creates a slice of the object or sequence |
sorted() | Returns a new list containing the elements of the given list in ascending order |
tuple() | Creates a tuple from the object given. If no argument is provided, it creates an empty tuple |
zip() | Returns iterator of tuples |
__import__() | Imports a module |
type() | This function returns the type of the given object |
callable() | Callable function resultsTrue if the object is callable else it is False |
chr() | This function returns a unicode string of one character with ordinal |
classmethod() | It changes a function to a class method |
compile() | Complex source into a code object |
complex() | Returns complex number with the given real and imaginary parts |
dict() | Creates a dict from the object given. If the argument is not given, it creates an empty dict |
enumerate() | Returns pairs containing count and values of the iterable argument |
range() | Returns a sequence of numbers between a given range |
filter() | It passes all the elements to the given argument function one by one and returns the elements for which the function becomes True. |
map() | It passes all the elements to a given argument function one by one, and the output elements are returned by the argument function |
float() | Converts a given type to float type |
format() | Return formatted representation of a value |