Table of contents |
|
Introduction |
|
Functions |
|
User Defined Functions |
|
Scope of a Variable |
|
Python Standard Library |
|
So far, we have written several programs and may have noticed that as problems become more complex, the number of lines in a program increases. This makes the code appear lengthy and harder to manage. Now, consider the following scenario: A company produces tents based on customer specifications. Each tent has a cylindrical base with a conical top.
The company follows these steps to determine the selling price of each tent:
1. Gather customer requirements, including:
a) Height of the tent
b) Radius of the base
c) Slant height of the conical top
2. Compute the total canvas area required.
3. Determine the cost of the canvas used to manufacture the tent.
Calculate the final amount payable by the customer, including an 18% tax.
Program: Program to calculate the payable amount for the tent.
Another approach to solve the above problem is to divide the program into different blocks of code as shown in Figure.
Breaking a computer program into distinct, independent code blocks or smaller sub-problems, each with a unique name and specific functionality, is called modular programming. In this chapter, we will explore the advantages of this approach.
Functions are a key aspect of programming that promote modularity and reusability. A function is essentially a named set of instructions designed to perform a specific task when called upon. Once a function is defined, it can be invoked multiple times from different parts of the program without the need to rewrite the same code. Functions can also be called from within other functions by simply using the function’s name and providing any necessary parameters. There is no limit to the number of functions a programmer can create while coding.
To illustrate the use of functions, let’s consider a program that calculates the payable amount for a tent. The initial version of the program is rewritten using user-defined functions to enhance its organization and readability.
In the revised program, functions are defined to calculate the curved surface area of the cylindrical part of the tent, the curved surface area of the conical part, and the net price after tax. By breaking down the calculations into smaller, manageable functions, the code becomes cleaner and easier to understand.
When comparing the two versions of the program, it is clear that the second version, which utilizes functions, is more structured and readable. Functions not only make the code more organized but also allow for easier maintenance and updates in the future.
Program: Program to calculate the payable amount f or the tent using user defined functions.
Suppose further the company decides to design another type of tent whose base is rectangular, while the upper part remains the same. In such a scenario, some part of the existing code can be reused by calling the function con(l,r). If the company develops other products or provides services, and where 18% tax rate is to be applied, the programmer can use the function post_tax_price(cost)directly.
Thus, following are the advantages of using functions in a program:
Functions are reusable pieces of code that can be called multiple times within a program. Python has a vast standard library with many built-in functions that can be used directly without defining them. However, programmers can also create their own functions tailored to specific tasks or requirements. These are known as user defined functions.
A user defined function is essentially a block of code designed to perform a particular task as per the programmer's needs. By defining functions, programmers can organize their code better, avoid repetition, and make it more manageable.
Introduction to User-Defined Functions
def
keyword, which stands for define.def function_name(parameters):
Example: Adding Two Numbers
Let's look at a simple program that defines a function to add two numbers and display their sum.
Program: Write a user defined function to add 2 numbers and display their sum.
In order to execute the function addnum(), we need to call it. The function can be called in the program by writing function name followed by () as shown in the last line of program.
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11
In the previous example, the numbers were obtained from the user within the function. However, it is also possible for a user-defined function to receive values at the time of being called. An argument is a value passed to the function during the function call, which is received by the corresponding parameter defined in the function header.
Program: Write a program using a user defined function that displays sum of first n natural numbers, where n is passed as an argument.
Since the function is called, the control is transferred to execute the function def sumSquares(n): where parameter n also refers to the value 5 which num is referring to as shown in Figure.
Since both num and n are referring to the same value, they are bound to have the same identity. We can use the id() function to find the identity of the object that the argument and parameter are referring to. Let us understand this with the help of the following example.
In Python, functions can either return a value or not when they are called. The return statement is used to send values back from a function. For instance, in the examples we've seen so far, the functions perform calculations and show results, but they don't return any values. These are called void functions. However, there are times when we need to send values back to the calling function, and that's when we use the return statement.
Program: Write a program using user defined function calcPow() that accepts base and exponent as arguments and returns the value Baseexponent where Base and exponent are integers.
So far we have learnt that a function may or may not have parameter(s) and a function may or may not return any value(s). In Python, as per our requirements, we can have the function in either of the following ways:
The flow of execution refers to the order in which statements in a program are executed. The Python interpreter begins executing instructions from the first statement and proceeds one by one, from top to bottom.
When the interpreter comes across a function definition, the statements inside the function are not executed immediately; they are executed only when the function is called.
Program: Write a program using user defined function that accepts length and breadth of a rectangle and returns the area and perimeter of the rectangle.
A variable defined within a function is not accessible outside of that function. Each variable has a specific level of accessibility, which is referred to as its scope. Variables can possess one of two types of scopes: a global variable, which has global scope, or a local variable, which has local scope.
(A) Global Variable
(B) Local Variable
Program: Program to access any variable outside the function
Note: Modifications made to a global variable are enduring and influence all functions that utilize it. When a variable shares the same name as a global variable within a function, it is treated as local to that function, effectively concealing the global variable. To access the updated value of a global variable outside the function, the keyword global must be used before the variable name within the function.
The Python Standard Library is a vast collection of modules and packages that come pre-installed with Python. It offers a wide range of functionalities, allowing programmers to perform various tasks without having to write code from scratch.
Built-in functions
The built-in function being utilized in the statement fname = input("Enter your name: ") is input(). This function does accept a value or argument, as indicated by the parentheses () which contain the string "Enter your name".
Additionally, the function does return a value. The presence of the assignment operator =
before the function name suggests that the output of the input() function is stored in the variable fname.
Thus, it can be concluded that the input() function both accepts a value and returns a value.
Now, when considering the other built-in functions, int() and print(), we can answer the following questions:
Following is a categorised list of some of the frequently used built-in functions in Python:We have already used some of the built-in functions.
Commonly used built-in functions
(A) Built-in Modules
Python includes a variety of built-in modules that are incredibly useful for programmers. Let's take a closer look at some commonly used modules and their frequently used functions:
Note: Python is case sensitive, so all module names are in lowercase.
1. Module: math
The math module contains various mathematical functions, most of which return a float value. To use this module, you need to import it using the statement import math.
Commonly Used Functions in the Math Module
2. Module: random
The random module is used for generating random numbers. To use this module, you can import it using the statement import random.
Commonly Used Functions in the Random Module
3. Module: statistics
The statistics module provides functions for calculating various statistics of numeric data. To use this module, you can import it using the statement import statistics.
Commonly Used Functions in the Statistics Module
Note:
(B) From Statement
Example 7.5
Example 7.6
Composition in Programming
In addition to the modules provided by the Python standard library, we can create custom modules that include our own functions.
Program: Create a user defined module basic_ math that contains the following user defined functions:
1. To add two numbers and return their sum.
2. To subtract two numbers and return their difference.
3. To multiply two numbers and return their product.
4. To divide two numbers and return their quotient and print “Division by Zero” error if the denominator is zero.
5. Also add a docstring to describe the module. After creating module, import and execute functions.
Output:
33 docs|11 tests
|
1. What are functions in Python and why are they important? | ![]() |
2. How do you define a user-defined function in Python? | ![]() |
3. What is the scope of a variable in Python and why does it matter? | ![]() |
4. Can you explain the difference between local and global variables? | ![]() |
5. What are some common built-in functions in the Python Standard Library? | ![]() |