In this tutorial, you will learn about recursion function in python with example. The term recursion involves process of calling itself in definition. The physical word would be to place two parallel mirrors facing each other. If any object is present in between the mirrors then it is reflected recursively. Recursion also work like the loop. In recursion function term the function will call continue to call itself and repeat its behavior until condition met to return the result. The recursive function is defined in term of itself via self referential expressions. If we want to repeat the task, we usually think about for and while loop. In some cases the function makes more sense to use recursive loop and convert any loop to recursion. The condition which is repeatedly followed and not stopped is called as base condition. Base condition plays an important role in every recursive program otherwise it will continue to execute like infinite loop.
Example:-
We have function xyz() in body of xyz() there is call to xyz().
The output is 24.
The example is with recursive function.
Example:-
def factorial(n):
f=1
while n>0:
f*=n
n=1
print(f)
factorial(4)
O/p:-
24
Global variable are the one that defined and declared outside a function need to use them inside a function.
Example:-
def f():
print s
s=”I love python”
f() |
O/p:-
I love python
Variable declaration example in python:-
A=20
Print a
The redeclaration of the variable is also possible after declaration.
There are two types of variables in python:-
O/p:-
Local variable
x = "Python"
def foo():
print("x inside :", x)
foo()
print("x outside:", x)
O/p:-
x inside : Python
x inside :Python
In above example we have x as global variable and define foo() to print the global
Variable x.
Then call foo() which will print value of x.
Now the both variables are declared in same code.
Example:-
x = "hello"
def foo():
global x
y = "python"
x = x * 2
print(x)
print(y)
foo()
O/p:-
hello hello
python