SlideShare una empresa de Scribd logo
1 de 17
K.S.R COLLEGE OF ENGINEERING
TIRUCHENGODE-637 215.(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON PROGRAMMING[20CS311]
FUNCTIONS
PRESENTED BY
S.SOUNDARYA,
73152213091,
II YEAR/CSE/B.
Python - Functions
• A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provides better
modularity for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These
functions are called user-defined functions.
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these
parentheses.
• The code block within every function starts with a colon (:) and is
indented.
• The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with no
arguments is the same as return None.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need
to inform them in the same order that they were defined.
• Example:
def printme( str ):
"This prints a passed string function"
print str
return
Syntax
Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print str;
return;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
• This would produce following result:
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within
a function, the change also reflects back in the calling function. For
example:
def changeme( mylist ): "This changes a passed list“
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference
but inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes
nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments:
A function by using the following types of formal arguments::
– Required arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Required arguments:
• Required arguments are the arguments passed to a function in correct
positional order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:
• Keyword arguments are related to the function calls. When
you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
• This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords
provided to match the values with parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
Default arguments:
• A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
• Following example gives idea on default arguments, it would
print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
• You may need to process a function for more arguments than
you specified while defining the function. These arguments
are called variable-length arguments and are not named in
the function definition, unlike required and default
arguments.
• The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
• An asterisk (*) is placed before the variable name that will
hold the values of all nonkeyword variable arguments. This
tuple remains empty if no additional arguments are specified
during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions.
These functions are called anonymous because they are not
declared in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just
one value in the form of an expression. They cannot contain
commands or multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression.
• Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
• Although it appears that lambda's are a one-line version of a
function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
• Following is the example to show how lembda form of
function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables:
• All variables in a program may not be accessible at all locations in
that program. This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program
where you can access a particular identifier. There are two basic
scopes of variables in Python:
Global variables
Local variables
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
• This means that local variables can be accessed only inside the
function in which they are declared whereas global variables can be
accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into
scope.
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0

Más contenido relacionado

Similar a Python programming variables and comment

Similar a Python programming variables and comment (20)

Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
L14-L16 Functions.pdf
L14-L16 Functions.pdfL14-L16 Functions.pdf
L14-L16 Functions.pdf
 
Functions
FunctionsFunctions
Functions
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Python functions
Python   functionsPython   functions
Python functions
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Python functions
Python functionsPython functions
Python functions
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Function
FunctionFunction
Function
 

Más de MalligaarjunanN

bro_nodejs-1 front end development .pdf
bro_nodejs-1 front end development  .pdfbro_nodejs-1 front end development  .pdf
bro_nodejs-1 front end development .pdfMalligaarjunanN
 
Microprocessor and microcontroller record.pdf
Microprocessor and microcontroller record.pdfMicroprocessor and microcontroller record.pdf
Microprocessor and microcontroller record.pdfMalligaarjunanN
 
8087 MICROPROCESSOR and diagram with definition.pdf
8087 MICROPROCESSOR and diagram with definition.pdf8087 MICROPROCESSOR and diagram with definition.pdf
8087 MICROPROCESSOR and diagram with definition.pdfMalligaarjunanN
 
8089 microprocessor with diagram and analytical
8089 microprocessor with diagram and analytical8089 microprocessor with diagram and analytical
8089 microprocessor with diagram and analyticalMalligaarjunanN
 
English article power point presentation eng.pptx
English article power point presentation eng.pptxEnglish article power point presentation eng.pptx
English article power point presentation eng.pptxMalligaarjunanN
 
Digital principle and computer design Presentation (1).pptx
Digital principle and computer design Presentation (1).pptxDigital principle and computer design Presentation (1).pptx
Digital principle and computer design Presentation (1).pptxMalligaarjunanN
 
Technical English grammar and tenses.pptx
Technical English grammar and tenses.pptxTechnical English grammar and tenses.pptx
Technical English grammar and tenses.pptxMalligaarjunanN
 
Polymorphism topic power point presentation li.pptx
Polymorphism topic power point presentation li.pptxPolymorphism topic power point presentation li.pptx
Polymorphism topic power point presentation li.pptxMalligaarjunanN
 
Chemistry iconic bond topic chem ppt.pptx
Chemistry iconic bond topic chem ppt.pptxChemistry iconic bond topic chem ppt.pptx
Chemistry iconic bond topic chem ppt.pptxMalligaarjunanN
 
C programming DOC-20230723-WA0001..pptx
C programming  DOC-20230723-WA0001..pptxC programming  DOC-20230723-WA0001..pptx
C programming DOC-20230723-WA0001..pptxMalligaarjunanN
 
Chemistry fluorescent topic chemistry.pptx
Chemistry fluorescent topic  chemistry.pptxChemistry fluorescent topic  chemistry.pptx
Chemistry fluorescent topic chemistry.pptxMalligaarjunanN
 
C programming power point presentation c ppt.pptx
C programming power point presentation c ppt.pptxC programming power point presentation c ppt.pptx
C programming power point presentation c ppt.pptxMalligaarjunanN
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxMalligaarjunanN
 
Python programming file handling mhhk.pptx
Python programming file handling mhhk.pptxPython programming file handling mhhk.pptx
Python programming file handling mhhk.pptxMalligaarjunanN
 
Computer organisation and architecture updated unit 2 COA ppt.pptx
Computer organisation and architecture updated unit 2 COA ppt.pptxComputer organisation and architecture updated unit 2 COA ppt.pptx
Computer organisation and architecture updated unit 2 COA ppt.pptxMalligaarjunanN
 
Data structures trees and graphs - Heap Tree.pptx
Data structures trees and graphs - Heap Tree.pptxData structures trees and graphs - Heap Tree.pptx
Data structures trees and graphs - Heap Tree.pptxMalligaarjunanN
 
Data structures trees and graphs - AVL tree.pptx
Data structures trees and graphs - AVL  tree.pptxData structures trees and graphs - AVL  tree.pptx
Data structures trees and graphs - AVL tree.pptxMalligaarjunanN
 
Data structures trees - B Tree & B+Tree.pptx
Data structures trees - B Tree & B+Tree.pptxData structures trees - B Tree & B+Tree.pptx
Data structures trees - B Tree & B+Tree.pptxMalligaarjunanN
 
Computer organisation and architecture .
Computer organisation and architecture .Computer organisation and architecture .
Computer organisation and architecture .MalligaarjunanN
 
pythoncommentsandvariables-231016105804-9a780b91 (1).pptx
pythoncommentsandvariables-231016105804-9a780b91 (1).pptxpythoncommentsandvariables-231016105804-9a780b91 (1).pptx
pythoncommentsandvariables-231016105804-9a780b91 (1).pptxMalligaarjunanN
 

Más de MalligaarjunanN (20)

bro_nodejs-1 front end development .pdf
bro_nodejs-1 front end development  .pdfbro_nodejs-1 front end development  .pdf
bro_nodejs-1 front end development .pdf
 
Microprocessor and microcontroller record.pdf
Microprocessor and microcontroller record.pdfMicroprocessor and microcontroller record.pdf
Microprocessor and microcontroller record.pdf
 
8087 MICROPROCESSOR and diagram with definition.pdf
8087 MICROPROCESSOR and diagram with definition.pdf8087 MICROPROCESSOR and diagram with definition.pdf
8087 MICROPROCESSOR and diagram with definition.pdf
 
8089 microprocessor with diagram and analytical
8089 microprocessor with diagram and analytical8089 microprocessor with diagram and analytical
8089 microprocessor with diagram and analytical
 
English article power point presentation eng.pptx
English article power point presentation eng.pptxEnglish article power point presentation eng.pptx
English article power point presentation eng.pptx
 
Digital principle and computer design Presentation (1).pptx
Digital principle and computer design Presentation (1).pptxDigital principle and computer design Presentation (1).pptx
Digital principle and computer design Presentation (1).pptx
 
Technical English grammar and tenses.pptx
Technical English grammar and tenses.pptxTechnical English grammar and tenses.pptx
Technical English grammar and tenses.pptx
 
Polymorphism topic power point presentation li.pptx
Polymorphism topic power point presentation li.pptxPolymorphism topic power point presentation li.pptx
Polymorphism topic power point presentation li.pptx
 
Chemistry iconic bond topic chem ppt.pptx
Chemistry iconic bond topic chem ppt.pptxChemistry iconic bond topic chem ppt.pptx
Chemistry iconic bond topic chem ppt.pptx
 
C programming DOC-20230723-WA0001..pptx
C programming  DOC-20230723-WA0001..pptxC programming  DOC-20230723-WA0001..pptx
C programming DOC-20230723-WA0001..pptx
 
Chemistry fluorescent topic chemistry.pptx
Chemistry fluorescent topic  chemistry.pptxChemistry fluorescent topic  chemistry.pptx
Chemistry fluorescent topic chemistry.pptx
 
C programming power point presentation c ppt.pptx
C programming power point presentation c ppt.pptxC programming power point presentation c ppt.pptx
C programming power point presentation c ppt.pptx
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
 
Python programming file handling mhhk.pptx
Python programming file handling mhhk.pptxPython programming file handling mhhk.pptx
Python programming file handling mhhk.pptx
 
Computer organisation and architecture updated unit 2 COA ppt.pptx
Computer organisation and architecture updated unit 2 COA ppt.pptxComputer organisation and architecture updated unit 2 COA ppt.pptx
Computer organisation and architecture updated unit 2 COA ppt.pptx
 
Data structures trees and graphs - Heap Tree.pptx
Data structures trees and graphs - Heap Tree.pptxData structures trees and graphs - Heap Tree.pptx
Data structures trees and graphs - Heap Tree.pptx
 
Data structures trees and graphs - AVL tree.pptx
Data structures trees and graphs - AVL  tree.pptxData structures trees and graphs - AVL  tree.pptx
Data structures trees and graphs - AVL tree.pptx
 
Data structures trees - B Tree & B+Tree.pptx
Data structures trees - B Tree & B+Tree.pptxData structures trees - B Tree & B+Tree.pptx
Data structures trees - B Tree & B+Tree.pptx
 
Computer organisation and architecture .
Computer organisation and architecture .Computer organisation and architecture .
Computer organisation and architecture .
 
pythoncommentsandvariables-231016105804-9a780b91 (1).pptx
pythoncommentsandvariables-231016105804-9a780b91 (1).pptxpythoncommentsandvariables-231016105804-9a780b91 (1).pptx
pythoncommentsandvariables-231016105804-9a780b91 (1).pptx
 

Último

Intelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsIntelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsSheetal Jain
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfragupathi90
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfJNTUA
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfEr.Sonali Nasikkar
 
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...jiyav969
 
Introduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of ArduinoIntroduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of ArduinoAbhimanyu Sangale
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)NareenAsad
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxRashidFaridChishti
 
Quiz application system project report..pdf
Quiz application system project report..pdfQuiz application system project report..pdf
Quiz application system project report..pdfKamal Acharya
 
Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsKineticEngineeringCo
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashidFaiyazSheikh
 
Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdfKamal Acharya
 
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...Nitin Sonavane
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...archanaece3
 
Lesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsxLesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsxmichaelprrior
 
Microkernel in Operating System | Operating System
Microkernel in Operating System | Operating SystemMicrokernel in Operating System | Operating System
Microkernel in Operating System | Operating SystemSampad Kar
 
Theory for How to calculation capacitor bank
Theory for How to calculation capacitor bankTheory for How to calculation capacitor bank
Theory for How to calculation capacitor banktawat puangthong
 
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Lovely Professional University
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfMadan Karki
 
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...ShivamTiwari995432
 

Último (20)

Intelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsIntelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent Acts
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
Vip ℂall Girls Karkardooma Phone No 9999965857 High Profile ℂall Girl Delhi N...
 
Introduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of ArduinoIntroduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of Arduino
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Quiz application system project report..pdf
Quiz application system project report..pdfQuiz application system project report..pdf
Quiz application system project report..pdf
 
Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and Applications
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Online crime reporting system project.pdf
Online crime reporting system project.pdfOnline crime reporting system project.pdf
Online crime reporting system project.pdf
 
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Lesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsxLesson no16 application of Induction Generator in Wind.ppsx
Lesson no16 application of Induction Generator in Wind.ppsx
 
Microkernel in Operating System | Operating System
Microkernel in Operating System | Operating SystemMicrokernel in Operating System | Operating System
Microkernel in Operating System | Operating System
 
Theory for How to calculation capacitor bank
Theory for How to calculation capacitor bankTheory for How to calculation capacitor bank
Theory for How to calculation capacitor bank
 
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
Fabrication Of Automatic Star Delta Starter Using Relay And GSM Module By Utk...
 

Python programming variables and comment

  • 1. K.S.R COLLEGE OF ENGINEERING TIRUCHENGODE-637 215.(AUTONOMOUS) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING PYTHON PROGRAMMING[20CS311] FUNCTIONS PRESENTED BY S.SOUNDARYA, 73152213091, II YEAR/CSE/B.
  • 2. Python - Functions • A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. • As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 3. Defining a Function Here are simple rules to define a function in Python: • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. • The code block within every function starts with a colon (:) and is indented. • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. • Syntax: • def functionname( parameters ): • "function_docstring" function_suite return [expression]
  • 4. def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. • Example: def printme( str ): "This prints a passed string function" print str return Syntax
  • 5. Calling a Function • Following is the example to call printme() function: def printme( str ): "This is a print function“ print str; return; printme("I'm first call to user defined function!"); printme("Again second call to the same function"); • This would produce following result: I'm first call to user defined function! Again second call to the same function
  • 6. Pass by reference vs value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example: def changeme( mylist ): "This changes a passed list“ mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 7. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 8. Function Arguments: A function by using the following types of formal arguments:: – Required arguments – Keyword arguments – Default arguments – Variable-length arguments Required arguments: • Required arguments are the arguments passed to a function in correct positional order. def printme( str ): "This prints a passed string" print str; return; printme(); • This would produce following result: Traceback (most recent call last): File "test.py", line 11, in <module> printme(); TypeError: printme() takes exactly 1 argument (0 given)
  • 9. Keyword arguments: • Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. def printme( str ): "This prints a passed string" print str; return; printme( str = "My string"); • This would produce following result: My string
  • 10. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); • This would produce following result: Name: miki Age 50
  • 11. Default arguments: • A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. • Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); printinfo( name="miki" ); • This would produce following result: Name: miki Age 50 Name: miki Age 35
  • 12. Variable-length arguments: • You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. • The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression]
  • 13. • An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print "Output is: " print arg1 for var in vartuple: print var return; printinfo( 10 ); printinfo( 70, 60, 50 ); • This would produce following result: Output is: 10 Output is: 70 60 50
  • 14. The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. • An anonymous function cannot be a direct call to print because lambda requires an expression. • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. • Syntax: lambda [arg1 [,arg2,.....argn]]:expression
  • 15. Example: • Following is the example to show how lembda form of function works: sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  • 16. Scope of Variables: • All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. • The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables • Global vs. Local variables: • Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. • This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 17. • Example: total = 0; # This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total • This would produce following result: Inside the function local total : 30 Outside the function global total : 0