SlideShare a Scribd company logo
1 of 21
Functions
Prepared by
Md. Shafiuzzaman
Functions
• a mini-program within a program
• Built-in: print(), input(), len()
• User-defined
Example
Purpose of functions
• group code that gets executed multiple times
• without a function defined, you would have to copy and paste code
each time
• avoid duplicating code, because if you ever decide to update the
code—if, for example, you find a bug you need to fix—you’ll have to
remember to change the code everywhere you copied it
Key Concepts
• def Statements
• arguments
• parameters
• return
None Value
• Other programming languages might call this value null, nil, or
undefined.
Keyword Arguments
Keyword Arguments
Local and Global Scope
• code in the global scope cannot use any local variables
• a local scope can access global variables
• code in a function’s local scope cannot use variables in any other local
scope
Local and Global Variables with the Same
Name
The global Statement
The global Statement
If you ever want to modify the value stored in a global variable from
in a function,
you must use a global statement on that variable
Exception Handling
Exception Handling
Exception Handling
Practice Projects: The Collatz Sequence
• Write a function named collatz() that has one parameter named
number. If number is even, then collatz() should print number // 2
and return this value. If number is odd, then collatz() should print and
return 3 * number + 1.
• Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1.
Hints
• Remember to convert the return value from input() to an integer with
the int() function; otherwise, it will be a string value
• An integer number is even if number % 2 == 0, and it’s odd if number
% 2 == 1
Sample Output
Input Validation
• Add try and except statements to the previous project to detect
whether the user types in a noninteger string.
• Normally, the int() function will raise a ValueError error if it is passed
a noninteger string, as in int('puppy').
• In the except clause, print a message to the user saying they must
enter an integer.

More Related Content

What's hot

What's hot (20)

Programming Sessions KU Leuven - Session 02
Programming Sessions KU Leuven - Session 02Programming Sessions KU Leuven - Session 02
Programming Sessions KU Leuven - Session 02
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
ReSharper Presentation for NUGs
ReSharper Presentation for NUGsReSharper Presentation for NUGs
ReSharper Presentation for NUGs
 
Ruby on rails intro
Ruby on rails introRuby on rails intro
Ruby on rails intro
 
c3ee900a-894b-4680-894c-42f77ffd4446-160308162303
c3ee900a-894b-4680-894c-42f77ffd4446-160308162303c3ee900a-894b-4680-894c-42f77ffd4446-160308162303
c3ee900a-894b-4680-894c-42f77ffd4446-160308162303
 
Api testing
Api testingApi testing
Api testing
 
Intro to javascript (6:19)
Intro to javascript (6:19)Intro to javascript (6:19)
Intro to javascript (6:19)
 
Automation Testing and its importance
Automation Testing and its importanceAutomation Testing and its importance
Automation Testing and its importance
 
Managing state in modern React web applications
Managing state in modern React web applicationsManaging state in modern React web applications
Managing state in modern React web applications
 
EK127S15HW2
EK127S15HW2EK127S15HW2
EK127S15HW2
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
 
CSharp 5 Async
CSharp 5 AsyncCSharp 5 Async
CSharp 5 Async
 
Tut1 script
Tut1 scriptTut1 script
Tut1 script
 
Prowess presentation
Prowess presentationProwess presentation
Prowess presentation
 
How to NLProc from .NET
How to NLProc from .NETHow to NLProc from .NET
How to NLProc from .NET
 
Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4
 
Java basics training 1
Java basics training 1Java basics training 1
Java basics training 1
 
RESUME
RESUMERESUME
RESUME
 
Refactoring merged code - ReSharper meets SemanticMerge
Refactoring merged code - ReSharper meets SemanticMergeRefactoring merged code - ReSharper meets SemanticMerge
Refactoring merged code - ReSharper meets SemanticMerge
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
 

Similar to Function in Python

classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptxMohammedAlYemeni1
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringSri Harsha Pamu
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercisesNico Ludwig
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Mohamed El Desouki
 

Similar to Function in Python (20)

Functions
FunctionsFunctions
Functions
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Functions
FunctionsFunctions
Functions
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
C programming
C programmingC programming
C programming
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Pc module1
Pc module1Pc module1
Pc module1
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++
 

More from Md. Shafiuzzaman Hira (20)

Introduction to Web development
Introduction to Web developmentIntroduction to Web development
Introduction to Web development
 
Software measurement and estimation
Software measurement and estimationSoftware measurement and estimation
Software measurement and estimation
 
Why do we test software?
Why do we test software?Why do we test software?
Why do we test software?
 
Software Requirements engineering
Software Requirements engineeringSoftware Requirements engineering
Software Requirements engineering
 
Software architectural patterns
Software architectural patternsSoftware architectural patterns
Software architectural patterns
 
Class based modeling
Class based modelingClass based modeling
Class based modeling
 
Class diagram
Class diagramClass diagram
Class diagram
 
State diagram
State diagramState diagram
State diagram
 
Use case Modeling
Use case ModelingUse case Modeling
Use case Modeling
 
User stories
User storiesUser stories
User stories
 
Dev ops
Dev opsDev ops
Dev ops
 
Agile Methodology
Agile MethodologyAgile Methodology
Agile Methodology
 
Software Process Model
Software Process ModelSoftware Process Model
Software Process Model
 
Introduction to Software Engineering Course
Introduction to Software Engineering CourseIntroduction to Software Engineering Course
Introduction to Software Engineering Course
 
C files
C filesC files
C files
 
C pointers
C pointersC pointers
C pointers
 
C structures
C structuresC structures
C structures
 
Regular expressions using Python
Regular expressions using PythonRegular expressions using Python
Regular expressions using Python
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Lists in Python
Lists in PythonLists in Python
Lists in Python
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

Function in Python

  • 2. Functions • a mini-program within a program • Built-in: print(), input(), len() • User-defined
  • 4. Purpose of functions • group code that gets executed multiple times • without a function defined, you would have to copy and paste code each time • avoid duplicating code, because if you ever decide to update the code—if, for example, you find a bug you need to fix—you’ll have to remember to change the code everywhere you copied it
  • 5. Key Concepts • def Statements • arguments • parameters • return
  • 6.
  • 7. None Value • Other programming languages might call this value null, nil, or undefined.
  • 10. Local and Global Scope • code in the global scope cannot use any local variables • a local scope can access global variables • code in a function’s local scope cannot use variables in any other local scope
  • 11. Local and Global Variables with the Same Name
  • 14. If you ever want to modify the value stored in a global variable from in a function, you must use a global statement on that variable
  • 18. Practice Projects: The Collatz Sequence • Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. • Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
  • 19. Hints • Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value • An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1
  • 21. Input Validation • Add try and except statements to the previous project to detect whether the user types in a noninteger string. • Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy'). • In the except clause, print a message to the user saying they must enter an integer.