SlideShare a Scribd company logo
1 of 3
Scope of Variables inPython
A variable isn’t visible everywhere and alive every time.
1. Scope
A variable’s scope tells us where in the program it is visible. A variable may have local or global
scope.
 Local Scope- A variable that’s declared inside a function has a local scope. In other words, it
is local to that function.
def fun():
s = "I love India!" #local
variable
print(s)
fun()
print(s)
output is :-
I love India
Name error s not defined
def fun():
s = "I love India!"
#local variable
print(s)
s = "I love World!"
fun()
print(s)
output is :-
I love India
I love World
def fun(x):
a=10 # local
x=x+10
print(a,x)
a,x= 1,2
fun(x)
print(a,x)
output is :-
(10, 12)
(1, 2)
Global Scope- When you declare a variable outside python function, or anything else, it has
global scope. It means that it is visible everywhere within the program.
However, you can’t change its value from inside a local scope(here, inside a function). To do so,
you must declare it global inside the function, using the ‘global’ keyword.
a=10 #global
def fun(x):
x=x+10
print(a,x)
x= 1
fun(x)
print(a,x)
output is :-
(10, 11)
(10, 1)
def fun(x):
global a
a=10
x=x+10
print(a,x)
a,x= 1,2
fun(x)
print(a,x)
output is :-
(10, 12)
(10, 2)
As we know in python, every thing is as object. If the value of the object is changed, it is
called mutable, while if the value of object cannot change, it is called immutable.Example of
immutable objects are int, float, tuple, bool and str. Example of immutable are list, dict and set.
Passing int variable to function Passing string to function
def change(a):
a=a+10
q=10
change(q)
print (q)
output is :-10
def count(str):
count = 0
for ch in str:
if ch in "aeiouAEIOU":
count +=1
return count
str="computer"
print (count(str))
output is :- 3
Passing tuple as
arguement
Passing list/ array as
arguement
Passing dictionary as argument
def change(marks):
for i in
range(len(marks)):
print (marks[i]),
li=(10,20,30,40)
change(li)
output is :- 10 20 30 40
def change(marks):
for i in range(len(marks)):
marks[i]+=10
li=[10,20,30,40]
change(li)
print (li)
output is :- [20, 30, 40, 50]
def change(d1):
d1['roll']=1
d1['sec']='a'
d1={ "name": "amit", "class":12}
change(d1)
print (d1)
output is :-
{'roll': 1, 'sec': 'a', 'name': 'amit', 'cla
ss': 12}
NOTE: The changes reflect back after calling function as for mutable data types by default (call
by refernce method). The changes does not reflect back after calling function as for immutable
data types by default (call by value method)
VALUE RETURNING FUNCTION
Single Value returning function Multiple Values returning function
def disp(A, B):// formal parameters
return (A+B)
X,Y=10,20
C=disp(X,Y)
def cal(a, b):
c=a+b
d=a-b
e=a*b
f=a/b
print ( C)
output is:- 30
g=a%b
return c,d,e,f,g
q=cal(10,20)
print (q)
output is:- (30, -10, 200, 0, 10)
In Python, comma-separated values are
considered tuples without parentheses
Note :- If functiondoes not have return statement in it then it return None
Passing Parameters to function
Required/Positional
arguments (have to pass in
the same order as used in
function definition)
Keyword Arguments (we
are not required to
remember the position of
argument)
Default
argument(always
should be last
argument)
Variable
length (any
no. of
arguments
can be
passed)
def cal(a, b, ch):
if ch=='+':
print (a+b)
elif ch=='-':
print (a-b)
elif ch=='*':
print (a*b)
elif ch=='/':
print (a/b)
elif ch=='%':
print (a%b)
cal(4,5,’+’)
x,y=20,30
c='*'
cal(x,y,c)
cal(c,x,y)#wrong (no
output)
output is :-
9
600
def cal(a, b, ch):
if ch=='+':
print (a+b)
elif ch=='-':
print (a-b)
elif ch=='*':
print (a*b)
elif ch=='/':
print (a/b)
elif ch=='%':
print (a%b)
cal(b=10,ch='%', a=30)
#keyword arguments
output is:-
0
def cal(a, b, ch='+'):
if ch=='+':
print (a+b)
elif ch=='-':
print (a-b)
elif ch=='*':
print (a*b)
elif ch=='/':
print (a/b)
elif ch=='%':
print (a%b)
cal(4,5)
cal(4,5,’*’)
output is:-
9
20
def sum(*
var):
s=0
for i in var:
s=s+i
print (s)
sum(10)
sum(10,20)
output is:-
10
30

More Related Content

Similar to functions.docx

Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approachFrancesco Bruni
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180Mahmoud Samir Fayed
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)ssuser7f90ae
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxhappycocoman
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYvikram mahendra
 

Similar to functions.docx (20)

Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180The Ring programming language version 1.5.1 book - Part 30 of 180
The Ring programming language version 1.5.1 book - Part 30 of 180
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Functions.docx
Functions.docxFunctions.docx
Functions.docx
 
Ch3
Ch3Ch3
Ch3
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 
Python programing
Python programingPython programing
Python programing
 
functions
functionsfunctions
functions
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAY
 

More from VandanaGoyal21

Database Query Using SQL_ip.docx
Database Query Using SQL_ip.docxDatabase Query Using SQL_ip.docx
Database Query Using SQL_ip.docxVandanaGoyal21
 
sample project-binary file.docx
sample project-binary file.docxsample project-binary file.docx
sample project-binary file.docxVandanaGoyal21
 
Computer Networks.docx
Computer Networks.docxComputer Networks.docx
Computer Networks.docxVandanaGoyal21
 
Computer Networks.docx
Computer Networks.docxComputer Networks.docx
Computer Networks.docxVandanaGoyal21
 
CLASS 10 IT PRACTICAL FILE.pdf
CLASS 10 IT PRACTICAL FILE.pdfCLASS 10 IT PRACTICAL FILE.pdf
CLASS 10 IT PRACTICAL FILE.pdfVandanaGoyal21
 
WEB APPLICATIONS 1.pdf
WEB APPLICATIONS 1.pdfWEB APPLICATIONS 1.pdf
WEB APPLICATIONS 1.pdfVandanaGoyal21
 

More from VandanaGoyal21 (8)

Database Query Using SQL_ip.docx
Database Query Using SQL_ip.docxDatabase Query Using SQL_ip.docx
Database Query Using SQL_ip.docx
 
sql_data.pdf
sql_data.pdfsql_data.pdf
sql_data.pdf
 
sample project-binary file.docx
sample project-binary file.docxsample project-binary file.docx
sample project-binary file.docx
 
STACK.docx
STACK.docxSTACK.docx
STACK.docx
 
Computer Networks.docx
Computer Networks.docxComputer Networks.docx
Computer Networks.docx
 
Computer Networks.docx
Computer Networks.docxComputer Networks.docx
Computer Networks.docx
 
CLASS 10 IT PRACTICAL FILE.pdf
CLASS 10 IT PRACTICAL FILE.pdfCLASS 10 IT PRACTICAL FILE.pdf
CLASS 10 IT PRACTICAL FILE.pdf
 
WEB APPLICATIONS 1.pdf
WEB APPLICATIONS 1.pdfWEB APPLICATIONS 1.pdf
WEB APPLICATIONS 1.pdf
 

Recently uploaded

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

functions.docx

  • 1. Scope of Variables inPython A variable isn’t visible everywhere and alive every time. 1. Scope A variable’s scope tells us where in the program it is visible. A variable may have local or global scope.  Local Scope- A variable that’s declared inside a function has a local scope. In other words, it is local to that function. def fun(): s = "I love India!" #local variable print(s) fun() print(s) output is :- I love India Name error s not defined def fun(): s = "I love India!" #local variable print(s) s = "I love World!" fun() print(s) output is :- I love India I love World def fun(x): a=10 # local x=x+10 print(a,x) a,x= 1,2 fun(x) print(a,x) output is :- (10, 12) (1, 2) Global Scope- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program. However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the ‘global’ keyword. a=10 #global def fun(x): x=x+10 print(a,x) x= 1 fun(x) print(a,x) output is :- (10, 11) (10, 1) def fun(x): global a a=10 x=x+10 print(a,x) a,x= 1,2 fun(x) print(a,x) output is :- (10, 12) (10, 2)
  • 2. As we know in python, every thing is as object. If the value of the object is changed, it is called mutable, while if the value of object cannot change, it is called immutable.Example of immutable objects are int, float, tuple, bool and str. Example of immutable are list, dict and set. Passing int variable to function Passing string to function def change(a): a=a+10 q=10 change(q) print (q) output is :-10 def count(str): count = 0 for ch in str: if ch in "aeiouAEIOU": count +=1 return count str="computer" print (count(str)) output is :- 3 Passing tuple as arguement Passing list/ array as arguement Passing dictionary as argument def change(marks): for i in range(len(marks)): print (marks[i]), li=(10,20,30,40) change(li) output is :- 10 20 30 40 def change(marks): for i in range(len(marks)): marks[i]+=10 li=[10,20,30,40] change(li) print (li) output is :- [20, 30, 40, 50] def change(d1): d1['roll']=1 d1['sec']='a' d1={ "name": "amit", "class":12} change(d1) print (d1) output is :- {'roll': 1, 'sec': 'a', 'name': 'amit', 'cla ss': 12} NOTE: The changes reflect back after calling function as for mutable data types by default (call by refernce method). The changes does not reflect back after calling function as for immutable data types by default (call by value method) VALUE RETURNING FUNCTION Single Value returning function Multiple Values returning function def disp(A, B):// formal parameters return (A+B) X,Y=10,20 C=disp(X,Y) def cal(a, b): c=a+b d=a-b e=a*b f=a/b
  • 3. print ( C) output is:- 30 g=a%b return c,d,e,f,g q=cal(10,20) print (q) output is:- (30, -10, 200, 0, 10) In Python, comma-separated values are considered tuples without parentheses Note :- If functiondoes not have return statement in it then it return None Passing Parameters to function Required/Positional arguments (have to pass in the same order as used in function definition) Keyword Arguments (we are not required to remember the position of argument) Default argument(always should be last argument) Variable length (any no. of arguments can be passed) def cal(a, b, ch): if ch=='+': print (a+b) elif ch=='-': print (a-b) elif ch=='*': print (a*b) elif ch=='/': print (a/b) elif ch=='%': print (a%b) cal(4,5,’+’) x,y=20,30 c='*' cal(x,y,c) cal(c,x,y)#wrong (no output) output is :- 9 600 def cal(a, b, ch): if ch=='+': print (a+b) elif ch=='-': print (a-b) elif ch=='*': print (a*b) elif ch=='/': print (a/b) elif ch=='%': print (a%b) cal(b=10,ch='%', a=30) #keyword arguments output is:- 0 def cal(a, b, ch='+'): if ch=='+': print (a+b) elif ch=='-': print (a-b) elif ch=='*': print (a*b) elif ch=='/': print (a/b) elif ch=='%': print (a%b) cal(4,5) cal(4,5,’*’) output is:- 9 20 def sum(* var): s=0 for i in var: s=s+i print (s) sum(10) sum(10,20) output is:- 10 30