SlideShare a Scribd company logo
1 of 31
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 4
Fundamentals of Programming
Functions
A function is a named sequence of statements that performs a
computation
When you define a function, you specify the name and the
sequence of statements
Later, you can “call” the function by name
>>> type(32)
Built-in functions
Python provides a number of important built-in functions that we
can use without needing to provide the function definition
The creators of Python wrote a set of functions to solve common
problems and included them in Python for us to use
>>> max(10, 100)
100
>>> min(10,100)
>>> len(‘BS GIS')
6
Type conversion functions
Python also provides built-in functions that convert values from one type to
another
The int function takes any value and converts it to an integer, if it can, or
complains otherwise
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
Type conversion functions
int can convert floating-point values to integers, but it doesn’t
round off; it chops off the fraction part
>>> int(3.99999)
3
>>> int(-2.3)
-2
Type conversion functions
float converts integers and strings to floating-point numbers
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Type conversion functions
Finally, str converts its argument to a string
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
Math functions
Python has a math module that provides most of the familiar
mathematical functions
>>> import math
This statement creates a module object named math
>>> print(math)
<module 'math' (built-in)>
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
Random Numbers
The random module provides functions that generate
pseudorandom numbers
The function random returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0)
import random
x = random.random()
print(x)
The random function is only one of many functions that handle
random numbers
The function randint takes the parameters low and high, and returns
an integer between low and high (including both)
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
To choose an element from a sequence at random, you can use
choice
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
Adding new Functions
A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
Once we define a function, we can reuse the function over and
over throughout our program
def print_words():
print(“Inside a function.")
def is a keyword that indicates that this is a function definition
rules for function names are the same as for variable names:
letters, numbers and some punctuation marks are legal, but the
first character can’t be a number
You can’t use a keyword as the name of a function, and you
should avoid having a variable and a function with the same
name
def print_words():
print(“Inside a function.")
The empty parentheses after the name indicate that this function doesn’t take any
arguments
The first line of the function definition is called the header
The rest is called the body
The header has to end with a colon and the body has to be indented
By convention, the indentation is always four spaces
Functions in Interactive Mode
If you type a function definition in interactive mode, the interpreter
prints ellipses (. . .)
to let you know that the definition isn’t complete
>>> def print_words():
... print("Inside a function.")
>>> print(print_words)
>>> print(type(print_words))
Calling a Function
>>> print_words()
Calling a function from another function
def repeat_words():
print_words()
print_words()
>>> repeat_words():
Parameters and Arguments
Some of the built-in functions we have seen require arguments.
For example, when you call math.sin you pass a number as an
argument.
Some functions take more than one argument: math.pow takes
two, the base and the exponent
Inside the function, the arguments are assigned to variables
called parameters
Parameters and Arguments
def print_twice(name):
print(name)
print(name)
This function assigns the argument to a parameter named name.
When the function is called, it prints the value of the parameter
(whatever it is) twice
>>> print_twice('Adnan')
Adnan Adnan
>>> print_twice(30)
30 30
>>> import math
>>> print_twice(math.pi)
>>> print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
>>> print_twice(math.cos(math.pi))
You can also use a variable as an argument:
>>> department = ‘Computer Science.'
>>> print_twice(department)
Computer Science.
Computer Science.
Fruitful functions and void functions
Functions that perform an action but don’t return a value. They
are called void functions
>>> math.sqrt(5)
This script computes the square root of 5, but since it doesn’t
store the result in a variable or display the result, it is not very
useful.
Void functions might display something on the screen or have
some other effect, but they don’t have a return value. If you try to
assign the result to a variable, you get a special value called
None
But in a script, if you call a fruitful function and do not store the
result of the function in a variable, the return value vanish
The value None is not the same as the string “None”. It is a
special value that has its own type:
>>> print(type(None))
Return Value
To return a result from a function, we use the return statement in our
function. For example, we could make a very simple function called
addtwo that adds two numbers together and returns a result
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
Why functions?
• Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read, understand,
and debug.
• Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have to make it in one
place.
• Dividing a long program into functions allows you to debug the parts
one at a time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.

More Related Content

What's hot (20)

Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
C function
C functionC function
C function
 
Ch7 C++
Ch7 C++Ch7 C++
Ch7 C++
 
Functions
FunctionsFunctions
Functions
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Functions
FunctionsFunctions
Functions
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Functions in C
Functions in CFunctions in C
Functions in C
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 

Similar to Python Lecture 4

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
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.pptjaba kumar
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxSheetalMavi2
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdfpaijitk
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfzafar578075
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 

Similar to Python Lecture 4 (20)

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
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
FUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptxFUNCTIONINPYTHON.pptx
FUNCTIONINPYTHON.pptx
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Function
FunctionFunction
Function
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 

More from Inzamam Baig

More from Inzamam Baig (13)

Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 

Recently uploaded (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 

Python Lecture 4

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 4 Fundamentals of Programming
  • 2. Functions A function is a named sequence of statements that performs a computation When you define a function, you specify the name and the sequence of statements Later, you can “call” the function by name >>> type(32)
  • 3. Built-in functions Python provides a number of important built-in functions that we can use without needing to provide the function definition The creators of Python wrote a set of functions to solve common problems and included them in Python for us to use >>> max(10, 100) 100 >>> min(10,100)
  • 5. Type conversion functions Python also provides built-in functions that convert values from one type to another The int function takes any value and converts it to an integer, if it can, or complains otherwise >>> int('32') 32 >>> int('Hello') ValueError: invalid literal for int() with base 10: 'Hello'
  • 6. Type conversion functions int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part >>> int(3.99999) 3 >>> int(-2.3) -2
  • 7. Type conversion functions float converts integers and strings to floating-point numbers >>> float(32) 32.0 >>> float('3.14159') 3.14159
  • 8. Type conversion functions Finally, str converts its argument to a string >>> str(32) '32' >>> str(3.14159) '3.14159'
  • 9. Math functions Python has a math module that provides most of the familiar mathematical functions >>> import math This statement creates a module object named math >>> print(math) <module 'math' (built-in)>
  • 10. >>> ratio = signal_power / noise_power >>> decibels = 10 * math.log10(ratio) >>> radians = 0.7 >>> height = math.sin(radians)
  • 11. >>> degrees = 45 >>> radians = degrees / 360.0 * 2 * math.pi
  • 12. Random Numbers The random module provides functions that generate pseudorandom numbers The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0) import random x = random.random() print(x)
  • 13. The random function is only one of many functions that handle random numbers The function randint takes the parameters low and high, and returns an integer between low and high (including both) >>> random.randint(5, 10) 5 >>> random.randint(5, 10) 9
  • 14. To choose an element from a sequence at random, you can use choice >>> t = [1, 2, 3] >>> random.choice(t) 2 >>> random.choice(t) 3
  • 15. Adding new Functions A function definition specifies the name of a new function and the sequence of statements that execute when the function is called. Once we define a function, we can reuse the function over and over throughout our program def print_words(): print(“Inside a function.")
  • 16. def is a keyword that indicates that this is a function definition rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name
  • 17. def print_words(): print(“Inside a function.") The empty parentheses after the name indicate that this function doesn’t take any arguments The first line of the function definition is called the header The rest is called the body The header has to end with a colon and the body has to be indented By convention, the indentation is always four spaces
  • 18. Functions in Interactive Mode If you type a function definition in interactive mode, the interpreter prints ellipses (. . .) to let you know that the definition isn’t complete >>> def print_words(): ... print("Inside a function.")
  • 20. Calling a Function >>> print_words()
  • 21. Calling a function from another function def repeat_words(): print_words() print_words() >>> repeat_words():
  • 22. Parameters and Arguments Some of the built-in functions we have seen require arguments. For example, when you call math.sin you pass a number as an argument. Some functions take more than one argument: math.pow takes two, the base and the exponent Inside the function, the arguments are assigned to variables called parameters
  • 23. Parameters and Arguments def print_twice(name): print(name) print(name) This function assigns the argument to a parameter named name. When the function is called, it prints the value of the parameter (whatever it is) twice
  • 24. >>> print_twice('Adnan') Adnan Adnan >>> print_twice(30) 30 30 >>> import math >>> print_twice(math.pi)
  • 25. >>> print_twice('Spam '*4) Spam Spam Spam Spam Spam Spam Spam Spam >>> print_twice(math.cos(math.pi))
  • 26. You can also use a variable as an argument: >>> department = ‘Computer Science.' >>> print_twice(department) Computer Science. Computer Science.
  • 27. Fruitful functions and void functions Functions that perform an action but don’t return a value. They are called void functions
  • 28. >>> math.sqrt(5) This script computes the square root of 5, but since it doesn’t store the result in a variable or display the result, it is not very useful. Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None
  • 29. But in a script, if you call a fruitful function and do not store the result of the function in a variable, the return value vanish The value None is not the same as the string “None”. It is a special value that has its own type: >>> print(type(None))
  • 30. Return Value To return a result from a function, we use the return statement in our function. For example, we could make a very simple function called addtwo that adds two numbers together and returns a result def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print(x)
  • 31. Why functions? • Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read, understand, and debug. • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole. • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.

Editor's Notes

  1. The name of the function is type. The expression in parentheses is called the argument of the function. The argument is a value or variable that we are passing into the function as input to the function The result is called the return value
  2. The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation
  3. The decibel (abbreviated dB) is the unit used to measure the intensity of a sound. It is also widely used in electronics, signals and communication. The dB is a logarithmic way of describing a ratio. The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e. The second example finds the sine of radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians
  4. To convert from degrees to radians, divide by 360 and multiply by 2π
  5. To end the function, you have to enter an empty line
  6. The value of print_words is a function object, which has type “function”
  7. The argument is evaluated before the function is called, so in the examples the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once