Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Chapter Notes: Functions

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction

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.
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Another approach to solve the above problem is to divide the program into different blocks of code as shown in Figure.
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

The Advantages of Function

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:

  • Increases readability, particularly for longer code as by using functions, the program is better organised and easy to understand.
  • Reduces code length as same code is not required to be written at multiple places in a program. This also makes debugging easier.
  • Increases reusability, as function can be called from another function or another program. Thus, we can reuse or build upon already defined functions and avoid repetitions of writing the same piece of code.
  • Work can be easily divided among team members and completed in parallel.

User Defined Functions

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.

Creating User-Defined Functions

Introduction to User-Defined Functions

  • A user-defined function in Python is created using the  def  keyword, which stands for define.
  • The basic syntax for defining a function is as follows:

def function_name(parameters):

  • Parameters are optional and enclosed in square brackets [ ]. A function can have parameters or none at all.
  • A function may also return a value, but this is not mandatory.
  • The function header must end with a colon (:).
  • Function names should be unique and follow the same naming rules as identifiers.
  • Statements outside the function's indentation level are not part of the function.

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
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

Arguments and Parameters

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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.

Functions That Return Values in Python

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.

  • The return statement does two main things:
  • It sends control back to the calling function.
  • It returns value(s) or None.

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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: 

  • Function with no argument and no return value 
  • Function with no argument and with return value(s) 
  • Function with argument(s) and no return value

Flow of Execution in Python

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Scope of a Variable

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

  • In Python, a variable that is defined outside any function or block is called a global variable. Global variables can be accessed and modified by any function within the program. Any changes made to a global variable will affect all functions that have access to it.

(B) Local Variable

  • A variable defined inside a function or block is known as a local variable. Local variables can only be accessed within the function or block where they are defined. They exist only for the duration of the function's execution.

Program: Program to access any variable outside   the function

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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. 

Python Standard Library

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.
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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:

  • Does the function int() accept a value or argument? Yes, int() accepts a value that is typically a string or number that it will convert into an integer.
  • Does the function int() return a value? Yes, int() returns the integer representation of the given argument.
  • Does the function print() accept a value or argument? Yes, print() accepts one or more values or arguments that it will display on the screen.
  • Does the function print() return a value? No, print() does not return a value; it simply outputs the specified values to the console.

 Following is a categorised list of some of the frequently used built-in functions in Python:
Functions Chapter Notes | Computer Science for Class 11 - Humanities/ArtsWe have already used some of the built-in functions.

Commonly used built-in functions

Functions Chapter Notes | Computer Science for Class 11 - Humanities/ArtsFunctions Chapter Notes | Computer Science for Class 11 - Humanities/ArtsFunctions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Module in Python

  • Python Standard Library: In addition to built-in functions, Python offers a standard library containing various modules.
  • Functions vs. Modules: While a function is a set of instructions, a module is a collection of functions. Functions help simplify code and avoid repetition, especially in larger programs.
  • Organizing Code: For complex problems, code is divided into different modules to manage it better. This allows for organized and modular programming.
  • Reusing Functions: If you have functions you want to use in different programs, you can save them in a module and reuse them. A module is essentially a Python (.py) file with function definitions.
  • Importing Modules: To use a module, you need to import it. Once imported, you can access all the functions within that module.
  • Import Statement Syntax: The syntax for importing a module is: import modulename1 [,modulename2, …]
  • Calling Functions from a Module: To call a function from a module, use the syntax: modulename.functionname()

(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:

  • math
  • random
  • statistics

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
Functions Chapter Notes | Computer Science for Class 11 - Humanities/ArtsFunctions Chapter Notes | Computer Science for Class 11 - Humanities/ArtsFunctions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

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
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Note:

  • The import statement can be placed anywhere in the program, but the module must be imported only once.
  • To get a list of available modules in Python, you can use the statement  help("module"). To view the content of a specific module, such as math, you can use  help("math").

(B) From Statement

  • The "from" statement in Python allows you to import only the specific functions you need from a module, rather than loading all the functions into memory. This can save memory and improve efficiency.
  • The syntax for the "from" statement is:  from modulename import functionname [, functionname,...]
  • When you import a function using the "from" statement, you can call it directly without prefixing it with the module name.

Example 7.5

  • Good Programming Practice: Importing only the necessary function(s) instead of the entire module helps save memory.
  • Code: from random import random
  • Output: random() #Function called without the module name  0.9796352504608387 

Example 7.6

  • Code: from math import ceil,sqrt
  • Output: value = ceil(624.7)  sqrt(value) 
  • Explanation: In this example, the  ceil  value of  624.  is stored in the variable  value , and then the  sqrt  function is applied to this variable. This can also be written as  sqrt(ceil(624.7)) , where the execution of the  sqrt() function depends on the output of the  ceil()  function.
  • Alternative Example: If you want to extract the integer part of  624.7 using the  trunc() function from the  math  module, you can do it as follows:  from math import trunc  sqrt(trunc(625.7)) 

Composition in Programming

  • A programming statement where functions or expressions depend on each other’s execution to produce an output is known as composition. For example:
  • a = int(input("First number: "))
  • print("Square root of ",a ," = ",math.sqrt(a))
  • print(floor(a+(b/c)))
  • math.sin(float(h)/float(c))

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.

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

Output:
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts
Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

The document Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Functions Chapter Notes - Computer Science for Class 11 - Humanities/Arts

1. What are functions in Python and why are they important?
Ans. Functions in Python are reusable pieces of code that perform a specific task. They help in organizing code, reducing redundancy, and improving readability. Functions allow programmers to break down complex problems into smaller, manageable parts, making code easier to maintain and debug.
2. How do you define a user-defined function in Python?
Ans. A user-defined function in Python is defined using the `def` keyword, followed by the function name and parentheses containing any parameters. The function body is indented below the definition. For example: python def my_function(parameter1, parameter2): # function body return result
3. What is the scope of a variable in Python and why does it matter?
Ans. The scope of a variable in Python refers to the region of the program where the variable is accessible. Variables can have local, global, or nonlocal scope. Understanding variable scope is crucial because it determines where a variable can be used and helps avoid variable name conflicts, leading to more predictable and bug-free code.
4. Can you explain the difference between local and global variables?
Ans. Local variables are defined within a function and can only be accessed inside that function. Global variables, on the other hand, are defined outside of any function and can be accessed throughout the entire program. This distinction is important to manage data flow and prevent unintended side effects in your code.
5. What are some common built-in functions in the Python Standard Library?
Ans. The Python Standard Library includes many built-in functions such as `print()`, `len()`, `max()`, `min()`, and `sum()`. These functions provide essential functionality for performing common tasks, such as outputting data, calculating lengths, and finding maximum or minimum values, thereby enhancing the capabilities of Python programming.
Related Searches

ppt

,

video lectures

,

shortcuts and tricks

,

Viva Questions

,

Exam

,

Semester Notes

,

Previous Year Questions with Solutions

,

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Summary

,

Sample Paper

,

mock tests for examination

,

past year papers

,

practice quizzes

,

Free

,

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

Extra Questions

,

pdf

,

Important questions

,

Objective type Questions

,

study material

,

Functions Chapter Notes | Computer Science for Class 11 - Humanities/Arts

,

MCQs

;