Applied Programming/Functions
This lesson introduces functions and related code documentation.
Objectives and Skills
editObjectives and skills for this lesson include:[1]
- Document code segments using comments and documentation strings
- Use indentation, white space, comments, and documentation strings; generate documentation by using pydoc
- Construct and analyze code segments that include function definitions
- Call signatures; default values; return; def; pass
Readings
editMultimedia
edit- YouTube: Introduction to Structured Programming
- YouTube: The Disadvantages of Spaghetti Code
- YouTube: The Advantages of Modularization
- YouTube: Modularity with Functions
- YouTube: Programming Basics - Statements & Functions
- YouTube: Programming Tutorial - Function Parameters
- YouTube: How to Use Functions in Python
- YouTube: Python Programming - Variable Scope
- YouTube: Naming Convention with Programming Languages
- YouTube: Python Programming: Docstrings
Examples
editActivities
editProgramming Languages
edit- Review Wikipedia: Coding conventions, Research style guides or coding standards for your selected programming language, looking specifically for function documentation. If applicable, discuss coding conventions with your classmates and agree on a standard to follow for this course.
Coding
editComplete one or more of the following coding activities in your selected programming language. Use self-documenting variable and constant names that follow the naming conventions for your selected programming language. Include comments at the top of the source code that describe the program and are consistent with the program or module documentation conventions for your selected programming language.
- Extend the BMI program from the previous lesson. Use separate functions for input, each type of conversion, BMI calculation, and output. Avoid global variables by passing parameters and returning results. Define constants for height and weight conversions and use the self-documenting function, variable, and constant names that follow the naming conventions for your selected programming language. Include comments at the top of the source code and comments for each function that is consistent with the documentation conventions for your selected programming language.
Lesson Summary
edit- Modular programming is a software design technique that emphasizes separating the functionality of a program into reusable, independent modules.[2]
- This concept is related to structured and object-oriented programming; all have the same end goal of deconstructing a comprehensive program into smaller pieces.[2]
- Structured programming enforces consistent structures (sequential, conditional, and repetition), requiring them to have a single entry and a single exit.[3]
- Object-oriented programming entails the use of classes, a template for object instantiation. An object is a user-created data type that carries its own attributes (fields) and behaviors (methods).[4]
- A subroutine, function, or method is a sequence of instructions designed to complete a given task.[5]
- Subroutines aid in the decomposition of complicated, multi-step tasks. They also facilitate the related concepts of re-usability and maintainability.[5]
- A subroutine may receive arguments upon invocation and return values upon termination.[5]
- A subroutine may call other subroutines, or itself recursively.[5]
- A subroutine has a side-effect when it modifies external data beyond its scope. For example, a subroutine may alter its supplied argument, changing its value in the calling environment.[5]
- A variable's scope is the portion of the source code in which the binding of an identifier (user-defined name of a program element[6]) gets associated with the underlying entity.[7]
- The scope of a name binding is the region where a given identifier can be recognized or declared; it could apply to variables, functions, and user-created structures.[7]
- A variable's scope can vary from a single expression to an entire program, with many gradations and flavors in-between.[7]
- The 6 levels of scope in order from the most to least inclusive: [7]
- global scope
- module scope
- file scope
- subroutine/function scope
- block scope
- expression scope
- A declaration is global in scope if the name has effect throughout an entire program. The use of non-constant variables with global recognition is considered a harmful practice, due to the increased likelihood of colliding identifiers and unintentional masking.[7]
- When the scope is limited to a module, the identifier can only reference within the visibility of that module (which could potentially span multiple files of source code).[7]
- This idea of module scope can also be extended to class hierarchies where certain attributes or behaviors may be specified as private, only to be accessed from within the class itself.[7]
- When variables are declared outside a subroutine, they usually are declared at the file-level; their scope ranges from the point of declaration until the end of the file.[7]
- Function scope variables are local to a specific function. They go 'out of scope' when the function returns.[7]
- In most cases, the lifetime of these variables spans the duration of the function call; the entity gets created when the variable is declared, only to be permanently destroyed when the function returns.[7]
- However, some languages also have static local variables, where the lifetime of the variable is the entire lifetime of the program. The variable is only known in the context of its resident function.[7]
- A variable known only to a block is usually restricted to a construct such as a conditional statement or a loop.[7]
- Some functional languages offer a let-expression mechanism that confines a declaration's scope to a single expression.[7]
- This could be useful if you only need a temporary, intermediate value for a computation.[7]
- There are two strategies employed to resolve names: lexical scoping and dynamic scoping.[7]
- With lexical scoping, the entity referenced is known prior to run-time, determined by the lexical structure and content of the program's source code.[7]
- With dynamic scoping, the entity referenced is deduced at run-time, depending on the variable's relative position in the call stack. This method is far less popular among implemented programming languages.[7]
- Parameters are variables that receive data inside a subroutine or function.[8]
- The subroutine or function head defines a parameter list, the standard by which future calls are to be made.[8]
- Subroutines may use a ‘call by value’ strategy where the arguments passed set-up local variables inside the function. These variables don't have access to data in the calling environment, so critical processes remain safe from accidental error.[8]
- The arguments passed to a subroutine are evaluated and transferred onto the corresponding parameter.[8]
- Subroutines may also use a ‘call by reference’ strategy where the original argument itself gets referenced—not just a copy of its value; by referring to the actual memory location of the variable, it can be directly affected, producing an observable side-effect.[8]
- There is a slight distinction to be made between an "argument" and a "parameter." The argument is the value or reference supplied when calling the function; the parameter is the variable inside the function that receives the argument. For variables that are ‘passed by reference,’ both aliases would refer to the same object.[8]
- Function parameters can have default parameter values written in parameter = expression form. When calling a function with default parameters, the corresponding argument can be omitted in a call, and the default value will be used instead.[9]
- If one function parameter has a default value, then all following parameters must have default values.[10]
- Following a naming convention is to properly name a variable, function, and other identifiers according to mutual standards.[11]
- Having a consistent naming convention allows other developers to focus on issues of logic rather than syntactical concerns.[11]
- Identifiers should be relatively brief, yet long enough to adequately describe the object being identified.[11]
- A popular naming convention in some programming languages is to use lower camel case, where the first word is lower-cased and subsequent words are capitalized (e.g., getHeight(), printChart(), and so on).[11]
- Constants are typically named with all upper-case letters and if applicable, underscores separating the words (e.g., WEIGHT_CONVERSION, HEIGHT_CONVERSION, and so on).[11]
- Different programming languages have different naming conventions; following your language's convention is not essential to writing code, but strongly advised. When peers review your code, they will be well-adjusted to your style of nomenclature.[11]
Key Terms
edit- argument
- Data that gets passed to a function upon invocation. Depending on the evaluation strategy, the argument supplied may consist of variables/constants, literal values, other function calls, or an expression involving operators and the aforementioned objects.[8]
- call-by-reference
- Arguments are passed to the subroutine by direct reference, typically using the argument's address.[5]
- call-by-value
- Arguments are evaluated and a copy of the value is passed to the subroutine.[5]
- docstrings
- A string literal which appears as the first expression in a class, function or module. While ignored when the suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object. [12]
- module
- A collection of programming objects (functions, variables, and other mechanisms) that get packaged together as reusable, adaptable code.[2]
- parameter
- Placeholder variables that receive the supplied arguments so they can be accessed inside the function.[8]
- return value
- A function may optionally return a value or another object to its calling environment upon termination. This return value may be captured or simply ignored.[13]
- scope
- The block or section of code in which the variable exists and can be referenced. This is known as its visibility.[7]
- subroutine
- A sequence of program instructions that perform a specific task, packaged as a unit.[5]
See Also
editReferences
edit- ↑ Microsoft: Exam 98-381 Introduction to Programming Using Python
- ↑ 2.0 2.1 2.2 Wikipedia: Modular programming
- ↑ Wikipedia: Structured programming
- ↑ Wikipedia: Object-oriented programming
- ↑ 5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 Wikipedia: Subroutine
- ↑ https://www.techopedia.com/definition/1810/identifier-c
- ↑ 7.00 7.01 7.02 7.03 7.04 7.05 7.06 7.07 7.08 7.09 7.10 7.11 7.12 7.13 7.14 7.15 7.16 7.17 Wikipedia: Scope (computer science)
- ↑ 8.0 8.1 8.2 8.3 8.4 8.5 8.6 8.7 Wikipedia: Parameter (computer programming)
- ↑ Python Reference Manualː Function definitions
- ↑ Python Reference Manualː Function definitions
- ↑ 11.0 11.1 11.2 11.3 11.4 11.5 Wikipedia: Naming convention (programming)
- ↑ Python 3.8.1 Glossary
- ↑ Wikipedia: Return statement