python function with arguments
In this tutorial, you will learn about python function with arguments with example. We need function parameters almost always. Arguments are used when we want to pass data to our function. When we call a function we pass arguments to the function.
Example:-
def my_function(food):
for x in food:
print(x)
fruits = ["cherry", "banana", "Apple"]
my_function(fruits)Run e
O/p:-
banana
Cherry
Apple
Nested function in Python
Functions are the first citizen of python means the functions is same as the interger, strings, etc. They can be created as well as destroyed passed to other functions. The nested functions can access variables of the enclosing scope. In Python, the non-local variables are read only by default. We must declare them explicitly as non-local to modify them. The function which is defined inside another function is known as nested function. Nested functions are able to access variables of the enclosing scope.
These non-local variables can be accessed within their scope and not outside their scope.
The non-local variables are read only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
If there are some lines of code inside a function (or method) which are repeating multiple times. You can put them inside a separate method and call the method where those lines are required instead of repeating. This prevents repeating lines of code as they are encapsulated in a single method which is called where those lines are required as shown below. Like nested loops, we also have nested functions in python.
We create a function using def inside another function to nest two functions.
Example:-
def f1():
Print(“Hello”)
def f2():
Print(“Python”)
f2()
f1()
Output:-
Hello
Python