Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

CHAPTER 6:

FUNCTIONS

CHAPTER BLUEPRINT PLAN FOR FINAL EXAM

VSA SA LA E TOTAL

1 MARK 2 MARKS 3 MARKS 5 MARKS

PRIMUS PU COLLEGE, BANGALORE


1 MCQ 1 ------ 1 9 MARKS

1 FIB

MCQ

1. What is the process of dividing a computer program into separate independent


blocks of code known as?

a) Function programming

b) Modular programming

c) Structured programming

d) Object-oriented programming

Answer: b) Modular programming

2. What is the purpose of functions in programming?


a) To make the code longer

b) To reduce readability

c) To achieve modularity and reusability

d) To increase complexity

Answer: c) To achieve modularity and reusability

3. Which of the following statements is true about functions?


PRIMUS PU COLLEGE, BANGALORE

a) Functions can be called only once

b) Functions cannot have parameters

c) Functions can be called repeatedly

d) Functions must always return a value

Answer: c) Functions can be called repeatedly

4. What is the syntax to define a function in Python?

a) def function_name:

b) function function_name():

c) def function_name():

d) function function_name:

Answer: c) def function_name():


2
5. What does the 'return' statement do in a function?

a) Ends the function execution and optionally passes back an expression to the
caller

b) Outputs a value to the console

c) Starts the function execution

d) Defines a new function

Answer: a) Ends the function execution and optionally passes back an expression

PRIMUS PU COLLEGE, BANGALORE


to the caller

6. What is the term for a value passed to a function during the function call?

a) Parameter

b) Argument

c) Return value

d) Variable

Answer: b) Argument

7. What is a user-defined function?

a) A function provided by Python standard library

b) A function defined by the programmer


3
c) A function that cannot be reused

d) A function without parameters


Answer: b) A function defined by the programmer

8. In the function definition `def add(a, b):`, what are `a` and `b`?

a) Arguments

b) Return values

c) Parameters

d) Variables
PRIMUS PU COLLEGE, BANGALORE

Answer: c) Parameters

9. Which keyword is used to create a function in Python?

a) func

b) define

c) function

d) def

Answer: d) def

10. What is the output of the following code?

Python Code:

def greet(name):
4
return "Hello, " + name
print(greet("Alice"))

a) Hello,

b) Hello, greet

c) Hello, Alice

d) greet(Alice)

PRIMUS PU COLLEGE, BANGALORE


Answer: c) Hello, Alice

11. How do you call a function named `my_function` in Python?

a) call my_function()

b) my_function()

c) def my_function()

d) execute my_function()

Answer: b) my_function()

12. What will be the output of the following code?

Python Code:

def add(a, b):


5
return a + b
result = add(3, 5)

print(result)

a) 8

b) 3

c) 5
PRIMUS PU COLLEGE, BANGALORE

d) add

Answer: a) 8

13. What is an advantage of using functions in a program?

a) Decreases readability

b) Increases code length

c) Increases reusability

d) Makes debugging difficult

Answer: c) Increases reusability

14. What is the output of the following code?

Python Code:
6
def multiply(a, b):
return a * b

print(multiply(2, 4))

a) 2

b) 4

c) 6

PRIMUS PU COLLEGE, BANGALORE


d) 8

Answer: d) 8

15. Which of the following is not a characteristic of a function?

a) It can be reused

b) It must return a value

c) It can take arguments

d) It helps in modularity

Answer: b) It must return a value

16. What is the main advantage of breaking a program into smaller functions?

a) To make the program slower


7
b) To increase code repetition
c) To make the program more organized and manageable

d) To make the code more complex

Answer: c) To make the program more organized and manageable

17. What is the keyword used to return a value from a function in Python?

a) send

b) yield
PRIMUS PU COLLEGE, BANGALORE

c) return

d) give

Answer: c) return

18. What is the output of the following code?

Python Code:

def subtract(a, b):

return a - b

print(subtract(10, 3))

a) 7
8
b) 3
c) 10

d) -7

Answer: a) 7

19. Which of the following best describes a function?

a) A block of code that performs a specific task

b) A loop structure

PRIMUS PU COLLEGE, BANGALORE


c) A conditional statement

d) A data type

Answer: a) A block of code that performs a specific task

20. How do you define a function with no parameters?

a) def function_name[]:

b) def function_name():

c) function_name():

d) function_name[]:

Answer: b) def function_name():

21. What will be the output of the following code?


9
Python Code:
def divide(a, b):

return a / b

print(divide(10, 2))

a) 5.0

b) 5
PRIMUS PU COLLEGE, BANGALORE

c) 2

d) 0.5

Answer: a) 5.0

22. What is a function call?

a) Declaring a function

b) Executing a function

c) Returning a value from a function

d) Passing parameters to a function

Answer: b) Executing a function

23. Which of the following is an invalid function name in Python?


10
a) my_function
b) _function

c) function1

d) 1function

Answer: d) 1function

24. What is the output of the following code?

Python Code:

PRIMUS PU COLLEGE, BANGALORE


def say_hello():

print("Hello, World!")

say_hello()

a) Hello, World!

b) say_hello

c) print

d) Hello

Answer: a) Hello, World!

25. What is the main purpose of the `def` keyword in Python?


11
a) To define a variable
b) To define a function

c) To create a loop

d) To import a module

Answer: b) To define a function

26. Which of the following functions is used to find the length of a list in Python?

a) length()
PRIMUS PU COLLEGE, BANGALORE

b) len()

c) size()

d) count()

Answer: b) len()

27. What will be the output of the following code?

Python Code:

def square(x):

return x * x

print(square(3))

12
a) 3
b) 6

c) 9

d) 12

Answer: c) 9

28. What is a parameter in the context of functions?

a) A loop counter

PRIMUS PU COLLEGE, BANGALORE


b) A variable defined inside a loop

c) A value that a function returns

d) A variable used in the function definition

Answer: d) A variable used in the function definition

29. Which of the following is an example of a function with a return value?

a) def greet(): print("Hello!")

b) def greet(): return "Hello!"

c) def greet(): pass

d) def greet(): break

Answer: b) def greet(): return "Hello!"

13
30. What will be the output of the following code?
Python Code:

def concat(str1, str2):

return str1 + str2

print(concat("Hello, ", "World!"))

a) Hello
PRIMUS PU COLLEGE, BANGALORE

b) World

c) Hello, World!

d) concat

Answer: c) Hello, World!

31. How do you pass multiple arguments to a function in Python?

a) def function_name(arg1 arg2):

b) def function_name(arg1, arg2):

c) function_name(arg1; arg2)

d) def function_name[arg1, arg2]:

Answer: b) def function_name(arg1, arg2):

14
32. What will be the output of the following code?
Python Code:

def power(base, exp):

return base exp

print(power(2, 3))

a) 6

PRIMUS PU COLLEGE, BANGALORE


b) 8

c) 9

d) 12

Answer: b) 8

33. What is the main purpose of using functions in programming?

a) To decrease execution time

b) To reduce the need for loops

c) To organize code and promote reusability

d) To complicate the program

Answer: c) To organize code and promote reusability

15
34. What will be the output of the following code?
Python Code:

def add_five(x):

return x + 5

print(add_five(10))

a) 10
PRIMUS PU COLLEGE, BANGALORE

b) 15

c) 5

d) 20

Answer: b) 15

35. What is the keyword

used to define a function in Python?

a) function

b) define

c) def

d) func
16
Answer: c) def
36. What will be the output of the following code?

Python Code:

def greet():

return "Hello!"

print(greet())

PRIMUS PU COLLEGE, BANGALORE


a) greet

b) "Hello!"

c) Hello!

d) None

Answer: c) Hello!

37. How do you specify default values for parameters in a function?

a) def function_name(param=value):

b) def function_name(param==value):

c) function_name(param=value):

d) function_name(param==value):
17
Answer: a) def function_name(param=value):
38. What is the output of the following code?

Python Code:

def increment(n):

n += 1

return n
PRIMUS PU COLLEGE, BANGALORE

print(increment(7))

a) 6

b) 7

c) 8

d) 9

Answer: c) 8

39. Which statement is true regarding a function with multiple return


statements?

a) Only the first return statement will be executed

b) All return statements will be executed


18
c) The function will return multiple values
d) Only the last return statement will be executed

Answer: a) Only the first return statement will be executed

40. What will be the output of the following code?

Python Code:

def double(x):

return x * 2

PRIMUS PU COLLEGE, BANGALORE


result = double(4)

print(result)

a) 2

b) 4

c) 6

d) 8

Answer: d) 8

41. Which of the following is a correct way to document a function in Python?

a) Using comments (#)


19
b) Using triple-quoted strings (""" """)
c) Using single-quoted strings (' ')

d) Using parentheses ()

Answer: b) Using triple-quoted strings (""" """)

42. What will be the output of the following code?

Python Code:

def subtract(a, b):


PRIMUS PU COLLEGE, BANGALORE

return a - b

print(subtract(15, 5))

a) 10

b) 20

c) 15

d) 5

Answer: a) 10

43. What is the term used for a function defined inside another function?

a) Nested function
20
b) Inner function
c) Sub function

d) Lambda function

Answer: a) Nested function

44. What will be the output of the following code?

Python Code:

def sum_numbers(a, b):

PRIMUS PU COLLEGE, BANGALORE


return a + b

result = sum_numbers(3, 4)

print(result)

a) 3

b) 4

c) 7

d) 10

Answer: c) 7

45. What is the output of the following code?


21
Python Code:
def identity(x):

return x

print(identity("Python"))

a) Python

b) identity
PRIMUS PU COLLEGE, BANGALORE

c) "Python"

d) print

Answer: a) Python

46. How do you ensure a function has a variable number of arguments in Python?

a) Using an asterisk (*) before the parameter name

b) Using double asterisks ( ) before the parameter name

c) Using an ampersand (&) before the parameter name

d) Using a hash (#) before the parameter name

Answer: a) Using an asterisk (*) before the parameter name

47. What will be the output of the following code?


22
Python Code:
def repeat_string(s, n):

return s * n

print(repeat_string("Hi", 3))

a) Hi

b) HiHiHi

PRIMUS PU COLLEGE, BANGALORE


c) Hi3

d) repeat_string

Answer: b) HiHiHi

48. Which of the following is not a valid Python function?

a) def my_func():

b) def my-func():

c) def my_func1():

d) def _myfunc():

Answer: b) def my-func():

49. What is the primary purpose of a lambda function in Python?


23
a) To create a complex function
b) To define a function with a long body

c) To create small anonymous functions

d) To define a class method

Answer: c) To create small anonymous functions

50. What will be the output of the following code?

Python Code:
PRIMUS PU COLLEGE, BANGALORE

def add(a, b=5):

return a + b

print(add(3))

a) 3

b) 5

c) 8

d) 15

Answer: c) 8

24
FILL IN THE BLANKS (Sample)

1. The process of dividing a computer program into separate independent


blocks of code is known as __________.
o Answer: modular programming
2. A function can be defined as a named group of instructions that accomplish
a specific task when it is __________.
o Answer: invoked
3. A function definition begins with the keyword __________.

PRIMUS PU COLLEGE, BANGALORE


o Answer: def
4. The function header always ends with a __________.
o Answer: colon (:)
5. The default value assigned to a parameter in a function definition is known
as a __________.
o Answer: default value
6. A function defined to achieve some task as per the programmer's
requirement is called a __________ function.
o Answer: user defined

2 MARKS QUESTIONS

2 Marks Questions

1. Define a user-defined function in Python.


o A user-defined function is a function created by the programmer to
perform specific tasks according to their requirements. It is defined
using the def keyword followed by the function name and parameters.
25
2. What are the benefits of using functions in a program?
o Functions help in breaking down complex problems into smaller,
manageable parts. They promote code reusability, improve readability,
and make maintenance easier.
3. Explain the concept of a global variable with an example.
o A global variable is defined outside of any function and can be accessed
in any function defined onwards. Example:

num = 5
def myfunc1():
global num
PRIMUS PU COLLEGE, BANGALORE

print("Accessing num =", num)


num = 10
print("num reassigned =", num)
myfunc1()
print("Accessing num outside myfunc1", num)

Output:

Accessing num = 5
num reassigned = 10
Accessing num outside myfunc1 10

4. Explain the concept of a local variable with an example.


o A local variable is defined within a function or block and can only be
accessed within that function or block. It exists only for the duration of
the function's execution. Example:

def myFunc1():
y = num + 5
print("Accessing num -> (global) in myFunc1, value =",
26
num)
print("Accessing y-> (local variable of myFunc1)
accessible, value=", y)
myFunc1()
print("Accessing num outside myFunc1", num)
print("Accessing y outside myFunc1", y)

Output:

Accessing num -> (global) in myFunc1, value = 5


Accessing y-> (local variable of myFunc1) accessible,
value = 10

PRIMUS PU COLLEGE, BANGALORE


Accessing num outside myFunc1 5
NameError: name ‘y’ is not defined
​:citation[oaicite:0]{index=0}​

5. How do you call a function in Python?


o To call a function in Python, write the function name followed by
parentheses containing any required arguments. Example:

answer = calcpow(base, expo)

6. What is the syntax for defining a user-defined function in Python?


o The syntax for defining a user-defined function is:

def function_name(parameters):
# function body

7. What is an argument in the context of functions?


o An argument is a value that is passed to a function when it is called.
Arguments are used by the function to perform operations or
calculations. 27
8. What is a parameter in the context of functions?
o A parameter is a variable in the function definition that receives the
value of an argument when the function is called.
9. What is the difference between a built-in function and a user-defined
function?
o Built-in functions are pre-defined in Python and available for use
directly (e.g., print(), input()). User-defined functions are created
by the programmer to perform specific tasks.
10. Explain the term "scope of a variable".
o The scope of a variable refers to the part of the program where the
PRIMUS PU COLLEGE, BANGALORE

variable can be accessed. Variables can have a global scope (accessible


throughout the program) or a local scope (accessible only within the
function or block where they are defined).
11. What does the global keyword do in Python?
o The global keyword is used to declare that a variable inside a function
is global, allowing the function to modify the variable outside its local
scope.
12. What is the significance of the return statement in a function?
o The return statement ends the execution of a function and optionally
sends a value back to the caller. It allows functions to produce output
based on their operations.
13. Describe how you can import a specific function from a module.
o You can import a specific function from a module using the from
keyword followed by the module name and the import keyword.
Example:

from math import sqrt


28
14. What happens if a global variable and a local variable have the same name
within a function?
o If a global variable and a local variable have the same name within a
function, the local variable will hide the global variable within that
function's scope. Any changes to the variable will only affect the local
variable.
15. Explain the purpose of the import statement in Python.
o The import statement is used to include external modules or libraries
into a Python program, allowing the use of their functions, classes, and

PRIMUS PU COLLEGE, BANGALORE


variables.
16. What is the Python Standard Library?
o The Python Standard Library is a collection of modules and packages
that come with Python, providing a wide range of functionalities, such
as file I/O, system calls, and networking.
17. How does Python handle multiple imports of the same module?
o Python handles multiple imports of the same module efficiently by
loading the module only once. Subsequent imports will use the already
loaded module from the cache.
18. What is the role of indentation in Python function definitions?
o Indentation in Python is crucial for defining the body of a function. It
indicates the block of code that belongs to the function, ensuring proper
structure and readability.

29
3 MARKS QUESTIONS

1. Explain the advantages of using functions in a program with examples.

Functions provide several advantages in programming:

o Increased Readability: Functions make code more organized and


easier to understand. For example, breaking down a complex task into
smaller functions makes the main program more readable.
o Reduced Code Length: Functions prevent code repetition. The same
PRIMUS PU COLLEGE, BANGALORE

code does not need to be written at multiple places, which also makes
debugging easier. For example, a function to calculate the area of a
circle can be reused whenever needed.
o Reusability: Functions can be reused in different parts of the program
or in different programs. For example, a function that calculates the tax
on a product can be used in various billing systems.
o Parallel Development: Work can be divided among team members and
completed in parallel. Each member can work on different functions.
2. Write a short program to demonstrate the use of a global variable.

x = 10 # global variable

def increase():
global x
x += 5
print("Inside function, x =", x)

increase()
30 print("Outside function, x =", x)

Output:
Inside function, x = 15
Outside function, x = 15

3. Write a short program to demonstrate the use of a local variable.

def example():
y = 5 # local variable
y += 3
print("Inside function, y =", y)

example()

PRIMUS PU COLLEGE, BANGALORE


# Uncommenting the following line would raise an error
# print("Outside function, y =", y)

Output:

Inside function, y = 8

4. Explain with an example how a function can return multiple values in


Python. In Python, a function can return multiple values by returning a tuple.

def get_min_max(numbers):
return min(numbers), max(numbers)

nums = [1, 2, 3, 4, 5]
minimum, maximum = get_min_max(nums)
print("Min:", minimum)
print("Max:", maximum)

Output:

Min: 1 31
Max: 5
5. Describe the process of creating a user-defined function with parameters.
Creating a user-defined function with parameters involves:
o Using the def keyword followed by the function name and parameters
in parentheses.
o Writing the function body indented under the function header.
o Optionally, returning a value using the return statement.

def greet(name):
print("Hello,", name)
PRIMUS PU COLLEGE, BANGALORE

greet("Alice")

Output:

Hello, Alice

6. Write a function that calculates the sum of the first n natural numbers.

def sum_natural_numbers(n):
return n * (n + 1) // 2

print("Sum of first 5 natural numbers:", sum_natural_numbers(5))

Output:

Sum of first 5 natural numbers: 15

7. What is the purpose of the return statement in a Python function? Give an


example. The return statement is used to exit a function and return a value to
the caller.
32
def square(x):
return x * x
result = square(4)
print("Square of 4 is", result)

Output:

Square of 4 is 16

8. Explain the difference between positional and keyword arguments with


examples.
o Positional Arguments: Arguments passed to a function based on their

PRIMUS PU COLLEGE, BANGALORE


position.

def display_info(name, age):


print("Name:", name)
print("Age:", age)

display_info("Alice", 25)

o Keyword Arguments: Arguments passed to a function by explicitly


naming each parameter.

display_info(age=25, name="Alice")

9. Output:

Name: Alice
Age: 25

10. How do you handle default values in function parameters? Provide an


example. Default values can be provided in function parameters by assigning
33
values in the function header.
def greet(name, message="Hello"):
print(message, name)

greet("Alice")
greet("Bob", "Good morning")

Output:

Good morning Bob

11. Write a short program to demonstrate the use of the global keyword.
PRIMUS PU COLLEGE, BANGALORE

count = 0

def increment():
global count
count += 1

increment()
print("Count after increment:", count)

Output:

Count after increment: 1

12. Describe the flow of execution in a Python program with multiple function
calls. The flow of execution in a Python program with multiple function calls
involves:
o Starting at the first statement of the program.
o Executing function definitions but not their bodies.

34 o When a function is called, jumping to the function body and executing


it.
o Returning to the point after the function call once the function
completes.

def first():
print("First function")

def second():
print("Second function")

first()
second()

PRIMUS PU COLLEGE, BANGALORE


Output:

First function
Second function

13. Explain the concept of a module in Python and how it helps in program
development. A module in Python is a file containing Python code, which can
include functions, classes, and variables. Modules help in:
o Organizing code into manageable sections.
o Reusing code across different programs by importing the module.
o Reducing redundancy and improving maintainability.

# example_module.py
def greet(name):
print("Hello,", name)

# main_program.py
import example_module 35

example_module.greet("Alice")
Output:

Hello, Alice

14. Write a short program to demonstrate the use of the Python Standard
Library.

import math

def calculate_circle_area(radius):
return math.pi * radius ** 2
PRIMUS PU COLLEGE, BANGALORE

print("Area of a circle with radius 5:",


calculate_circle_area(5))

Output:

Area of a circle with radius 5: 78.53981633974483

15. How can you reuse functions from another program or module? Explain
with an example. Functions from another program or module can be reused by
importing the module.

# math_functions.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

# main_program.py
36 import math_functions
print("Addition:", math_functions.add(5, 3))
print("Subtraction:", math_functions.subtract(5, 3))

Output:

Addition: 8
Subtraction: 2

16. Explain the importance of the def keyword in Python. The def keyword is
used to define a new function. It tells the Python interpreter that the following
block of code is a function.

PRIMUS PU COLLEGE, BANGALORE


python
Copy code
def greet(name):
print("Hello,", name)

17. Describe how function headers and function calls work in Python.
o Function Header: Begins with def, followed by the function name,
parentheses, and a colon. It may include parameters.

def greet(name):

o Function Call: Executes the function by providing arguments if needed.

greet("Alice")

o When a function is called, the control is passed to the function body,


and once the function completes, the control returns to the point after
the function call.
18. Write a short program that includes both user-defined functions and built- 37
in functions.
def square(num):
return num * num

num = int(input("Enter a number: "))


result = square(num)
print("Square of", num, "is", result)

Output:

Enter a number: 4
Square of 4 is 16
PRIMUS PU COLLEGE, BANGALORE

19. Explain the significance of the colon (:) at the end of a function header in
Python. The colon (:) at the end of a function header indicates the beginning
of the function body. It tells the Python interpreter that the following indented
block of code belongs to the function.

def greet(name):
print("Hello,", name)

5 MARKS QUESTIONS

1. Write a Python program that demonstrates the use of both global and local
variables within multiple functions.

x = 50 # global variable

def func1():
global x
x += 10
y = 20 # local variable
38
print("func1 - global x:", x)
print("func1 - local y:", y)
def func2():
z = 30 # local variable
print("func2 - global x:", x)
print("func2 - local z:", z)

func1()
func2()
print("Global x after functions:", x)

Output:

PRIMUS PU COLLEGE, BANGALORE


func1 - global x: 60
func1 - local y: 20
func2 - global x: 60
func2 - local z: 30
Global x after functions: 60

2. Discuss in detail the advantages of using functions in programming. Use


examples to support your explanation.

Functions offer several advantages in programming:

o Modularity: Functions break down a program into smaller, manageable


pieces. This makes the program easier to understand and maintain.

def add(a, b):


return a + b

def subtract(a, b):


return a - b
39
o Reusability: Functions can be reused across different parts of a program
or in different programs without rewriting the code.

result1 = add(5, 3)
result2 = subtract(10, 4)

o Readability: Functions provide a clear structure, making the code more


readable.

def calculate_area(radius):
pi = 3.14159
PRIMUS PU COLLEGE, BANGALORE

return pi * radius ** 2

print("Area of circle:", calculate_area(5))

o Testing and Debugging: Smaller functional units are easier to test and
debug compared to a large block of code.

def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0

o Parallel Development: Functions allow multiple developers to work on


different parts of a program simultaneously.

def feature1():
pass # Developer A

def feature2():
pass # Developer B

40
3. Write a Python function to calculate the factorial of a number.
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print("Factorial of",num,"is",fact)

num = int(input("Enter the number: "))


calcFact(num)

Output:

PRIMUS PU COLLEGE, BANGALORE


Enter the number: 5

Factorial of 5 is 120

4. Describe in detail the process of creating, calling, and executing a user-


defined function in Python.
o Creating a Function:
▪ Use the def keyword followed by the function name and
parentheses.
▪ Inside the parentheses, define any parameters.
▪ End the function header with a colon (:).
▪ Indent the function body, which contains the code to execute.

def greet(name):
print("Hello,", name)

o Calling a Function:
▪ Use the function name followed by parentheses.
▪ Pass arguments inside the parentheses if the function requires 41

parameters.
greet("Alice")

o Executing a Function:
▪ When a function is called, Python executes the code within the
function body.
▪ If the function returns a value, it can be captured in a variable or
used directly.

def add(a, b):


return a + b
PRIMUS PU COLLEGE, BANGALORE

result = add(3, 4)
print("Sum:", result)

5. Explain the concept of scope in Python with detailed examples.

Scope refers to the region of a program where a variable is accessible. There


are two main types of scope in Python:

o Local Scope: Variables defined within a function. They can only be


accessed inside that function.

def my_function():
local_var = 10
print(local_var)

my_function()
# print(local_var) # This would raise an error

o Global Scope: Variables defined outside of all functions. They can be


42
accessed from anywhere in the program.

global_var = 20
def another_function():
print(global_var)

another_function()
print(global_var)

6. Write a comprehensive program that uses functions to perform


mathematical operations (addition, subtraction, multiplication, division)
and demonstrates passing arguments and returning values.

PRIMUS PU COLLEGE, BANGALORE


def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0:
return a / b
else:
return "Division by zero is not allowed"

def main():
x = 10
y = 5

print("Addition:", add(x, y))


43
print("Subtraction:", subtract(x, y))
print("Multiplication:", multiply(x, y))
print("Division:", divide(x, y))

main()

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
PRIMUS PU COLLEGE, BANGALORE

7. Discuss the role and benefits of the Python Standard Library in program
development. Provide examples of commonly used modules and functions.

The Python Standard Library is a collection of modules and packages included


with Python. It provides standardized solutions for various programming tasks,
reducing the need for third-party libraries. Benefits include:

o Consistency and Reliability: The library is maintained by the Python


development team, ensuring high quality and consistency.
o Efficiency: Provides efficient implementations for common tasks like
file handling, data manipulation, and more.
o Ease of Use: Simplifies complex tasks with easy-to-use functions and
classes.
o Portability: Code using the standard library is more portable across
different systems.

Commonly Used Modules and Functions:

44 o math: Provides mathematical functions.

import math
print(math.sqrt(16))

o random: For generating random numbers.

import random
print(random.randint(1, 10))

8. Explain the different types of function arguments in Python (positional,


keyword, default, variable-length) with examples.
o Positional Arguments: Passed to functions in the order they are

PRIMUS PU COLLEGE, BANGALORE


defined.

def greet(name, age):


print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)

o Keyword Arguments: Passed to functions by explicitly naming each


parameter.

greet(age=25, name="Alice")

o Default Arguments: Parameters with default values. If no argument is


provided, the default value is used.

def greet(name, age=18):


print(f"Hello {name}, you are {age} years old.")

greet("Alice")
greet("Bob", 25)

45
9. Write a detailed program that demonstrates the use of modules in Python.
Show how to import modules, use functions from them, and handle
namespace conflicts.

# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b
PRIMUS PU COLLEGE, BANGALORE

# main_program.py
import math_operations as mo
from math import sqrt # Importing specific function

def main():
x = 10
y = 5

print("Addition:", mo.add(x, y))


print("Subtraction:", mo.subtract(x, y))
print("Square root of 16:", sqrt(16))

main()

Output:

Addition: 15
Subtraction: 5
Square root of 16: 4.0

46
10. Discuss the importance of modularity and reusability in programming. Use
Python functions and modules to illustrate your points.
o Modularity: Dividing a program into separate modules that perform
distinct tasks. Each module can be developed, tested, and debugged
independently, enhancing maintainability and scalability.

# module1.py
def function1():
pass

# module2.py
def function2():

PRIMUS PU COLLEGE, BANGALORE


pass

# main.py
import module1
import module2

module1.function1()
module2.function2()

o Reusability: Writing code that can be reused in different parts of a


program or in different programs, reducing redundancy and increasing
efficiency.

# math_functions.py
def add(a, b):
return a + b

# main_program.py
import math_functions as mf

result = mf.add(3, 4) 47
print("Sum:", result)
Modularity and reusability make programs easier to understand, reduce
development time, and minimize the risk of errors.

11. Write a comprehensive guide on how to create and use user-defined


functions in Python, including examples, best practices, and common
pitfalls to avoid.
o Creating Functions:
▪ Use the def keyword followed by the function name and
parentheses.
PRIMUS PU COLLEGE, BANGALORE

▪ Inside the parentheses, define any parameters.


▪ End the function header with a colon (:).
▪ Indent the function body, which contains the code to execute.

def greet(name):
print("Hello,", name)

o Calling Functions:
▪ Use the function name followed by parentheses.
▪ Pass arguments inside the parentheses if the function requires
parameters.

greet("Alice")

o Best Practices:
▪ Use meaningful function names that describe what the function
does.
▪ Keep functions short and focused on a single task.
▪ Document functions with comments and docstrings.
48
▪ Handle edge cases and errors within the function.
o Common Pitfalls:
▪ Forgetting to return a value from the function.

def add(a, b):


return a + b

result = add(2, 3)
print(result) # Correct usage

▪ Using global variables unnecessarily, which can lead to code


that is difficult to understand and debug.

PRIMUS PU COLLEGE, BANGALORE


count = 0

def increment():
global count
count += 1

▪ Overusing default mutable arguments (e.g., lists or dictionaries),


which can lead to unexpected behavior.

def append_to_list(value, my_list=[]):


my_list.append(value)
return my_list

print(append_to_list(1)) # [1]
print(append_to_list(2)) # [1, 2] (unexpected)

# Correct way
def append_to_list(value, my_list=None):
if my_list is None:
my_list = []
my_list.append(value) 49
return my_list
print(append_to_list(1)) # [1]
print(append_to_list(2)) # [2]

Example:

def factorial(n):
"""Calculate the factorial of a number."""
if n == 0:
return 1
else:
return n * factorial(n-1)
PRIMUS PU COLLEGE, BANGALORE

print("Factorial of 5:", factorial(5))

Output:

Factorial of 5: 120

EXERCISES (CHAPTER END QUESTIONS)

1. Identify the errors in the following programs:

a)

def create(text, freq):


for i in range(1, freq):
print(text)
create(5) # function call

50 Error: The function call create(5) is missing a second argument for freq.

b)
from math import sqrt, ceil

def calc():
print(cos(0))
calc() # function call

Error: The function cos from the math module is not imported.

c)

mynum = 9

PRIMUS PU COLLEGE, BANGALORE


def add9():
mynum = mynum + 9
print(mynum)
add9() # function call

Error: mynum is referenced before assignment within the function. Declare


global mynum inside the function.

d)

def findValue(vall=1.1, val2, val3):


final = (val2 + val3) / vall
print(final)
findvalue() # function call

Error: Non-default argument follows default argument. Also, findvalue()


should be findValue().

e)
51
def greet():
return "Good morning"
greet() = message # function call

Error: Cannot assign to function call. Correct way is message = greet().

2. Difference between math.ceil(89.7) and math.floor(89.7)


o math.ceil(89.7) returns the smallest integer greater than or equal to
89.7, which is 90.
o math.floor(89.7) returns the largest integer less than or equal to 89.7,
PRIMUS PU COLLEGE, BANGALORE

which is 89.
3. Use of random() vs randint() to generate random numbers between 1 and
5

To generate random numbers between 1 and 5, use randint(1, 5). The


randint() function allows specifying a range, while random() generates a
float between 0.0 and 1.0 which would need to be scaled and converted to an
integer.

4. Difference between built-in function pow() and math.pow()


o pow(x, y) is a built-in function that returns x raised to the power y.
o math.pow(x, y) is a function from the math module that returns x
raised to the power y but always returns a float.

Example:

result1 = pow(3, 2) # result1 is 9


result2 = math.pow(3, 2) # result2 is 9.0
52
5. Example of a function returning multiple values in Python
def sum_and_product(a, b):
sum = a + b
product = a * b
return sum, product

s, p = sum_and_product(2, 3)
print("Sum:", s)
print("Product:", p)

6. Differentiate between Argument and Parameter, Global and Local


variable

PRIMUS PU COLLEGE, BANGALORE


a) Argument vs Parameter:

o Parameter: Variable in the function definition (e.g., n in def func(n):).


o Argument: Value passed to the function (e.g., 5 in func(5)).

b) Global vs Local variable:

o Global Variable: Defined outside any function and accessible anywhere


in the code.
o Local Variable: Defined inside a function and accessible only within
that function.

Example:

x = 10 # global variable

def func():
y = 5 # local variable
print("Local y:", y) 53

func()
print("Global x:", x)

7. Does a function always return a value?

No, a function does not always return a value. Functions that do not explicitly
return a value return None by default.

Example:

def greet():
print("Hello")
PRIMUS PU COLLEGE, BANGALORE

result = greet() # result is None


print(result) # prints None

****************

54

You might also like