Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Functions

The document provides a comprehensive overview of functions in Python, detailing types such as built-in, module-defined, and user-defined functions. It covers key concepts including function creation, parameters, return values, flow of execution, and variable scope. Additionally, it includes questions and exercises to reinforce understanding of these concepts.

Uploaded by

prafulla gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Functions

The document provides a comprehensive overview of functions in Python, detailing types such as built-in, module-defined, and user-defined functions. It covers key concepts including function creation, parameters, return values, flow of execution, and variable scope. Additionally, it includes questions and exercises to reinforce understanding of these concepts.

Uploaded by

prafulla gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

FUNCTIONS

CBSE SYLLABUS
Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable
(global scope, local scope)

Topic Wise Notes

What is a Function in Python?


A function in Python is a block of reusable code that performs a specific task. It helps in
organizing code, improving readability, and avoiding repetition.

Types of Functions in Python:

Built-in Functions – Predefined functions like print(), len(), sum(), etc.

Types of Functions in Python


Functions in Python can be categorized into three main types:
1. Built-in Functions
2. Functions Defined in a Module (Library Functions)
3. User-defined Functions

1. Built-in Functions
These are pre-defined functions in Python that can be used directly without any import.

Examples:

print(len("Python")) # Finds length → Output: 6


print(max(10, 20, 5)) # Finds maximum → Output: 20
print(sum([1, 2, 3, 4])) # Sums numbers → Output: 10
print(abs(-10)) # Absolute value → Output: 10

👉 Common Built-in Functions: print(), len(), sum(), max(), min(), abs(), type(), input(), etc.

2. Functions Defined in a Module (Library Functions)


These functions are provided by Python modules (libraries) and require import before use.

Examples:

(a) Math Module Functions


import math
print(math.sqrt(25)) # Square root → Output: 5.0
print(math.factorial(5)) # Factorial → Output: 120
print(math.pi) # Value of pi → Output: 3.141592653589793

(b) Random Module Functions


import random
print(random.randint(1, 10)) # Random number between 1 and 10
print(random.choice(["Apple", "Banana", "Mango"])) # Random selection

Page 0 of 28
👉 Common Modules with Functions:
math → sqrt(), factorial(), pow(), ceil(), floor()
random → randint(), choice(), shuffle()
datetime → datetime.now(), strftime()

3. User-defined Functions
These are functions created by the user using the def keyword.
Examples:

(a) Function Without Parameters


def greet():
print("Hello, Welcome to Python!")

greet() # Calling the function

Output:
Hello, Welcome to Python!

(b) Function With Parameters


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

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

Output:
Sum: 8

(c) Function With Default Parameters


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

greet() # Uses default value


greet("Riya") # Overrides default value

Output:
Hello, Guest
Hello, Riya

(d) Function Returning Multiple Values


def operations(a, b):
return a + b, a - b, a * b, a / b

add, sub, mul, div = operations(10, 2)


print("Addition:", add)
print("Subtraction:", sub)
print("Multiplication:", mul)
print("Division:", div)

Output:

Page 1 of 28
Addition: 12
Subtraction: 8
Multiplication: 20
Division: 5.0

User-Defined Functions in Python


A user-defined function is a function created by the user using the def keyword. It allows
code reusability and improves readability.

1. Creating a User-Defined Function


 To define a function in Python:
 Use the def keyword.
 Provide a function name.
 Specify parameters (optional).
 Write the function body with indentation.
 Use return (optional) to return a value.

Example:
def greet():
print("Hello, Welcome to Python!")

greet() # Calling the function

Output:
Hello, Welcome to Python!

2. Arguments and Parameters

Parameter: A variable defined in the function signature.


Argument: A value passed to the function when calling it.

Example:
def add(a, b): # a and b are parameters
return a + b

result = add(5, 3) # 5 and 3 are arguments


print("Sum:", result)

Output:
Sum: 8

3. Default Parameters

A default parameter has a predefined value, which is used if no argument is provided.


Example:
def greet(name="Guest"):
print("Hello,", name)

greet() # Uses default value "Guest"


greet("Riya") # Overrides default value

Output:
Hello, Guest

Page 2 of 28
Hello, Riya

4. Positional Parameters

In positional parameters, arguments are assigned to parameters based on their position.

Example:
def person_details(name, age):
print("Name:", name)
print("Age:", age)

person_details("Riya", 16) # Correct order


person_details(16, "Riya") # Incorrect order leads to wrong output

Output (Correct Order):


Name: Riya
Age: 16

Output (Incorrect Order):


Name: 16
Age: Riya
👉 Order matters in positional parameters!

1. Function Returning Value(s)


A function can return a value using the return statement. It allows the function to send back
data to the caller.

Example: Function Returning a Single Value


def square(num):
return num * num

result = square(5) # Function call


print("Square:", result)

Output:
Square: 25

Example: Function Returning Multiple Values

A function can return multiple values as a tuple.

def math_operations(a, b):


return a + b, a - b, a * b, a / b

add, sub, mul, div = math_operations(10, 2)


print("Addition:", add)
print("Subtraction:", sub)
print("Multiplication:", mul)
print("Division:", div)

Output:
Addition: 12

Page 3 of 28
Subtraction: 8
Multiplication: 20
Division: 5.0

2. Flow of Execution in a Function


When a function is called:
The program jumps to the function definition.
The function executes its statements in order.
The function returns a value (if specified).
The control goes back to the calling statement.

Example:
def greet():
print("Step 1: Inside function")
return "Hello!"
print("Step 2: This will not execute") # Unreachable

print("Step 3: Before function call")


message = greet() # Function call
print("Step 4: After function call", message)

Output:
Step 3: Before function call
Step 1: Inside function
Step 4: After function call Hello!
👉 Note: Statements after return do not execute.

3. Scope of a Variable
The scope of a variable determines where it can be accessed.

(a) Local Scope


A variable declared inside a function is local and cannot be accessed outside.

Example:
def my_function():
x = 10 # Local variable
print("Inside function:", x)

my_function()
print("Outside function:", x) # Error! x is not accessible here

Error:
NameError: name 'x' is not defined

(b) Global Scope


A variable declared outside a function is global and can be accessed inside functions.

Example:
x = 100 # Global variable

def my_function():
print("Inside function:", x)

Page 4 of 28
my_function()
print("Outside function:", x) # Accessible everywhere

Output:
Inside function: 100
Outside function: 100

(c) Using global Keyword


If we modify a global variable inside a function, we must use the global keyword.

Example:
x = 10 # Global variable

def change_value():
global x
x = 20 # Modifying global variable
print("Inside function:", x)

change_value()
print("Outside function:", x) # Modified globally

Output:
Inside function: 20
Outside function: 20

Working with Functions (Sumita Arora)


Question 1
What is the default return value for a function that does not return any value explicitly?
1. None
2. int
3. double
4. null
Question 2
Which of the following items are present in the function header?
1. function name only
2. both function name and parameter list
3. parameter list only
4. return value
Question 3
Which of the following keywords marks the beginning of the function block?
1. func
2. define
3. def
4. function
Question 4
What is the name given to that area of memory where the system stores the parameters and
local variables of a function call?
1. a heap
2. storage area
3. a stack

Page 5 of 28
4. an array
Question 5
Pick one of the following statements to correctly complete the function body in the given
code snippet.
def f(number):
#Missing function body
print(f(5))
1. return "number"
2. print(number)
3. print("number")
4. return number
Question 6
Which of the following function headers is correct?
1. def f(a = 1, b):
2. def f(a = 1, b, c = 2):
3. def f(a = 1, b = 1, c = 2):
4. def f(a = 1, b = 1, c = 2, d):
Question 7
Which of the following statements is not true for parameter passing to functions?
1. You can pass positional arguments in any order.
2. You can pass keyword arguments in any order.
3. You can call a function with positional and keyword arguments.
4. Positional arguments must be before keyword arguments in a function call.
Question 8
Which of the following is not correct in the context of Positional and Default parameters in
Python functions?
1. Default parameters must occur to the right of Positional parameters.
2. Positional parameters must occur to the right of Default parameters.
3. Positional parameters must occur to the left of Default parameters.
4. All parameters to the right of a Default parameter must also have Default values.
Question 9
Which of the following is not correct in the context of the scope of variables?
1. Global keyword is used to change the value of a global variable in a local scope.
2. Local keyword is used to change the value of a local variable in a global scope.
3. Global variables can be accessed without using the global keyword in a local scope.
4. Local variables cannot be used outside their scope.
Question 10
Which of the following function calls can be used to invoke the below function definition?
def test(a, b, c, d):
1. test(1, 2, 3, 4)
2. test(a = 1, 2, 3, 4)
3. test(a = 1, b = 2, c = 3, 4)
4. test(a = 1, b = 2, c = 3, d = 4)
Question 11
Which of the following function calls will cause an error while invoking the below function
definition?
def test(a, b, c, d):
1. test(1, 2, 3, 4)
2. test(a = 1, 2, 3, 4)
3. test(a = 1, b = 2, c = 3, 4)
4. test(a = 1, b = 2, c = 3, d = 4)
Question 12
For a function header as follows:

Page 6 of 28
def Calc(X, Y = 20):
Which of the following function calls will give an error?
1. Calc(15, 25)
2. Calc(X = 15, Y = 25)
3. Calc(Y = 25)
4. Calc(X = 25)
Question 13
What is a variable defined outside all the functions referred to as?
1. A static variable
2. A global variable
3. A local variable
4. An automatic variable
Question 14
What is a variable defined inside a function referred to as?
1. A static variable
2. A global variable
3. A local variable
4. An automatic variable
Question 15
Carefully observe the code and give the answer.
def function1(a):
a = a + '1'
a=a*2
function1("hello")
1. Indentation Error
2. Cannot perform mathematical operation on strings
3. hello2
4. hello2hello2
Question 16
What is the result of this code?
def print_double(x):
print(2 ** x)
print_double(3)
1. 8
2. 6
3. 4
4. 10
Question 17
What is the order of resolving the scope of a name in a Python program?
1. B G E L
2. L E G B
3. G E B L
4. L B E G
Question 18
Which of the given argument types can be skipped from a function call?
1. Positional arguments
2. Keyword arguments
3. Named arguments
4. Default arguments

Fill in the Blanks

Page 7 of 28
Question 1
A function is a subprogram that acts on data and often returns a value.

Question 2
Python names the top-level segment (main program) as main.

Question 3
In Python, program execution begins with the first statement of the main segment.

Question 4
The values being passed through a function-call statement are called arguments.

Question 5
The values received in the function definition/header are called parameters.

Question 6
A parameter having a default value in the function header is known as a default parameter.

Question 7
A default argument can be skipped in the function call statement.

Question 8
Keyword arguments are the named arguments with assigned values being passed in the
function call statement.

Question 9
A void function also returns a None value to its caller.

Question 10
By default, Python names the segment with top-level statements (main program) as main.

Question 11
The flow of execution refers to the order in which statements are executed during a program
run.

Question 12
The default value for a parameter is defined in the function header.

True/False Questions

Question 1
Non-default arguments can be placed before or
False – Non-default arguments must be placed before default arguments in a function
header.

Question 2
A parameter having default value in the function header is known as a default parameter.

Question 3
The first line of function definition that begins with keyword def and ends with a colon (:), is
also known as function header.

Question 4

Page 8 of 28
Variables that are listed within the parentheses of a function header are called function
variables.
False – Variables listed within the parentheses of a function header are called parameters,
not function variables.

Question 5
In Python, the program execution begins with first statement of __main__ segment.

Question 6
Default parameters cannot be skipped in function call.
False – Default parameters can be skipped in a function call because they already have
assigned default values.

Question 7
The default values for parameters are considered only if no value is provided for that
parameter in the function call statement.

Question 8
A Python function may return multiple values.

Question 9
A void function also returns a value i.e., None to its caller.

Question 10
Variables defined inside functions can have global scope.

Question 11
A local variable having the same name as that of a global variable, hides the global variable
in its function.
False – Variables defined inside functions have local scope and cannot be accessed
globally unless declared using the global keyword.

Assertions and Reasons


Question 1
Assertion. A function is a subprogram.
Reason. A function exists within a program and works within it when called.

Question 2
Assertion. Non-default arguments cannot follow default arguments in a function call.
Reason. A function call can have different types of arguments.

Question 3
Assertion. A parameter having a default in function header becomes optional in function
call.
Reason. A function call may or may not have values for default arguments.

Question 4
Assertion. A variable declared inside a function cannot be used outside it.
Reason. A variable created inside a function has a function scope.

Question 5
Assertion. A variable not declared inside a function can still be used inside the function if it
is declared at a higher scope level.

Page 9 of 28
Reason. Python resolves a name using LEGB rule where it checks in Local (L), Enclosing
(E), Global (G) and Built- in scopes (B), in the given order.

Question 6
Assertion. A parameter having a default value in the function header is known as a default
parameter.
Reason. The default values for parameters are considered only if no value is provided for
that parameter in the function call statement.

Question 7
Assertion. A function declaring a variable having the same name as a global variable,
cannot use that global variable.
Reason. A local variable having the same name as a global variable hides the global variable
in its function.

Question 8
Assertion. If the arguments in a function call statement match the number and order of
arguments as defined in the function definition, such arguments are called positional
arguments.
Reason. During a function call, the argument list first contains default argument(s) followed
positional argument(s).

Answer-

Question 1
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 2
(c) The assertion is correct but the reason is incorrect.

Question 3
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 4
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 5
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 6
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 7
(a) Both assertion and reason are correct and the reason is a correct explanation of the
assertion.

Question 8
(c) The assertion is correct but the reason is incorrect.

Page 10 of 28
Using Python Libraries
Question 1
A .py file containing constants/variables, classes, functions etc. related to a particular task and
can be used in other programs is called
1. module
2. library
3. classes
4. documentation

Question 2
The collection of modules and packages that together cater to a specific type of applications or
requirements, is called ...............
1. module
2. library
3. classes
4. documentation

Question 3
An independent triple quoted string given inside a module, containing documentation related
information is a ...............
1. Documentation string
2. docstring
3. dstring
4. stringdoc

Question 4
The help <module> statement displays ............... from a module.
1. constants
2. functions
3. classes
4. docstrings

Question 5
Which command(s) modifies the current namespace with the imported object name ?
1. import <module>
2. import <module1>, <module2>
3. from <module> import <object>
4. from <module> import *

Question 6
Which command(s) creates a separate namespace for each of the imported module ?
1. import <module>
2. import <module1>, <module2>
3. from <module> import <object>
4. from <module> import *

Question 7
Which of the following random module functions generates a floating point number ?
1. random()
2. randint()

Page 11 of 28
3. uniform()
4. all of these

Question 8
Which of the following random module functions generates an integer ?
1. random()
2. randint()
3. uniform()
4. all of these

Question 9
Which file must be a part of a folder to be used as a Python package ?
1. package.py
2. __init__.py
3. __package__.py
4. __module__.py

Question 10
A python module has ............... extension.
1. .mod
2. .imp
3. .py
4. .mpy

Question 11
Which of the following is not a function/method of the random module in Python ?
1. randfloat()
2. randint()
3. random()
4. randrange()

Fill in the Blanks

Question 1
The file __init__.py must be the part of the folder holding library files and other definitions
in order to be treated as an importable package.

Question 2
A library refers to a collection of modules that together cater to a specific type of needs or
applications.

Question 3
A Python module is a file (.py file) containing variables, class definitions, statements, and
functions related to a particular task.

Question 4
The uniform() function is part of the random module.

Question 5
The capwords() function is part of the string module.

Page 12 of 28
Question 1
A Python program and a Python module mean the same.
Answer: False

Question 2
A Python program and a Python module have the same .py file extension.
Answer: True

Question 3
The import <module> statement imports everything in the current namespace of the Python
program.
Answer: False

Question 4
Any folder having .py files is a Python package.
Answer: False

Question 5
A folder having .py files along with a special file i.e., __init__.py in it is an importable
Python package.
Answer: True

Question 6
The statement from <module> import <objects> is used to import a module in full.
Answer: False

Assertions and Reasons

Question 1
Assertion: The documentation for a Python module should be written in triple-quoted
strings.
Reason: The docstrings are triple-quoted strings in Python that are displayed as
documentation when help(<module>) command is issued.
Answer: (a) Both assertion and reason are correct, and the reason is a correct explanation of
the assertion.

Question 2
Assertion: After importing a module through import <module> statement, all its function
definitions, variables, constants, etc., are made available in the program.
Reason: Imported module's definitions do not become part of the program's namespace if
imported through an import <module> statement.
Answer: (c) The assertion is correct, but the reason is incorrect.

Question 3
Assertion: If an item is imported through from <module> import <item> statement, then
you do not use the module name along with the imported item.
Reason: The from <module> import command modifies the namespace of the program and
Page 13 of 28
adds the imported item to it.
Answer: (a) Both assertion and reason are correct, and the reason is a correct explanation of
the assertion.

Question 4
Assertion: Python's built-in functions, which are part of the standard Python library, can
directly be used without specifying their module name.
Reason: Python's standard library's built-in functions are made available by default in the
namespace of a program.
Answer: (a) Both assertion and reason are correct, and the reason is a correct explanation of
the assertion.

Question 5
Assertion: Python offers two statements to import items into the current program: import
<module> and from <module> import <item> , which work identically.
Reason: Both import <module> and from <module> import <item> bring the imported
items into the current program.
Answer: (b) Both assertion and reason are correct, but the reason is not a correct explanation
of the assertion.

Application based questions: -


1. What are the errors in following codes ? Correct the code and predict output :
total = 0;
def sum(arg1, arg2):
total = arg1 + arg2;
print("Total :", total)
return total;
sum(10, 20);
print("Total :", total)

Answer-
total = 0 # Global variable

def sum(arg1, arg2):


total = arg1 + arg2 # Local variable inside the function
print("Total :", total) # Prints local total
return total

sum(10, 20) # Function call


print("Total :", total) # Prints the global total

Error

1. There is an indentation error in second line.


2. The return statement should be indented inside function and it should not end with
semicolon.
3. Function call should not end with semicolon.

Page 14 of 28
2. What are the errors in following codes ? Correct the code and predict output :
def Tot(Number) #Method to find Total
Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])

Answer-
def Tot(Number): # Method to find Total
Sum = 0
for C in range(1, Number + 1):
Sum += C
return Sum

print(Tot(3)) # Function call


print(Tot(6)) # Function call

Error-

1. There should be a colon (:) at the end of the function definition line to indicate the
start of the function block.
2. Python's built- in function for generating sequences is range(), not Range().
3. Python keywords like return should be in lowercase.
4. When calling a function in python, the arguments passed to the function should be
enclosed inside parentheses () not square brackets [].

3. Find and write the output of the following python code :


def Call(P = 40, Q = 20):
P=P+Q
Q=P-Q
print(P, '@', Q)
return P
R = 200
S = 100
R = Call(R, S)
print(R, '@', S)
S = Call(S)
print(R, '@', S)

Answer-
300 @ 200
300 @ 100
120 @ 100
300 @ 120

Page 15 of 28
4. What will the following function return ?
def addEm(x, y, z):
print(x + y + z)
Answer-

ANSWER

The function addEm will return None. The provided function addEm takes three parameters x,
y, and z, calculates their sum, and then prints the result. However, it doesn't explicitly return
any value. In python, when a function doesn't have a return statement, it implicitly
returns None. Therefore, the function addEm will return None.

5. What will be the output of following program ?


num = 1
def myfunc():
num = 10
return num
print(num)
print(myfunc())
print(num)

1
10
1

6. What will be the output of following program ?


def display():
print("Hello", end='')
display()
print("there!")

ANSWER
Hellothere!

7. Predict the output of the following code :


a = 10
y=5
def myfunc():
y=a
a=2
print("y =", y, "a =", a)
print("a + y =", a + y)
return a + y

Page 16 of 28
print("y =", y, "a =", a)
print(myfunc())
print("y =", y, "a =", a)

ANSWER
y= 5 a= 10
y= 10 a= 2
a+y 12
12
y= 5 a= 10

8. Find and write the output of the following python code :


a = 10
def call():
global a
a = 15
b = 20
print(a)
call()

ANSWER
15

9. What will be the output of the following Python code ?


V = 25
def Fun(Ch):
V = 50
print(V, end = Ch)
V *= 2
print(V, end = Ch)
print(V, end = "*")
Fun("!")
print(V)
i. 25*50!100!25
ii. 50*100!100!100
iii. 25*50!100!100
iv. Error

ANSWER

25*50!100!25

Page 17 of 28
10. What will be the output of the following Python code?

def cube(x):
return x * x * x
x = cube(3)
print x
A. 9
B. 3
C. 27
D. 30

11. Which of the following items are present in the function header?
a) function name
b) parameter list
c) return value
d) Both A and B

12. Choose the correct answer:


def fun1(num):
return num + 5
print(fun1(5))
print(num)
a) Print value 10
b) Print value 5
c) Name Error
d) 25

14. Predict the output of the following code:


def func1(list1):
for x in list1:
print(x.lower(), end="#")
func1(["New", "Dehli"])
a) [New, Dehli]
b) new#dehli#
c) newdehli#
d) New#Dehli#

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


def mul(num1, num2):
x = num1 * num2
x = mul(20, 30)
a) 600
b) None
c) No Output
d) 0

Page 18 of 28
16. Which of the following function headers is correct?
a) def fun(x=1,y)
b) def fun(x=1,y,z=2)
c) def fun(x=1,y=1,z=2)
d) def fun(x=1,y=1,z=2,w)

17. What is the output of the program given below?


x = 50
def func(x):
x=2
func(x)
print('x is now', x)
a) x is now 50
b) x is now 2
c) x is now 100
d) Error

Answer-
x is now 50

18. Choose the correct output from the options given below.
print(‘Welcome!’)
print(‘Iam’, name ) # 'name' is undefined
a) Welcome!
b) Error
Iam main
c) Welcome!
d) None of these
Iam name

Welcome! NameError: name 'name' is not defined

19. Predict the output of the following code fragment:


def update(x=10):
x += 15
print("x=", x)

x = 20
update()
print("x=", x)
a) x=20
b) x=25 x=25 x=25
c) x=20
d) x=25 x=25 x=20

ANSWER

Output

Page 19 of 28
15
13 22

20. Predict the output of the following code fragment:


def display(x=2, y=3):
x=x+y
y += 2
print(x, y)

display()
display(5, 1)
display(9)

Answer -
55
63
12 5

21. Find the output of the following code:


print(pow(5, 4, 9))

22. Give the output of the following program:


def check(a):
for i in range(len(a)):
a[i] = a[i] + 5
return a

b = [1, 2, 3, 4]
c = check(b)
print(c)

Answer-

[6, 7, 8, 9]

23. Predict the output of the following code:


def abc(x, y=60):
return x + y

a = 20
b = 30
a = abc(a, b)
print(a, b)
b = abc(a)
print(a, b)
a = abc(b)
print(a, b)

Page 20 of 28
Anwer-

ANSWER
50 30

24. Predict the output of the following code snippet:


def Execute(M):
if M % 3 == 0:
return M * 3
else:
return M + 10

def Output(B=2):
for T in range(0, B):
print(Execute(T), "*", end="")
print()

Output(4)
Output()
Output(3)

Answer-
22# 40# 9# 13#

25. Find the output of the following program:


def ChangeIt(Text, C):
T = ""
for K in range(len(Text)):
if 'F' <= Text[K] <= 'L':
T = T + Text[K].lower()
elif Text[K] == 'E' or Text[K] == 'e':
T=T+C
elif K % 2 == 0:
T = T + Text[K].upper()
else:
T = T + T[K-1]
print(T)

OldText = "pOwERALone"
ChangeIt(OldText, "%")

Ans: c) PPW%RRllN%

26. Find the output of the following code:


def disp(str):
m=''
for i in range(len(str)):
if str[i].isupper():

Page 21 of 28
m = m + str[i].lower()
elif str[i].islower():
m = m + str[i].upper()
else:
if i % 2 == 0:
m = m + str[i - 1]
else:
m = m + "@"
print(m.swapcase())

disp('StudyBag$2021')

Answer-
StudyBagG$2$2

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


total = 0 # Global variable
def add(a, b):
global total
total = a + b
print(total)

add(6, 6)
print(total)

Answer-
12

28. Find and write the output of the following Python code:
def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count % 2 == 0:
newstr = newstr + i.lower()
else:
if i.islower():
newstr = newstr + i.upper()
else:
newstr = newstr + i
count += 1
newstr = newstr + mystr[:3]
print("The new string is:", newstr)

makenew("cbseEXAMs@2022")

Answer-
cBsEeXaMs@2022cbs

29. Choose the correct option:


Statement 1: Local Variables are accessible only within a function or block in which it is
Page 22 of 28
declared.
Statement 2: Global variables are accessible in the whole program.
a) Statement 1 is correct but Statement 2 is incorrect
b) Statement 2 is correct but Statement 1 is incorrect
c) Both Statements are Correct
d) Both Statements are incorrect

30. Consider the following code and choose the correct answer:
def nameage(name, age):
return [age, name]

t = nameage('kishan', 20)
print(type(t))

a) tuple b) list c) (kishan,20) d) None of all

31. Write the output of the following:


a = (10, 12, 13, 12, 13, 14, 15)
print(max(a) + min(a) + a.count(2))

a) 13 b) 25 c) 26 d) Error

32. Consider the code given below and identify how many times the message "Hello" is
printed:
def prog(name):
for x in name:
if x.isalpha():
print('Alphabet')
elif x.isdigit():
print('Digit')
elif x.isupper():
print('Capital Letter')
else:
print('Hello All')

prog('vishal123@gmail.com')
a) 0 b) 2 c) d) 3

33. def fun(s):


k = len(s)
m=""
for i in range(0, k):
if s[i].isupper():
m = m + s[i].lower()
elif s[i].isalpha():
m = m + s[i].upper()
else:
m = m + 'bb'

Page 23 of 28
print(m)

fun('school2@com')

Answer

SCHOOLbbbbCOM

34.
def Change(P, Q=30):
P=P+Q
Q=P-Q
print(P, "#", Q)
return P

R = 150
S = 100
R = Change(R, S)
print(R, "#", S)
S = Change(S)

Answer

250 # 150 250 # 100 130 # 100

35.

def Diff(N1, N2):


if N1 > N2:
return N1 - N2
else:
return N2 - N1

NUM = [10, 23, 14, 54, 32]

for CNT in range(4, 0, -1):


A = NUM[CNT]
B = NUM[CNT-1]
print(Diff(A, B), '#', end=' ')

Answer
22 # 40 # 9 # 13 #

36.
def check(n1=1, n2=2):
n1 = n1 + n2
n2 += 1
print(n1, n2)

check() # Call 1
check(2, 1) # Call 2
check(3) # Call 3

Page 24 of 28
Answer-
333253

37.
def check():
global num # Declaring 'num' as a global variable
num = 1000
print(num)
num = 100
print(num)

check()
print(num)

Answer-
1000 100 100

38.
def Total(Number=10):
Sum = 0
for C in range(1, Number + 1):
if C % 2 == 0:
continue
Sum += C
return Sum

print(Total(4))
print(Total(7))
print(Total())

Answer
4 16 25

39.
X = 100 # Global variable

def Change(P=10, Q=25):


global X # Declaring X as global
if P % 6 == 0:
X += 100
else:
X += 50
Sum = P + Q + X
print(P, '#', Q, '$', Sum)

Change()
Change(18, 50)
Change(30, 100)

Answer-
10 # 25 $ 185
18 # 50 $ 318
30 # 100 $ 480

Page 25 of 28
39.
def Updater(A, B=5):
A = A // B
B=A%B
print(A, '$', B)
return A + B

A = 100
B = 30

A = Updater(A, B)
print(A, '#', B)

B = Updater(B)
print(A, '#', B)

A = Updater(A)
print(A, '$', B)

Answer-
3$3
6 # 30
6$1
6#7
1$1
2$7

40.
def Fun1(num1):
num1 *= 2
num1 = Fun2(num1)
return num1

def Fun2(num1):
num1 = num1 // 2
return num1

n = 120
n = Fun1(n)
print(n)

Answer-
120

41.
def Fun1(mylist):
for i in range(len(mylist)):
if mylist[i] % 2 == 0:
mylist[i] /= 2 # Halve even numbers
else:
mylist[i] *= 2 # Double odd numbers

list1 = [21, 20, 6, 7, 9, 18, 100, 50, 13]


Fun1(list1)
print(list1)

Page 26 of 28
Answer-
[42, 10.0, 3.0, 14, 18, 9.0, 50.0, 25.0, 26]

42.
b = 100 # Global variable

def test(a):
global b # Declare b as global to modify it inside the function
b =b+ a
print(a, b)

test(10)
print(b)

Answer-
10 110
110

43.
def ChangeList():
L = [] # List L
L1 = [] # List L1
L2 = [] # List L2

for i in range(1, 10):


L.append(i)

for i in range(10, 1, -2):


L1.append(i)

for i in range(len(L1)):
L1.append(L1[i] + L[i])

L2.append(len(L) - len(L1))

print(L2)

ChangeList()

Answer- [-1]

44..
def Fun1(mylist):
for i in range(len(mylist)):
if mylist[i] % 2 == 0:
mylist[i] /= 2 # Divide even numbers by 2
else:
mylist[i] *= 2 # Multiply odd numbers by 2

list1 = [21, 20, 6, 7, 9, 18, 100, 50, 13]


Fun1(list1)
print(list1)
Answer- [42, 10.0, 3.0, 14, 18, 9.0, 50.0, 25.0, 26]

Page 27 of 28

You might also like