Table of Contents
4.1 Functions
Definition and Syntax: How to Define and Call Functions
A function is a block of organized, reusable code that performs a single, related action. Functions provide better modularity and a high degree of code reusability. To use functions, you need to define them and then call them when required.
Defining a Function:
- In Python:
def function_name(parameters): """Docstring: Describe the function.""" # function body return result
- In JavaScript:
function functionName(parameters) { // function body return result; }
- In Java:
java public returnType functionName(parameters) { // function body return result; }
Calling a Function:
Once defined, functions are called by their name followed by parentheses enclosing any required parameters.
- Python:
function_name(arguments)
- JavaScript:
functionName(arguments)
- Java:
functionName(arguments)
Example:
- Python:
def greet(name): return f"Hello, {name}!" print(greet("Alice"))
- JavaScript:
function greet(name) { return `Hello, ${name}!`; } console.log(greet("Alice"));
- Java:
public class Main { public static void main(String[] args) { System.out.println(greet("Alice")); }public static String greet(String name) { return "Hello, " + name + "!"; }}
Parameters and Arguments: Passing Data to Functions and Receiving Output
Parameters are the variables listed inside the parentheses in the function definition. Arguments are the values passed to the function when it is called.
Example with Parameters and Arguments:
- Python:
def add(a, b): return a + b print(add(2, 3))
- JavaScript:
function add(a, b) { return a + b; } console.log(add(2, 3));
- Java:
public class Main { public static void main(String[] args) { System.out.println(add(2, 3)); }public static int add(int a, int b) { return a + b; }}
Return Values: Returning Results from Functions
A function can send a value back to the part of the program that called it. The return
statement is used for this purpose.
Example with Return Values:
- Python:
def square(x): return x * x result = square(4) print(result)
- JavaScript:
function square(x) { return x * x; } let result = square(4); console.log(result);
- Java:
public class Main { public static void main(String[] args) { int result = square(4); System.out.println(result); }public static int square(int x) { return x * x; }}
Scope and Lifetime: Understanding Local and Global Variables
Scope refers to the visibility of variables. Variables defined inside a function are local to that function and cannot be accessed outside it. Variables defined outside any function are global and can be accessed anywhere in the program.
Lifetime of a variable is the period during which the variable exists in memory. Local variables have a lifetime limited to the execution of the function.
Example of Scope and Lifetime:
- Python:
global_var = "I am global" def func(): local_var = "I am local" print(global_var) # Accessible print(local_var) # Accessible func() print(local_var) # Error: local_var is not defined
- JavaScript:
let globalVar = "I am global"; function func() { let localVar = "I am local"; console.log(globalVar); // Accessible console.log(localVar); // Accessible } func(); console.log(localVar); // Error: localVar is not defined
- Java:
public class Main { static String globalVar = "I am global";public static void main(String[] args) { func(); System.out.println(localVar); // Error: localVar is not defined } public static void func() { String localVar = "I am local"; System.out.println(globalVar); // Accessible System.out.println(localVar); // Accessible }}
4.2 Modules
Modules are files containing Python code that can define functions, classes, and variables. They also include runnable code.
Importing Modules: How to Use Pre-built Modules or Libraries
You can import an entire module or specific parts from a module.
Importing an Entire Module:
- Python:
python import math print(math.sqrt(16))
- JavaScript (Node.js):
javascript const math = require('mathjs'); console.log(math.sqrt(16));
- Java:
import java.util.*; public class Main { public static void main(String[] args) { System.out.println(Math.sqrt(16)); } }
Importing Specific Parts:
- Python:
python from math import sqrt print(sqrt(16))
- JavaScript (ES6):
javascript import { sqrt } from 'mathjs'; console.log(sqrt(16));
Creating Modules: Writing Your Own Modules and Organizing Code
You can create your own modules by saving functions and classes in a file with a .py
extension (for Python) and importing them as needed.
Example of Creating a Module:
- Python:
- Create a module file
mymodule.py
:def greet(name): return f"Hello, {name}!"
- Import and use the module:
python import mymodule print(mymodule.greet("Alice"))
- Create a module file
- JavaScript:
- Create a module file
mymodule.js
:function greet(name) { return `Hello, ${name}!`; } module.exports = greet;
- Import and use the module:
javascript const greet = require('./mymodule'); console.log(greet("Alice"));
- Create a module file
Package Management: Using Package Managers to Handle Dependencies
Package managers help in managing dependencies and libraries required for your project. Examples include pip
for Python and npm
for JavaScript.
Using pip
for Python:
- Install a package:
bash pip install requests
- Use the installed package:
python import requests response = requests.get('https://api.github.com') print(response.status_code)
Using npm
for JavaScript:
- Install a package:
bash npm install lodash
- Use the installed package:
javascript const _ = require('lodash'); console.log(_.random(1, 100));
4.3 Best Practices
Code Reusability: Writing Reusable and Maintainable Code
Reusable code is easier to maintain and reduces redundancy. Writing modular code with functions and modules enhances reusability.
Tips for Code Reusability:
- Write functions that perform single tasks.
- Use meaningful function and variable names.
- Avoid hardcoding values; use parameters instead.
- Keep functions short and focused.
Documentation: Commenting and Documenting Functions and Modules for Clarity
Well-documented code is easier to understand and maintain. Use comments and docstrings to explain the purpose of code segments and how to use them.
Example of Documentation:
- Python:
def add(a, b): """ Adds two numbers.Parameters: a (int): The first number. b (int): The second number. Returns: int: The sum of a and b. """ return a + b</code></pre></li>JavaScript: /** * Adds two numbers. * @param {number} a - The first number. * @param {number} b - The second number. * @returns {number} The sum of a and b. */ function add(a, b) { return a + b; } Java:
```java
/** Adds two numbers. @param a The first number. @param b The second number. @return The sum of a and b.
*/
public static int add(int a, int b) {
return a + b;
}
```