Best post on recursive function, scope of variable-5

Recursive function and Scope of Variables

This post explains about recursive functions with examples and scope of variables in python. Scope of variables can be local scope and global scope.

Let us have a quick glimpse on what is function?

A function is a block or package of organized , reusable lines of code for later execution.
Functions provide modularity to the script by breaking huge codes in small modules.
This helps to avoid repetition and increases re-usability.
Python provides various built-in functions like int(), sqrt(), list(), type() etc.
We can also create own functions in python, this is termed as user defined functions.

Recursive function

In python we have already explained how to define function and call a function.
Such functions defined by user are called as user defined functions.
Generally, function call is mention in main() and after executing this statement control is shifted to actual function definition.
When a function is called by itself in its own definition is termed as recursive function and the process is called as recursion.
Python stop calling recursive function after 1000 calls by default. If we provide value as 1000 it will show “RuntimeError: maximum recursion depth exceeded in comparison” as it will move from 0 to 999

Working of recursive function

  • Recursive function is called from main().
  • If the condition is met then the script executes statements and exits .
  • Else, function performs required processing and then calls itself to continue recursion

Example 1

"""
Author : ITVoyagers (itvoyagers.in)

Date :8th September 2020

Description : Program to find factorial using recursive function
"""
def facto(num):
    if num == 1:
        return 1
    else:
        return (num * facto(num-1))
print("Output of factorial using recursive function")
print("-------------------------------------------------")
n=int(input("Enter a number"))
if n<0:
    print("Factorial does not exists for negative number")
elif n==0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of",n,"is",facto(n))

Output

Output of factorial using recursive function
Output of factorial using recursive function

Example 2

"""
Author : ITVoyagers (itvoyagers.in)

Date :8th September 2020

Description : Program to find Fibonacci using recursive function
"""
def fibo(val):
    if val == 1 :
        return 0
    elif val == 2:
        return 1
    else:
        return (fibo(val-1)+fibo(val-2))
print("Output of fibonacci series using recursive function")
print("-------------------------------------------------")
n=int(input("Enter a number greater than 1      "))
for i in range(1,n):
    print(fibo(i))

Output

Output of Fibonacci using recursive function
Output of Fibonacci using recursive function

Scope of Variables

The scope of variable can be defined by the area of script where the variable is accessible.
The variables can be accessible either inside function body or outside function body.
Scope of variables can be classified as local scope and global scope and variables accessible in that scopes are classified as local variable and global variable respectively.

Local Variables

Variables declared inside a function body are accessible only that function and not outside the function are called as local variables.
Such variables are present in local scope.

Global Variables

Variables declared outside function body are accessible throughout that function body as well as outside the function are called as global variables.
Such variables are present in global scope.

Example

"""
Author : ITVoyagers (itvoyagers.in)

Date :8th September 2020

Description : Program to show local variables and global variables
"""
total=0                         #total is global variable in global scope
def add_me(a,b):
    #We can use both local and global variables inside function body
    total=a+b                 #a and b are local varibles in local scope
    print("Total value inside function is",total)
    return total
print("Output of local and global variables")
print("---------------------------------------")
x=add_me(10,20)         #x stores the value returned by funtion
total = x+5                   #total is global variable in global scope
print("Total value outside function is",total)

Output

Output of local and global variables
Output of local and global variables

Note: In above example along with local and global variables we have also seen how the function returns value and how that value can be used outside function definition.

For other python basics related posts:

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon.......



For other advanced python related posts:

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in 're' module(Part I)- Match vs Search
Functions in 're' module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon.......

Leave a Comment