Functions in Python
Functions in Python
What is a function
def greet():
print('Hello World!’)
def greet():
print('Hello World!’)
def greet():
print('Hello World!')
print('Outside function')
Output
Hello World!
Outside functio
Working of Python Function
Here,
1.When the function greet() is called, the program's
control transfers to the function definition.
2.All the code inside the function is executed.
3.The control of the program jumps to the next statement
after the function call.
Python Function Arguments
# pass argument
greet("MOHAMED")
Output
Hello Mohamed
Here, we passed 'John' as an argument to the greet() function.
We can pass different arguments in each call, making the function re-usable and greet("Mohamed")
dynamic. Output
Let's call the function with a different argument. Hello Mohamed
Example: Function to Add Two
Numbers
Output
Sum: 9
In the above example, we have created a function named add_numbers() with arguments: num1 and num2.
The return Statement
# function call
square = find_square(3)
print('Square:', square)
Square: 9
Output
In the above example, we have created a function named find_square(). The function accepts a number and returns the square of the
number.
Note: The return statement also denotes that the function has ended. Any code after return is not executed.
Python Library Functions
Python provides some built-in functions that can be directly used in our program.
We don't need to create the function, we just need to call them.
Some Python library functions are:
1.print() - prints the string inside the quotation marks
2.sqrt() - returns the square root of a number
3.pow() - returns the power of a number
These library functions are defined inside the module. And to use them, we must include the module inside
our program.
For example, sqrt() is defined inside the math module.
Example: Python Library Function
import math
Here, we imported a math module to use the library functions sqrt() and pow().
Read more
Python Library Functions
Python input()
reads and returns a line of string Python help()
Invokes the built-in Help System
Python complex()
Creates a Complex Number Python int()
returns integer from a number or string
Python chr()
Returns a Character (a string) from an Integer Python list()
creates a list in Python
Python abs()
returns absolute value of a number Python len()
Returns Length of an Object
Python float()
returns floating point number from number, string Python max()
returns the largest item
Read more
Python Library Functions
Python min()
returns the smallest value Python str()
returns the string version of the object
Python pow()
returns the power of a number Python sum()
Adds items of an Iterable
Python print()
Prints the Given Object
Python range() Function
returns a sequence of numbers
Python round()
rounds a number to specified decimals