What is a Function?
- A function is a chunk of code that can be called by name to perform a task. Functions often require arguments, that is, specific data values, to perform their tasks. Arguments are also known as parameters.
- When a function completes its task (which is usually some kind of computation), the function may send a result back to the part of the program that called that function in the first place. The process of sending a result back to another part of a program is known as returning a value.
- For example, the argument in the function call round(6.5) is the value 6.5, and the value returned is 7.
- As another example, when an argument is an expression, it is first evaluated, and then its value is passed to the function for further processing.
- The function call abs(4-5) first evaluates the expression (4-5) and then passes the result , -1 to abs. Finally, abs returns 1.
python
1absoluteValueExample = abs(4-5)
2print(absoluteValueExample)Output:
11What is a Module?
- Functions and other resources are coded in components called modules. Some functions like abs are always available, however others must be explicitly imported from the modules where they are defined.
- An import statement tells Python to make the code in a module available in the currently running program file. Knowing how to import functions also allows you to use libraries of functions that other programmers have written and reuse functions in different programs.
Example:
- The math module includes several functions that perform basic mathematical operations. Specifically, it includes the value of pi (π).
- To use a resource from a module, you write the name of the module as a qualifier, followed by a dot (.) and the name of the resource.
- To use the value of pi from the math module, you would write the following code: math.pi
Putting It All Together with Floats:
-
Given the radius, compute the diameter, circumference, and surface area of a sphere.
-
Helpful facts:
- Diameter = 2 * radius
- Circumference = diameter * PI
- Surface area = 4 * PI * radius * radius
python
1import math
2
3#2. Get Values for Variables
4radius = float(input("Enter the sphere's radius: "))
5
6#3. Do Calculations
7diameter = 2 * radius
8circumference = diameter * math.pi
9surfaceArea = 4 * math.pi * radius * radius
10
11#4 Display results
12print("Diameter :", diameter)
13print("Circumference:", circumference)
14print("Surface area :", surfaceArea)- Using the input value of 2.5 would produce the following Output:
1Diameter : 5.0
2Circumference: 15.707963267948966
3Surface area : 78.53981633974483