Section 4.1 Introduction to Functions
In Python, a function is a chunk of code that performs a specific operation that is a meaningful and self-contained part of a larger problem, such as calculating a student’s GPA in a learning system or responding to the jump action in a video game. Once a function has been defined and you are satisfied that it does what it is supposed to do, it is useful to start thinking about it in terms of the larger operation that it performs rather than the specific lines of code that make it work.
In computer programming, this breaking down of a task or problem into smaller, solveable, sub-functions, is called decomposition and the idea of hiding the complexity of the sub-steps of the algorithm in a function is called abstraction. Learning how to do both of these problem solving techniques is crucial to the successful implementation of any program of more than 50 or so lines (and plenty of smaller ones too). For example, the programmer who coded the Instagram landing page decomposed it into functions that:
- display the header bar
- display your friends’ posts
- display your friends’ stories
- display the ad at the bottom of the screen recommending you use the app
And each of those is made up of functions as well. For example, the function that displays your friends’ posts is a
for
loop that calls a ’sub’-function to display a single post, which in turn calls ’sub-sub’-functions to:- display the photo and name of the person posting the story
- display the photo itself
- display other users’ “likes” to the story
- display the comments on the story
- etc.
In this chapter you will learn about named functions, i.e. functions that are referred to by a name when you want to execute them.
Subsection 4.1.1 Topics
- The purpose of functions as a means of abstraction
-
The syntax and parts of functions
- Function headers
- Parameters and arguments
- Body and return statement
- Local and global scope and the flow of execution
Subsection 4.1.2 Learning Objectives
At the end of this chapter, you should be able to:
- identify formal parameters and parameter values in a code sample
- predict the return value of a function given sample parameter values (aka arguments)
- define functions with appropriate names for formal parameter
- avoid the use of global variables in function definitions by creating formal parameters for all values that are needed
You have attempted of activities on this page.