0% found this document useful (0 votes)
1 views38 pages

Functions

The document provides an overview of functions in Python, including how to define and call them, the use of arguments and parameters, and the importance of the return keyword. It explains variable scope, the global keyword, and the differences between mutable and immutable types when passing arguments. Additionally, it covers various types of arguments, name resolution rules, and includes a worksheet with questions to test understanding of the concepts discussed.

Uploaded by

Jhishnu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views38 pages

Functions

The document provides an overview of functions in Python, including how to define and call them, the use of arguments and parameters, and the importance of the return keyword. It explains variable scope, the global keyword, and the differences between mutable and immutable types when passing arguments. Additionally, it covers various types of arguments, name resolution rules, and includes a worksheet with questions to test understanding of the concepts discussed.

Uploaded by

Jhishnu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Function

Reusable block of code that performs a specific task. For example: len(),
print(), min(), max(), sorted () , type() etc.
Types of Functions

Defining a function in Python:

Name the function and specify what to do when the function is called. Python
interpreter ignores the function definition until the function is called.
Calling a function:
Calling the function using the function name performs the specified actions
with the indicated parameters
Function Definition in Python
In Python, a function is defined using the def keyword
● Arguments: Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma. Eg: add(a,b,c)
● Parameters: Parameters are variables specified in function definitions
to receive values from arguments passed during function calls.
Eg: def add(e,f,g) :

• Formal Arguments and Actual Arguments

• Formal parameters and Actual parameters

Arguments are called as Actual arguments or Actual Parameters

Parameters are called as Formal Parameters or Formal Arguments


return keyword:

In Python, the `return` keyword is used in functions to specify the


value that the function will return when it is called. When a function is
executed, it may perform some computations or operations, and the
result can be sent back to the caller using the `return` statement.
The basic syntax for using the `return` statement is as follows:

Here's what you need to know about the `return` statement:


1. Returning a Value: (Non-void / Fruitful functions)
When you want to return a specific value from the function, you can
use the `return` statement followed by the value you want to return.
Note: The function will stop executing immediately after the
`return` statement is encountered, and the value will be passed back
to the caller.

A Function that returns a value is called Non void function

2. Returning Multiple Values:


Python allows you to return multiple values from a function as a
tuple. You can simply separate the values with commas after the
`return` statement. The multiple values are returned as tuple and it
can be unpacked in the main function with equal no. of individual
variables.
3. Returning None: (Void / non-fruitful functions)
If a function doesn't have a `return` statement or has a `return`
statement without any value, it implicitly returns `None`. A function
that does not return a value is called Void function.

`None` is a special constant in Python that represents the absence of a value.

4. Early Exit with Return:


You can use the `return` statement to exit a function early if certain
conditions are met. This is useful when you want to terminate the function
before reaching the end.
Scope of a variable:

In Python, the scope of a variable refers to the region of the program where
the variable is accessible. The scope determines where a variable is
created, modified, and used.
Global Scope:

● Variables defined outside of any function or block have a global scope.


● They are accessible from anywhere in the code, including inside
functions.

Local Scope:

● Variables defined inside a function have a local scope.


● They are accessible only within the function where they are defined.

Local variables are created when the function is called and destroyed when
the function returns.
Points to be noted:

● When the local variable and global variable have different names: the
global variable can be accessed inside the function

● When local and global variables have the same name: priority is given
to the local copy of the variable

• When a global variable is just printed or assigned to another variable or


used in a calculation inside a function, it doesn’t produce error. Only
when a global variable is modified, it produces error. However, if the
same variable is modified (assigned a new value) anywhere inside the
function, Python treats it as a local variable throughout that function.
As a result, if the variable is accessed before its local assignment, it
leads to an UnboundLocalError.
global keyword
In Python, the global keyword is used to indicate that a variable
declared inside a function should be treated as a global variable, rather
than a local variable. When you assign a value to a variable inside a
function, Python, by default, creates a local variable within that
function's scope. However, if you need to modify a global variable
within a function, you must use the global keyword to specify that you
want to work with the global variable instead.

Here's the basic syntax for using the global keyword: For example:

The lifetime of a variable:


The lifetime of a variable in Python depends on its scope. Global
variables persist throughout the program's execution, whereas, local
variables within functions exist only during the function's execution.
Study the following programs:

Example 1:
Example 2

Example 3

Example 4
Passing list as an argument to the function:

Please note that when a list is passed as an argument, the original copy
of the list is passed to the function i.e. if any change is made at any
index in the list inside the function, it is reflected in the original list.
That is because a list is a mutable datatype and in Python, when you
pass a list as an argument to a function, you are actually passing a
reference to the list rather than a copy of the list. This means that the
function parameter will point to the same memory location as the
original list. As a result, any changes made to the list within the function
will be reflected in the original list outside the function.

However, if you assign a different list to a variable inside a function in


Python, it will create a new local variable that is separate from any
variables outside the function. This local variable will only exist within
the scope of the function, and changes made to it won't affect the
original list outside the function.
Types of arguments passed to a function:

Positional Arguments:(required arguments)


● These are the most common types of arguments and are matched to
the function parameters based on their positions. The first argument
corresponds to the first parameter, the second argument corresponds
to the second parameter, and so on.
● The number and order of positional arguments must match the function's
parameter list.

Default Arguments:
● Default arguments are used when a function is called with fewer
arguments than there are parameters.
● The default values are specified in the function definition.

● If a value is not provided for a parameter during the function call, the
default value is used.
● Default parameters are always specified at the end in the function
definition.

Keyword Arguments:(named arguments)


● In this type, each argument is preceded by a keyword followed by
an equal sign.
● The order of keyword arguments does not matter, as they are
matched to the function parameters based on their names.
● These arguments provide flexibility to call a function with arguments
passed in any order.

● Positional arguments must always come before any keyword arguments

Name Resolution(LEGB Rule)


For every name reference within a program, when you access a variable
from within a program or function, python follows name resolution rule.

L- local environment /local namespace

E – enclosing environment (Function defined inside a function)

G – global environment

B- built in environment

If you want to use a value of already created global variable inside a local function
without modifying it, then simply use it.

But if you want to assign some value to the global variable without creating any
local variable, then use global keyword

Once an indentifier is declared global , it cant be reverted to local namespace.

Changes in immutable types are not reflected in the caller function.

Changes if any in mutable types are reflected in caller function if the name is not
assigned to a different variable or datatype.
The primary difference is that list concatenation creates an entirely new list object by
combining two sequences, while the append() method modifies the existing list in-place by
adding a single element to its end.

The core difference is that the + operator creates a brand-new list object in memory, while
the += operator modifies the existing list in-place

Default argument values are evaluated only once, when the function is defined, not each
time it is called.
FUNCTIONS – WORKSHEET – 1
1. What is the default value of a function that does not return any value.
a) None b) int c)double d) null
2. Which of the following items are present in the function header?
a) Function name only b) parameter List
c) Both function name and parameter list only d) Return value.
3. Which of the following keyword marks the beginning of the function block.
a) func b) define c) def d) function
4. Pick one of the following statements to correctly complete the function body in the given snippet:
def f (number):
#missing function body
print(f(5))
a) return “number” b) print(number) c) print(“number”) d) return number
5. Which of the following function header is correct.

a) def f (a=1,b): b) def f (a=1,b,c=1):


c) def f (a=1,b=1,c=2): d) def f( a=1,b=1,c,d=2):
6. Which of the following statement is not true for parameter passing to function?
a) You can pass positional arguments in any order.
b) You can pass keyword arguments in any order.
c) You can call a function with positional and keyword arguments.
d) Positional arguments must be before keyword argument in a function call.
7. Which of the following function header is correct?
a) def cal_si(p=100,r,t=2) c) def cal_si(p=100,r=8,t)
b) def cal_si(p,r=8,t) d) def cal_si(p,r=8,t=2)
8. Which of the following is a correct way to call the function.
a) my_fun() b) def my_fun() c) return my_fun() d) call my_fun
9. Which of the given argument types can be skipped from the function call.
a) Positional arguments. c) keyword arguments
b) Default arguments d) variable arguments
10. For a Function header as follows: def Calc(X,Y=20):
Which of the following function calls will give an Error?
a) Calc(15,25) c) Calc(X=15,Y=25)
b) Calc(Y=25) d) Calc(X=25)
11. Which of the following is not correct in context of scope of variable.
a) Global keyword is used to change value of a global variable in a local scope
b) Local keyword is used to change value of a local variable in global variable.
c) Global variable can be accessed without using global keyword in a local scope.
d) Local variable can not be used outside its scope.
12. What is the difference between a parameter and an argument?
a) Parameters are input passed to the function,while arguments are variable defined inside the
function.
b) Parameters are variables defined inside the function, while arguments are input passed to the
function.
c) Parameters and arguments are the same thing.
d) None of above
13. What is the Difference between positional parameters and keyword parameters?
a) Positional parameters are specified by their position in the function call ,while keyword parameters
are specified by their name.
b) Positional parameters are specified by their name in the function call, While keywords parameters
are specified by their position.
c) Positional parameters and keyword parameters are the same thing.
d) None of the above.
14. Which of the following is not correct in context of scope of a variable?
a) Global keyword is used to change value of a global variable in local variable.
b) Local keyword is used to change value of a local variable in a global scope.
c) Global variable can be accessed without using the global keyword in a local scope.
d) Local variables can not be used outside its scope.
15. Which of the following is not correct in context of Positional and Default parameters in python
functions?
a) Default parameters must occur to the right of Positional parameters.
b) Positional parameters must occur to the right of Default parameters.
c) Positional parameters must occur to the left of Default parameters.
d) All parameters to the right of a Default parameters must also have Default values.
16. Assertion (A): Default parameters are used in Python functions to specify values for arguments
that are not explicitly passed by the caller.
Reason (R): This allows the function to have a default behaviour when the caller does not provide
a value for an argument.
17. Assertion: Every function returns a value. if the function does not explicitly return a value, then it will
return ‘None’.
Reason: Zero is equivalent to None.
18. Assertion(A): Positional arguments in python function must be passed in the exact order in which they
are defined in the function signature.
Reason: This is because Python Function automatically assign default values to positional argument.
19. Assertion(A): For changes made to a variable defined with in the function to be visible outside the
function, it should be declared as global.
Reason: Variable defined with in the function a function is local to that function by default, unless
explicitly specified with the global variable.
20. Assertion: A function can’t return multiple values in Python.
Reason: Python functions can return values as a list.
21. The variable defined inside the function definition is called as _______

22. If a function is returning multiple values, by default it returns in the form of ________

23. The parameter used in the function call statement are called _________ or ____________

24. The parameters used in the function Header are called________________ or ___________

25. _______are the named arguments with associated values being passed in the function call statement.
FUNCTIONS – WORKSHEET – 2 change()

Question 1 x=10

x=5 print(x,y,sep="*")

def multiply(): Question 6:

global x v=25

x=x*2 def fun(ch):

print(x,end=”@”) v=50

multiply() print(v,end=ch)

x=10 print(v,end="*")

print(x,end=”!”) fun("!")

Question 2: print(v)

p=1 Question 7:

q=6 def call(P=40,Q=20):

def change(): P=P+Q

global p Q=P-Q

q=5 print(P,”@”,Q)

p=p+q return P

return p R=200

change() S=100

print(p,q) print(R,”@”,S)

Question 3: S=call(S)

x=25 print(R,”@”,S)

def change(): Question 8;

x=10 def change(P,Q=30):

x=x+5 P=P+Q

print(x) Q=P-Q

print(x) print(P,”#”,Q)

change() return P

Question 4: R=150

x=25 S=100

def change(): R=change(R,S)

x=x+5 print(R,”#”,S)

print(x) S=change(S)

print(x) Question 9:

change() def outer():

Question 5: x="Hello"

x=25 def inner():


def change(): x="World"

y=x inner()

print(x,y,end="-") return x

y=10 print(outer())
Question 9: return(ch)
def makenew(mystr): Question 12:
newstr="" def fun(str1):
count=0 n=len(str1)
for i in mystr: str2=''
if count%2!=0: for i in range(0,n):
newstr=newstr+str(count) if str1[i]>="A" and str1[i]<="M":
else: str2=str2+str1[i+1]
if [Link](): elif str1[i]>="0" and str1[i]<="9":
newstr=newstr+[Link]() str2=str2+str1[i-1]
else: else:
newstr=newstr+i str2=str2+"*"
count+=1 print(str2)
newstr=newstr+mystr[:1] fun("EXAM2025")
print(newstr) Question 13:
makenew("sTUdeNT") def change(P,Q=30):
Question 10: P=P+Q
def makenew(mystr): Q=P-Q
newstr="" print(P,"#",Q)
count=0 return(P)
for i in mystr: R=150
if count%2!=0: S=100
newstr=newstr+str(count) R=change(R,S)
else: print(R,"#",S)
if [Link](): S=change(S)
newstr=newstr+[Link]() print(R,"#",S)
else: S=change(R)
newstr=newstr+i print(R,"#",S)
count+=1 Question 14:
print(newstr) The code provided below is intended to remove
the first and last characters of a given string and
makenew("No@1") return the resulting string. However, there are
Question 11: The function given below is written syntax and logical errors in the code. Rewrite it
to accept a string s as a parameter and return the after removing all the errors. Also, underline all
number of vowels appearing in the string. The the corrections made.
code has certain errors. Observe the code define remove_first_last(str):
carefully and rewrite it after removing all the if len(str) < 2:
logical and syntax errors. Underline all the return str
corrections made. new_str = str[1:-2]
Def CountVowels(s): return new_str
result = remove_first_last("Hello")
C=0
Print("Resulting string: " result)
for ch in range(s):
if ‘aeiouAEIOU’ in ch:
c+=1
FUNCTIONS – WORKSHEET – 3
1. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The
function returns another list named ‘indexList’ that stores the indices of all Non - Zero Elements of L.

For example: If L contains [12,4,0,11,0,56]

The indexList will have :[0,1,3,5]

2. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as argument to
the function. The function returns another list named ‘indexList’ that stores the indices of all four
lettered word of L. For example :If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
3. Write a function modilst(L) that accepts a list of numbers as argument and increases the value of the
elements by 10 if the elements are divisible by [Link] write a proper call statement for the function.
For example:If list L contains [3,5,10,12,15]

4. Write a function countNow (DAYS) in Python, that takes the dictionary, DAYS as an argument and
displays the names (in lowercase) of the days whose names are longer than 7 characters. For
example, Consider the following dictionary
DAYS={1:"MONDAY",2:"TUESDAY",3:"WEDNESDAY",4:"THURSDAY",5:"FRIDAY",6:” ,
“SATURDAY”,7:”SUNDAY”}
5. The code provided below is intended to swap the first and last elements of a given tuple. However,
there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the
corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
return new_tup
result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)

6. The code provided below is intended to input a positive integer from the user and display the total
number of its factors. However, there are syntax and logical errors in the code. Rewrite the code
after removing all the errors. Underline all the corrections made.
n=int(input("Enter a positive integer:")
c=0
for i in range(n+1):
if n%i=0:
c+=1
print(c)
7. The code given below accepts N as an integer argument and returns the sum of all integers from 1 to
N. Observe the following code carefully and rewrite it after removing all syntax and logical errors.
Underline all the corrections made.
def Sum(N)
for I in range(N):
S=S+I
return S
print(Sum(10)
8. Write a Python function update_score() that accepts a dictionary named scores, a player name and a
new score. If the player name already present in dictionary, update the score, otherwise, display the
message "Player not found".
9. Write a function remove_duplicates() in Python that accepts a list L and returns a new list containing
only the unique elements from L, after removing the duplicates.
10. The code provided below is intended to swap the first and last elements of a given tuple. However,
there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the
corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
return new_tup
result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)

11. The code provided below is intended to input a positive integer from the user and display the total
number of its factors. However, there are syntax and logical errors in the code. Rewrite the code
after removing all the errors. Underline all the corrections made.
n=int(input("Enter a positive integer:")
c=0
for i in range(n+1):
if n%i=0:
c+=1
print(c)
12. Write a user defined function in Python named showGrades(S) which takes the dictionary S as an
argument. The dictionary, S contains Name:[Eng,Math,Science] as key:value pairs. The function
displays the corresponding grade obtained by the students according to the following grade rules.
Average of Eng,Math,Science Grade
>=90 A
<90 but >=60 B
<60 C
For example : Consider the following dictionary
S={“AMIT”:[92,86,64], “NAGMA”:[65,42,43], “DAVID”:[92,90,88]}
The output should be :
AMIT – B
NAGMA – C
DAVID – A
13. Write a user defined function in python named Puzzle(W,N) which take the argument W as an English
word and N as an integer and returns the string where every Nth alphabet of the word W is replaced
with an underscore(“_”)
For example: if W contains the word “TELEVISION” and N is 3, then the function should return the
string “TE_EV_SI_N”. Likewise for the word “TELEVISION”, IF n IS 4, then the function should return
“TEL_VIS_ON”.
FUNCTIONS – OUTPUT BASED QUESTIONS

1. def Findoutput():
L = "First PreBoard"
X = ""
count = 1
for i in L:
if i in ['a', 'e', 'i', 'o', 'u']:
X = X + [Link]()
else:
if count % 2 != 0:
X = X + str(len(L[:count]))
else:
X = X + i
count = count + 1
print(X)
Findoutput()

2. tup = ('cold',)
n = 4
for i in range(int(n)):
if i % 2 == 0:
tup = (tup,'cold')
else:
if i > 1:
continue
tup = (tup , 'hot')
print(tup)
3. s = "welcome2kv"
n = len(s)
m = ""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m + s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m + s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '#'
print(m)

4. What are the possible outputs ?


import random
AR=[20,30,40,50,60,70] (i) 10#40#70#
FROM=[Link](1,3) (ii) 30#40#50#
TO=[Link](2,4) (iii) 50#60#70#
for K in range(FROM,TO): (iv) 40#50#70#
print (AR[K],end=”#“)

5. def ChangeVal(M, N): def Call(P=40, Q=20):


for i in range(N): P = P + Q
if M[i] % 5 == 0: Q = P - Q
M[i] //= 5 print(P, ‘@’, Q)
if M[i] % 3 == 0: return P
M[i] //= 3 R=200
L = [25, 8, 75, 12] S=100
ChangeVal(L, 4) R=Call(R,S)
for i in L: print(R,’@’,S)
print(i, end="#") S = Call(S)
print(R, '@', S)
6. What are the possible outputs ?
import random
Colours = ["VIOLET", "INDIGO", "BLUE", "GREEN", "YELLOW",
"ORANGE", "RED"]
End = [Link](2) + 3
Begin = [Link](End) + 1
for i in range(Begin, End):
print(Colours[i], end="&")

i) INDIGO&BLUE&GREEN& ii) VIOLET&INDIGO&BLUE&


iii) BLUE&GREEN&YELLOW& iv) GREEN&YELLOW&ORANGE&

7. i) def Update(X=10): ii) def update (x=10):


X += 15 global x
print('X = ', X) x+=15
X = 20 print ( x )
Update() x=20
print('X = ', X) update()
print(x)

8. def display(s):
l = len(s)
m = ""
for i in range(0, l):
if s[i].isupper():
m = m + s[i].lower()
elif s[i].isalpha():
m = m + s[i].upper()
elif s[i].isdigit():
m = m + "$"
else:
m = m + "*"
print(m)
display("EXAM2026@[Link]")
9. def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count % 2 != 0:
newstr = newstr + str(count)
else:
if [Link]():
newstr = newstr + [Link]()
else:
newstr = newstr + i
count += 1
newstr = newstr + mystr[:1]
print("The new string is :", newstr)
makenew("WeLlFArE")

10. data=["L",20,"M",40,"N",60] L=[1,2,3,4,5]


times,add=0,0 Lst=[]
alpha="" for i in range(len(L)):
for c in range(1,6,2): if i%2==1:
times = times + c t=(L[i],L[i]**2)
alpha = alpha + data[c-1] + "@" [Link](t)
add = add + data[c] print(Lst)
print(times, add, alpha)

11. data=["L",20,"M",40,"N",60]
Times,add=0,0
alpha=""
for c in range(1,6,2):
times = times + c
alpha = alpha + data[c-1] + "@"
add = add + data[c]
print(times, add, alpha)
12. d1={'rno':25, 'name':'dipanshu'}
d2={'name':'himanshu', 'age':30, 'dept':'mechanical'}
[Link](d1)
print([Link]())
print(len(list([Link]())))
13. def foo(s1, s2): def SW (a, b):
l1 = [] if a > b:
l2 = [] print("changed",end="")
for x in s1: return b , a
[Link](x) else:
for x in s2: print("Not",end="")
[Link](x) return a , b
return l1, l2 L = [11, 22, 16, 50, 30]
a, b = foo("FUN", "DAY") for i in range(4, 0, -1):
print(a, b) print(SW(L[i], L[i-1]))
14. data = [2,4,2,1,2,1,3,3,4,4]
d = {}
for x in data:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
print(d)
15. i. def change(m, n=10): ii) a = -30
global x def call(x):
x += m global a
n += x if a % 2 ==0:
m = n + x x+=a
print(m, n, x) else:
x = 20 x-=a
change(10) return x
change(20) x=20
print(call(35), end="#")
print(call(40), end="@")
16. str = "" What are the possible outputs ?
name = "9@Days" import random
for x in name: M=[5,10,15,20,25,30]
if x in "aeiou": for I in range(1,3):
str += [Link]() F=[Link](2,5)-1
elif not [Link](): S=[Link](3,6)-2
str += "**" T=[Link](1,4)
elif [Link](): print(M[F],M[S],M[T],sep="#")
pass i) 10#25#15 ii) 5#25#25
else: 20#25#25 25#20#15
str += [Link]() iii) 30#20#20 iv) 10#15#25
print(str) 20#25+25 15#20#10#

17. What are the possible outputs ?


import random i) 66#44#55#
A=[11,22,33,44,55,66]; ii) 33#44#55#
Lower =[Link](1,3) iii) 11#22#33#44#55#
Upper =[Link](2,4) (iv) 33#44#55#11
for P in range(Lower, Upper +1):
print (A[P],end='#')

18. def Change(P ,Q=30): x=["rahul",5, "B",20,30]


P=P+Q [Link](1,3)
Q=P-Q [Link](3, "akon")
print( P,"#",Q) print(x[2])
return (P)
R = 150
S = 100
R = Change(R,S)
print(R,"#",S)
S = Change(S)
19. st = "python programming" x = ["A",40,"B",60,"C",20]
count = 4 a,b,c=0,0,0
while True: for I in range(1,6,2):
if st[0] == "p": a+=I
st = st[2:] b+=x[I-1]+’#’
elif st[-2] == "n": c+=x[I]
st = st[:4] print(a,b,c)
else:
count += 1
break
print(st)
print(count)

20. L=[4,6,7,1,6,9,4] T = (9,18,27,36,45,54)


def fun(L): L=list(T)
for i in range(len(L)): L1=[ ]
if(L[i]%3==0 and L[i]%2==0): for I in L:
L[i]=L[i]+1 if I%6==0:
print(L) [Link](I)
return(L) T1=tuple(L1)
print(L) print(T1)
k=fun(L)
print(k)

21. def checkNumber(N):


status = N % 2
return status
num = int(input("Enter a number to check: "))
k = checkNumber(num)
if k == 0:
print("This is EVEN number")
else:
print("This is ODD number")
22. value = 50 a=20
def display(N): def call():
global value global a
value = 25 b=20
if N%7==0: a=a+b
value = value + N return a
else: print(a)
value = value – N call()
print(value, end="#") print(a)
display(20)
print(value)

23. Text1 = "IND-23"


Text2 = ""
I = 0
while I < len(Text1):
if Text1[I] >= "0" and Text1[I] <= "9":
Val = int(Text1[I])
Val = Val + 1
Text2 = Text2 + str(Val)
elif Text1[I] >= "A" and Text1[I] <= "Z":
Text2 = Text2 + Text1[I+1]
else:
Text2 = Text2 + "*"
I += 1
print(Text2)

24. text = 'ABCD'


number = '1357'
i = 0
s =''
while i < len(text):
s = s + text[i] + number[len(number)-i-1]
i = i + 1
print(s)
25. If n is 9 and then 7, What will be the results of the program
def prime():
n = int(input("Enter number to check :: "))
for i in range(2, n//2 + 1):
if n % i == 0:
print("Number is not prime")
break
else:
print("Number is prime")
prime()

26. def Diff(N1,N2): def fact(N):


if N1>N2: fact=1
return N1-N2 while N>0:
else: fact=fact*N
return N2-N1 N=N-1
num=[10,23,14,54,32] print(“F=”,fact)
for cnt in range(4,0,-1): fact(7)
a=num[cnt]
b=num[cnt-1]
print(Diff(a,b),'#',end='')

27. def modify(L): def Funstr(S):


for C in range(len(L)): T=’’
if C%2==1: for I in S:
L[C]*=2 if [Link]():
else: T= T + I
L[C]//=2 return T
N=[5,13,47,9] A=”Computer-083”
modify(N) B=Funstr(A)
print(N) print(A,'\n',B, sep="#")
28. def ListChange(L): def display(S):
for i in range(len(L)): m=’’
if L[i]%2==0: for I in range(0,len(S)):
L[i]=L[i]*2 if(S[I].isupper()):
if L[i]%3==0: m=m+’*’
L[i]=L[i]*3 elif S[I].islower():
if L[i]%5==0: m=m+’%’
L[i]=L[i]*5 else:
L=[3,4,5,9] if I%2==0:
ListChange(L) m=m+S[i-1]
for i in L: else:
print(i, end="$") m=m+’#’
print(m)
display('Fun@Python3.0')
29. What will be the possible outputs :
import random
NAV=[“LEFT”,”FRONT”,”RIGHT”,”BACK”] i. BACKRIGHT
NUM=[Link](1,3) ii. BACKRIGHTFRONT
NAVG=”” iii. BACK
for C in (NUM,1,-1): iv. LEFTFRONTRIGHT
NAVG=NAVG+NAV[C]
print(NAVG)
30. def fun(a,b): s=’Rs.12’
global x,y n,m=len(s), ‘ ‘
x=a+b for I in range(0,n):
a,y=a+x,a*x if s[i].islower():
print(a,b,x,y) m=m+s[i]
fun(5,10) elif s[i].isupper():
print(fun(b=x,a=y)) m = m +s[i+1]
elif s[i].isdigit():
m = m*int(s[i])
else:
m = '@'+m
print(m)
31. If Y is 8 and then Y is 12, What will be the outputs ?
Y = int(input("Enter 1 or 10: "))
if Y == 10:
for Y in range(1, 11):
print(Y)
else:
for m in range(5, 0, -1):
print("thank you")

32. What are the possible outputs for (a) and (b) ?
a) import random
AR = ["MON", "TUE", "WED", "THU", "FRI", "SAT"]
X = [Link](0, 4)
for I in range(1, X+1):
print(AR[I] + "#", end="")

(i) TUE#WED#THU#FRI# (ii) MON#TUE#WED#THU#


(ii) TUE#WED#THU#FRI#SAT# (iv) TUE#WED#

b) import random (i) NX*UA*FM*


TEXT = "EXAMAREFUN" (ii) UM* FA* ER*
COUNT = [Link](0,3) (iii) NA*UM*FA*
C = 9 (iv) EN* XU* AF*
while TEXT[C] != 'E':
print(TEXT[C] + TEXT[COUNT] + '*', end=" ")
COUNT = COUNT + 1
C = C – 1

33. Number = 250 p = 30


while Number <= 1000: for I in range(0,p):
if Number >= 750: if I%4==0:
print(Number) print(I*4)
Number = Number + 10 elif I%5==0:
else: print(c + 3)
print(Number * 2) else:
Number = Number + 50 print(c + 10)
34. def Convert(Old):
l = len(Old)
New = ""
for i in range(0, l):
if Old[i].isupper():
New = New + Old[i].lower()
elif Old[i].islower():
New = New + Old[i].upper()
elif Old[i].isdigit():
New = New + "*"
else:
New = New + "%"
return New
Older = "InDIa@2020"
Newer = Convert(Older)
print("New string is : ", Newer)

35. What are the possible outputs?


import random (i) 10#40#70#
AR=[20,30,40,50,60,70] (ii) 30#40#50#
Lower =[Link](1,4) (iii) 50#60#70#
Upper =[Link](2,5) (iv) 40#50#70#
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)

36. count = 0
while(True):
if count % 3 == 0:
print(count, end = " ")
if(count > 15):
break;
count += 1
37. def encrypt(s):
k = len(s)
m = ""
for i in range(0, k):
if s[i].isupper():
m = m + str(i)
elif s[i].islower():
m = m + s[i].upper()
else:
m = m + '*'
print(m)
encrypt(“MouNT@TowN”)
38. 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].islower():
m = m + s[i].upper()
elif s[i].isdigit():
m = m + "O"
else:
m = m + '#'
print(m)
fun('CBSE@12@Exam')
39. L1 = [100, 900, 300, 400, 500] p,q=8,[8]
START , SUM = 1 , 0 def sum(r, s=5):
for C in range(START, 4): p = r + s
SUM = SUM + L1[C] q = [r, s]
print(C, ":", SUM) print(p, q, sep='@')
SUM = SUM + L1[0] * 10 sum(3, 4)
print(SUM) print(p, q, sep='@')
40. def replaceV(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = "Hello how are you"
st1 = replaceV(st)
print("The original String is:", st)
print("The modified String is:", st1)

41. def Findoutput():


L = "PreBoard Examination"
X = ""
I1 = []
count = 1
for i in L:
if i in ['a', 'e', 'i', 'o', 'u']:
X = X + [Link]()
else:
if count % 2 != 0:
X = X + str(len(L[:count]))
else:
X = X + i
count = count + 1
print(X)
Findoutput()
42. def Show(str):
m = ""
for i in range(0, len(str)):
if str[i].isupper():
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)
Show("GoOdLUcK")

43. T = ["20", "50", "30", "40"] def Alpha(N):


Counter = 3 while N:
Total = 0 a=[Link]()
for I in [7, 5, 4, 6]: if a%5>2:
newT = T[Counter] print(a)
Total = float(newT) + I else:
print(Total) break
Counter = Counter – 1 NN=[13,24,12,53,34,42,50]

44. T1 = tuple("Amsterdam") Alpha(NN)


T2, new_list = T1[1:-1], [] print(NN)
for i in T2:
if i in 'aeiou':
j = [Link](i)
new_list += [j]
print(new_list)
45. x = 25
def modify(s, c=2):
global x
for a in s:
if a in 'QWEiop':
x //= 5
print([Link](),'@',c*x)
else:
x += 5
print([Link](),'#',c+x)
string = 'We'
modify(string,10)
print(x, '$', string)
46. string= ‘abacus@2023’
count=3
while True:
if string[0] == 'a':
string= string[2:]
elif string[-1] == ‘b’:
string =string[:2]
else:
count+= 1
break
print (string)
print(count)
47. F1, F2 , F3 ="WoNdERFUL" , "StuDenTS" , " "
for I in range(0,len(F2)+1):
if F1[I]>='A' and F1<='F':
F3=F3+F1[I]
elif F1[I]>='N' and F1[I]<='Z':
F3=F3+F2[I]
else:
F3=F3+"*"
print(F3)
48. What are the possible outputs?
import random
Cards = ["Heart", "Spade", "Club", "Diamond"]
for i in range(2):
print(Cards[[Link](1, i+2)], end="#")
(A) Spade#Diamond# (B) Spade#Heart#
(C) Diamond#Club# (D) Heart#Spade#

49. def Total (Num=10):


Sum=0
for C in range(1,Num+1):
if C%2!=0:
continue
Sum+=C
return Sum
print(Total(4),end="$")
print(Total(),end="@")

50. What are the possible outputs ?


Import random as rd
status=[“EXCEL”, “GOOD”, “OK”]
turn=10
for count in range(1,4):
trick=[Link](count)
print(turn-trick,status[trick],end=”#”)

(i) 10EXCEL# 10EXCEL# 8OK#


(ii) 10EXCEL# 8OK# 9GOOD#
(iii) 10EXCEL# 9GOOD# 10EXCEL#
(iv) 10EXCEL# 10GOOD# 8OK
51. Consider the following code and Find the possible outputs :
import random
x=[Link]() i. 0:0 ii. 1:6
y=[Link](0,4) iii. 2:4 iv. 0:3
print(int(x),":",y+int(x))
52. string="aabbcc" K = "FIFA"
count=3 P = [12, 23, 31, 4]
while True: s={}
if string[0]=='a': for I in range(len(K)):
string=string[2:] if I%2==0:
elif string[-1]=='b': S[[Link]()] = K[i]
string=string[:2] else:
else: S[[Link]()] = i + 1
count+=1 for x,y iin [Link]():
break print(x,y,sep=’#’)
print(string)
print(count)
53. What are the possible output will come as result?
import random
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = [Link](1,3)
print(List[x],end="#")

a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
54. LST=[5,10,15,20,25,30,35,40,45,50,60,70]
a = randint(3,8) (i) 20#25#25#
b = randint(4,9) (ii) 30#40#70#
c = randint(6,11) (iii) 15#60#70#
print(LST*a+, “#”,LST*b+, “#”,LST*c+, “#”) (iv) 35#40#60#
55. hello = {empname: "Ishan", address: ”New Delhi”, salary: 10000}
hello[salary] = 15000
hello[address] = "Delhi"
print([Link]())
print(len([Link]())))
print(tuple([Link]()))
56. Original = [10, 20, 30, 40, 50]
Result = {}
while len(Original) > 0:
Val = [Link]()
if Val % 20 == 0:
Result[Val] = "Double"
else:
Result[Val] = "Triple"
for k, v in [Link]():
print(k, v, sep=":")
57. def fun1():
x = 100
def fun2():
x = 200
print("x in func()2", x)
print("Before calling fun2: " + str(x))
fun2()
print("After calling fun2: " + str(x))
global x
x = 50
fun1()
print("x in main: " + str(x))
58. def fun1():
x = 100
def fun2():
nonlocal x
x = 200
print("x in func()2:", x)
print("Before calling fun2:", x)
fun2()
print("After calling fun2:", x)
x = 50
fun1()
print("x in main:", x)
59. s="GuDLuck4Xam2026"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)

60. a. Name = "PythoN@3.11"


R = ""
for x in range(len(Name)):
if Name[x].isupper():
R = R + Name[x].lower()
elif Name[x].islower():
R = R + Name[x].upper()
elif Name[x].isdigit():
R = R + Name[x-1]
else:
R = R + "#"
print(R)

b. def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))

You might also like