0% found this document useful (0 votes)
39 views21 pages

Python Code Error Corrections Guide

The document contains a series of programming exercises where various Python code snippets are presented with errors. Each question includes an incorrect version of the code followed by a corrected version, with the changes highlighted. The exercises focus on common syntax errors and logical mistakes in Python programming.
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)
39 views21 pages

Python Code Error Corrections Guide

The document contains a series of programming exercises where various Python code snippets are presented with errors. Each question includes an incorrect version of the code followed by a corrected version, with the changes highlighted. The exercises focus on common syntax errors and logical mistakes in Python programming.
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

Q1. Vivek has written a code to input a number and check whether it is even or odd number.

His code
is having errors. Rewrite the correct code and underline the corrections made.

Def checkNumber(N):

status = N%2

return

#main-code

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”)

Ans:

Incorrect Code Incorrect Code


Def checkNumber(N): def checkNumber(N):

status = N%2 status = N%2

return return

#main-code #main-code

num=int( input(“ Enter a number to check :)) num=int( input(“ Enter a number to check :”))

k=checkNumber(num) k=checkNumber(num)

if k = 0: if k = = 0:

print(“This is EVEN number”) print(“This is EVEN number”)

else: else:

print(“This is ODD number”) print(“This is ODD number”)

Q2. Sameer has written a python function to compute the reverse of a number. He has
however committed a few errors in his code. Rewrite the code after removing errors also
underline the corrections made.
define reverse(num):
REV=0
While num > 0:
rem == num %10
rev = rev*10 + rem
Num=NUM//10
return rev

print(reverse(1234))

Ans:
Incorrect Code Correct Code
define reverse(num): def reverse(num):
REV=0 rev=rem=0
While num > 0: while num > 0:
rem == num %10 rem = num%10
rev = rev*10 + rem rev = rev*10 + rem
Num=NUM//10 num=num//10
return rev return rev

print(reverse(1234)) print(reverse(1234))

Q3. Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.

Num=int(rawinput("Number:"))

sum=0

for i in range(10,Num,3)

sum+=1

if i%2=0:

print(i*2)

else:

print(i*3)

print (Sum)

Ans:
Incorrect Code Correct Code
Num=int(rawinput("Number:")) Num=int(input("Number:"))
sum=0 sum=0
for i in range(10,Num,3) for i in range(10,Num,3) :
sum+=1 sum+=1
if i%2=0: if i%2==0:
print(i*2) print(i*2)
else: else:
print(i*3) print(i*3)
print (Sum) print(sum)

Q4. Observe the following Python code very carefully and rewrite it after removing all
syntactical errors with each correction underlined.
DEF execmain():
x = input("Enter a number:")
if (abs(x)== x)
print("You entered a positive number")
else:
print("Number made positive:" x )

Ans:
Incorrect Code Correct Code
DEF execmain(): def execmain():
x = input("Enter a number:") x = int(input("Enter a number:"))
if (abs(x)== x) if (abs(x)== x):
print("You entered a positive print("You entered a positive
number") number")
else: else:
print("Number made positive:" x ) print("Number made positive:" ,x )
execmain()

Q5. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in
the code.
30=Value
for VAL in range(0,Value)
If val%4==0:
print (VAL*4)
Elseif val%5==0:
print (VAL+3)
else
print(VAL+10)

Ans:
Incorrect Code Correct Code
30=Value Value=30
for VAL in range(0,Value) for val in range(0,Value):
If val%4==0: if val%4==0:
print (VAL*4) print (val*4)
Elseif val%5==0: elif val%5==0:
print (VAL+3) print (val+3)
else else:
print(VAL+10) print(val+10)
Q6. Ravi has written a function to print Fibonacci series for first 10 elements. His code is having
errors. Rewrite the correct code and underline the corrections made. some initial elements of
Fibonacci series are:
def fibonacci()
first=0,second=1
print(("first no. is ", first)
print("second no. is , second)
for a in range (1,9):
third=first+second
print(third)
first,second=second,third
fibonacci()
Incorrect Code Correct Code
def fibonacci() def fibonacci():
first=0,second=1
print(("first no. is ", first) first=0;second=1
print("second no. is , second)
for a in range (1,9): print("first no. is ", first)
third=first+second
print(third) print("second no. is ", second)
first,second=second,third
fibonacci() for a in range (1,9):

third=first+second

print(third)

first,second=second,third

fibonacci()

Q7. Aarti has written a code to input an integer and check whether it is even or odd. The code has
errors. Rewrite the code after removing all the syntactical errors, underlining each correction:
checkval def():
x = input("Enter a number")
if x % 2 == 0
print (x, "is even")
else;
print (x, "is odd")

Ans:
Incorrect Code Correct Code
checkval def(): def checkval():
x = input("Enter a number")
if x % 2 == 0 x = int(input("Enter a number"))
print (x, "is even")
else; if x % 2 == 0:
print (x, "is odd")
print (x, "is even")

else:
print (x, "is odd")

checkval()

Q8. Mithilesh has written a code to input a number and evaluate its factorial and then
finally print the result in the format : “The factorial of the <number> is <factorial value>”
His code is having errors. Rewrite the correct code and underline the corrections made.
f=0
num = input("Enter a number whose factorial you want to evaluate :")
n = num
while num > 1:
f = f * num
num -= 1
else:
print("The factorial of : ", n , "is" , f)
Incorrect Code Correct Code
f=0 f=1
num = input("Enter a number whose factorial you want to num = int(input("Enter a
evaluate :") number whose factorial you
n = num want to evaluate :"))
while num > 1: n = num
f = f * num while num > 1:
num -= 1 f = f * num
else: num -= 1
print("The factorial of : ", n , "is" , f) else:
print("The factorial of : ",
n , "is" , f)

Q9. Find error in the following code(if any) and correct code by rewriting code
and underline the

correction;‐

Def Errors()

x= int(“Enter value of x:”)

for in range [0,10]:


if x=y

print( x + y)
else:
print( x‐y)
Incorrect Code Correct Code
Def Errors() def Errors():

x= int(“Enter value of x:”) x= int(input("Enter value of x:"))

for in range [0,10]: for y in range (0,10):


if x=y
if x==y:
print( x + y)
else: print( x + y)
print( x‐y)
else:

print(x-y)

Q10. Mohini has written a code to input a positive integer and display all its even factors in
descending order. Her code is having errors. Rewrite the correct code and underline the
corrections made.
n=input("Enter a positive integer: ")
for i in range(n):
if i%2:
if n%i==0:
print(i,end=' ')
Incorrect Code Correct Code
Def code() def code():
n=input("Enter a positive integer: ")
for i in range(n): n=int(input("Enter a positive integer: ") )
if i%2:
if n%i==0: for i in range(n):
print(i,end=' ')
if i%2:
define code()
if n%i==0:

print(i,end=' ')

code()

Q11. Write the output of the following code:


def printMe(q,r=2): def show():
p=r+q**3 data = [1,2,4,5]
print(p) for x in data:
#main-code x = x + 10
a=10 print(data)
b=5
printMe(a,b) show()
printMe(r=4,q=2)
Output: [1, 2, 4, 5]
Output: 1005

12
def foo(s1,s2): def sumList():
l1=[] data = [2,4,2,1,2,1,3,3,4,4]
l2=[] d = {}
for x in s1: for x in data:
[Link](x) if x in d:
for x in s2: d[x]=d[x]+1
[Link](x) else:
return l1,l2 d[x]=1
a,b=foo("FUN",'DAY') print(d)
print(a,b) sumList()

Output: ['F', 'U', 'N'] ['D', 'A', 'Y'] Output: {2: 3, 4: 3, 1: 2, 3: 2}


def convert(s): st = "python programming"
n = len(s) def countShow(st):
m="" count = 4
for i in range(0, n): while True:
if (s[i] >= 'a' and s[i] <= 'm'): if st[0]== "p":
m = m +s[i].upper() st = st[2:]
elif (s[i] >= 'n' and s[i] <= 'z'): elif st[-2]=="n":
m = m +s[i-1] st = st[:4]
elif (s[i].isupper()): else:
m = m +s[i-1] count+=1
elif (s[i].isupper()): break
m=m+s[i].lower() print(st)
else: print(count)
m=m+'#'
print(m) countShow(st)
s="welcome2dis"
convert(s) Output: thon

Output: sELCcME#DIi 5
def output(myvalue): def convert(line):
alpha = 0 n = len(line)
beta = "" new_line = ''
gama = 0 for i in range(0,n):
for i in range(1,6,2): if not line[i].isalpha():
alpha += i new_line = new_line + '@'
beta += myvalue[i-1]+ "#" else:
gama += myvalue[i] if line[i].isupper():
print(alpha, beta, gama) new_line = new_line + line[i]*2
else:
myvalue = ["A", 40, "B", 60, "C", 20] new_line = new_line + line[i]
output(myvalue) return new_line

new_line = convert("Be 180 HuMan")


print(new_line)

Output: 9 A#B#C# 120 Output : BBe@@@@@HHuMMan


def Change(P ,Q=30): def newTuple(tuple1):
P=P+Q list1 =list(tuple1)
Q=P-Q new_list = []
print(P,"#",Q) for i in list1:
return(P) if i%2==0:
R=150 new_list.append(i)
S=100 new_tuple = tuple(new_list)
R=Change(R,S) print(new_tuple)
print(R,"#",S)
S=Change(S) tuple1 = (11, 22, 33, 44, 55 ,66)
newTuple(tuple1)
Output: 250 # 150

250 # 100 Output: (22, 44, 66)

130 # 100
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)

Output: 300 @ 200


Output: 5#8#5#4#
300 @ 100

120 @ 100

300 @ 120
def Alpha(N1): T1 = tuple("Amsterdam")
while N1:
a=[Link]() def vowel(T1):
if a%5>2: T2, new_list = T1[1:-1], []
print(a,end='@') for i in T2:
else: if i in 'aeiou':
break j=[Link](i)
NUM=[13,24,12,53,34] new_list+=[j]
Alpha(NUM);print(NUM) print(new_list)

vowel(T1)

Output : [4, 7]

Output : 34@53@[13, 24]


T = (9,18,27,36,45,54) L=[4,6,7,1,6,9,4]
def User_func(T): 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:
[Link](i) return(L)
T1 = tuple(L1) print("Original List : ", L)
print(T1) k=fun(L)
print("Now New List : ",k)
User_func(T)
Output: (18, 36, 54) Output: Original List : [4, 6, 7, 1, 6, 9, 4]

Now New List : [4, 7, 7, 1, 7, 9, 4]


def Convert(s): def Display(str):
n = len(s) m=""
m="" for i in range(0,len(str)):
for i in range(0, n): if(str[i].isupper()):
if (s[i] >= 'a' and s[i] <= 'm'): m=m+str[i].lower()
m = m +s[i].upper() elif str[i].islower():
elif (s[i] >= 'n' and s[i] <= 'z'): m=m+str[i].upper()
m = m +s[i-1] else:
elif (s[i].isupper()): if i%2==0:
m=m+s[i].lower() m=m+str[i-1]
else: else:
m=m+'&' m=m+"#"
print(m) print(m)
Display('Fun@World2.0')
s="Hello2everyone"
Convert(s)

Output: hELLl&EeEeryoE Output : fUN#wORLD#2#


x="hello world" def encrypt(s):
def Testy(x): k=len(s)
print(x[:2],x[:-2],x[-2:]) m=""
print(x[6],x[2:4]) for i in range(0,k):
print(x[2:-3],x[-4:-2]) if(s[i].isupper( )):
Testy(x) m=m+str(i)
elif s[i].islower( ):
m=m+s[i].upper()
else:
m=m+'*'
print(m)
encrypt('DooN@Kanpur')
Output: he hello wor ld
Output:
w ll
0
llo wo or
0O

0OO

0OO3

0OO3*

0OO3*5

0OO3*5A

0OO3*5AN
0OO3*5ANP

0OO3*5ANPU

0OO3*5ANPUR
def Change(P ,Q=10): value = 50
P=P*Q def display(N):
Q=Q+P global value
print( P,"#",Q) value = 25
return (Q) if N%7==0:
A=5 value = value + N
B=10 else:
A=Change(A) value = value - N
B=Change(A,B)
print(A,"#",B) print(value, end="#")
display(20)
print(value)

Output: 50 # 60
Output: 50#5
600 # 610

60 # 610
a=20 x = 50
def call(): def func():
global a global x
b=20 print('x is', x)
a=a+b x = 20
return a print('Changed global+local x to', x)
print(a) func()
call()
print(a)

Output: 20

40 Output: x is 50

Changed global+local x to 20
def convert(Old): def Compy(N1,N2=10):
l=len(Old) return N1 > N2
New="" NUM= [10,23,14,54,32]
for i in range(0,l): for VAR in range (4,0,-1):
if Old[i].isupper(): A=NUM[VAR]
New=New+Old[i].lower() B=NUM[VAR-1]
elif Old[i].islower(): if VAR > len(NUM)//2:
New=New+Old[i].upper() print(Compy(A,B),'#', end=' ')
elif Old[i].isdigit(): else:
New=New+"*" print(Compy(B),'%',end=' ')
else:
New=New+"%"
return New
Older="InDIa@2022"
Newer=convert(Older)
print("New String is: ", Newer)

Output: New String is: iNdiA%****

Output: False # True # True % False %


tuple1 = ( [7,6],[4,4],[5,9],[3,4],[5,5], string="aabbcc"
[6,2] , [8,4]) count=3
def fun(string):
def newValue(tuple1): count=3
listy = list( tuple1) while True:
new_list = list() if string[0]=='a':
for elem in listy : string=string[2:]
tot = 0 elif string[-1]=='b':
for value in elem: string=string[:2]
tot += value else:
if [Link](value) == 2: count+=1
new_list.append(value) break
tot = 0 print(string)
else: print(count)
print( tuple(new_list) ) fun(string)
newValue(tuple1)
Output: bbcc
Output: (4, 4, 5, 5)
4
def Fruit(fruit_list1): my_dict = {}
fruit_list2 = fruit_list1 my_dict[(1,2,4)] = 8
fruit_list3 = fruit_list1[:] my_dict[(4,2,1)] = 10
fruit_list2[0] = 'Guava' my_dict[(1,2)] = 12
fruit_list3[1] = 'Kiwi'
sum = 0 def Value(my_dict):
for ls in (fruit_list1, fruit_list2, sum = 0
fruit_list3): for k in my_dict:
if ls[0] == 'Guava': sum += my_dict[k]
sum += 1 print (sum)
if ls[1] == 'Kiwi': Value(my_dict)
sum += 20 print(my_dict)
print (sum)

fruit_list1 = ['Apple', 'Berry', 'Cherry',


'Papaya']
Fruit(fruit_list1)
Output: 30
Output: 22
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
def Alpha(N1,N2): List1 = list("Examination")
if N1>N2: List2 =List1[1:-1]
print(N1%N2) def newList(List2):
else: new_list = []
print(N2//N1,'#',end=' ') for i in List2:
NUM=[10,23,14,54,32] j=[Link](i)
for C in range (4,0,-1): if j%2==0:
A=NUM[C] [Link](i)
B=NUM[C-1] return(List1)
Alpha(A,B) print(newList(List2))

Output: 1 # 12

1#3
Output: ['E', 'a', 'i', 'a', 'i', 'n']
p=8 s="3 & Four"
def sum(q,r=5): n = len(s)
global p def Convert(s,n):
p=(r+q)**2 m=""
print(p, end= '#') for i in range(0, n):
a=2; b=5; sum(b,a) if (s[i] >= 'A' and s[i] <= 'Z'):
sum(r=3,q=2) m = m +s[i].upper()
elif (s[i] >= 'a' and s[i] <= 'z'):
Output : 49#25# m = m +s[i-1]
if (s[i].isdigit()):
m = m + s[i].lower()
else: m = m +'-'
return m
s=Convert(s,n)
print(s)

Output: 3---F-F-o-u-
def multiply(number1, number2) : def addEm(x,y,z):
answer = number1 * number2
return(answer) return(x+y+2)
print(number1, 'times', number2, '=',
answer) def prod(x,y,z):
output = multiply(5, 5)
print(output) return x*y*z

a= addEm(6,16,26)
Output : 25
b= prod(2,3,6)

print(a,b)

Output :24 36
Q12. 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 5. Also write a
proper call statement for the function.

For example:

If list L contains [3,5,10,12,15]

Then the modilist() should make the list L as [3,15,20,12,25]

Ans:

def modilst(L):

for i in range(len(L)):

if L[i] % 5 == 0:

L[i]+=10

L = [12,10,15,20,25]

modilst(L)

print(L)

Q13. 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]

Ans:

def lenFOURword(L):

indexList=[]

for i in range(len(L)):

if len(L[i])==4:

[Link](i)

return indexList
L=["DINESH", "RAMESH", "AMAN", "SURESH", "KARN"]

print(lenFOURword(L))

Q14. Write a python function displaywords() that will print all the words that are
having length greater than 3.

Example:

For the fie content:

A man always wants to strive higher in his life. He wants to be perfect.

The output after executing displayword() will be:

Always wants strive higher life wants perfect

Ans:

strings='A man always wants to strive higher in his life. He wants to be perfect.'

def displayword(strings):

words=[Link]()

for i in words:

if len(i)>3:

print(i,end=' ')

displayword(strings)

Q15. Write a python function countvowel() that reads the contents of the string and
counts the occurrence of vowels(A,E,I,O,U) in the file.

Ans:

def countvowels(st):

c=0

for i in st:

if i in 'aeiouAEIOU':

c+=1

return c
st="The quick brown fox jumps over the lazy dog"

count=countvowels(st)

print("Count no. of vowels :", count)

Q16. Ravi a python programmer is working on a project, for some requirement, he has to
define a function with

name CalculateInterest(), he defined it as:

def CalculateInterest (Principal, Rate=.06,Time): # code

But this code is not working, Can you help Ravi to identify the error in the above function and
what is the solution.

Ans:

In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default


parameters from right to left hence either Time should be provided with some default value
or default value of rate should removed.

Q17. What do you understand the default argument in function? Which function parameter
must be given default argument if it is used? Give example of function header to illustrate
default argument.

Ans:

Default argument in function- value provided in the formal arguments in the definition header
of a function is called as default argument in function. They should always be from right side
argument to the left in sequence. For example:

def func( a, b=2, c=5): # definition of function func( )

Q18. 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]

Ans:

def INDEX_LIST(L):

indexList = [ ]

for i in range(0,len(L)):

if (L[i]%2 == 0):
[Link](i)

return indexList

L =[12,4,15,11,9,56]

print(INDEX_LIST(L))

Q19. Write a function LeftShift(Numlist, n) in Python, which accepts a list Numlist of


numbers and n is a numeric value by which all elements of the list are shifted to left.

Sample input data of the list

Numlist = [10, 20, 30, 40, 50, 60, 70], n=2

Output

Numlist = [30, 40, 50, 60, 70, 10, 20]

Ans:

def LeftShift(Numlist,n):

NumList=Numlist[n:]+Numlist[:n]

return NumList

Numlist = [10, 20, 30, 40, 50, 60, 70]

n=2

print("Original List",Numlist)

print("After Shift List :",LeftShift(Numlist,n))

Q20. Write a function SQUARE_LIST(L), where L is the list of elements passed as argument to
the function. The function returns another list named ‘SList’ that stores the Squares of all Non-
Zero Elements of L.

For example:

If L contains [9,4,0,11,0,6,0]

The SList will have-[81,14,121,36]

Ans:
def SQUARE_LIST(L):

SList=[]

for i in L:

if i!= 0:

[Link](i*i)

return SList

L=[9,4,0,11,0,6,0]

print(SQUARE_LIST(L))

Q21. Write a function in Python Convert() to replaces elements having even values with
its half and elements having odd values with twice its value in a list.

eg: if the list contains 3,4,5,16,9 then rearranged list as 6,2,10,8, 18

Ans:

def Convert(L):

SList=[]

for i in L:

if i%2== 0:

[Link](i//2)

else:

[Link](i*2)

return SList

L=[3,4,5,16,9]

print(Convert(L))

Q22. Write a function AdjustList(L), where L is a list of integers. The function


should reverse the contents of the list without slicing the list and without using
any second list.

Example: If the list initially contains 2, 15, 3, 14, 7, 9, 19, 6, 1, 10,


then after reversal the list should contain 10, 1, 6, 19, 9, 7, 14, 3, 15, 2

Ans:

def AdjustList(lst):

print("Reversed List : ",end="")

print(list(reversed(lst)))

lst=[2, 15, 3, 14, 7, 9, 19, 6, 1, 10]

print("Original list : ",lst)

AdjustList(lst)

Q23. Write a function EVEN_LIST(L), where L is the list of elements passed as


argument to the function.

The function returns another list named „evenList‟ that stores the indices of all even
numbers of L.

For example:

If L contains [12,4,3,11,13,56]

The evenList will have - [12,4,5]

Ans:

def EVEN_LIST(L):

evenList=[]

for i in L:

if i%2==0:

[Link](i)

return(evenList)

L=[12,4,3,11,13,56]

print("Original List : ", L)

L2=EVEN_LIST(L)

print("Even List : ",L2)

Q24. Write definition of a method/function DoubletheOdd( ) to add and display twice of


odd values from the list of Nums.

For example :
If the Nums contains [25,24,35,20,32,41]

The function should display

Twice of Odd Sum: 202

Ans:

def DoubletheOdd(Nums):

s=0

for i in Nums :

if i%2!=0:

s+=i*2

print("Twice of Odd Sum : ",s)

Nums=[25,24,35,20,32,41]

print("Original List ", Nums)

DoubletheOdd(Nums)

Q25. Write a function in python named SwapHalfList(Array), which accepts a list


Array of numbers and swaps the elements of 1st Half of the list with the 2nd Half
of the list, ONLY if the sum of 1st Half is greater than 2nd Half of the list.

Sample Input Data of the list

Array= [ 100, 200, 300, 40, 50, 60],

Output Array = [40, 50, 60, 100, 200, 300]

def SwapHalfList(Array):

s1=s2=0

L=len(Array)

for i in range(0,L//2):

s1+=Array[i]

for i in range(L//2, L):

s2+=Array[i]

if s1>s2:

for i in range(0,L//2):
Array[i],Array[i+L//2]=Array[i+L//2],Array[i]

L=[ 100, 200, 300, 40, 50, 60]

SwapHalfList(L)

print(L)

Q26. 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 Elements of L which has a even unit place digit.

For example:

If L contains [12,4,15,11,9,56]

The indexList will have - [0,1,5]

Ans:

def Index_List(L):

index_List=[]

for i in range(len(L)):

if L[i]%2==0:

index_List.append(i)

return index_List

L=[12,4,15,11,9,56]

print(L)

idx=Index_List(L)

print(idx)

Q27. Write definition of a method/function AddOdd(VALUES) to display sum of


odd values from the

list of VALUES.

Ans:

def AddOdd(Values):

n=len(Values)

s=0

for i in Values:
if (i%2!=0):

s=s+i

print(s)

Values=[10,3,24,5,7,9,40]

AddOdd(Values)

Q28. Write the definition of a function Sum3(L) in Python, which accepts a list L of integers
and displays the sum of all such integers from the list L which end with the digit 3.

For example, if the list L is passed

[ 123, 10, 13, 15, 23]

then the function should display the sum of 123, 13, 23, i.e. 159 as follows :

Sum of integers ending with digit 3 = 159

Ans:

def sum3(L):

s=0

for i in L:

if i%10==3:

s=s+i

return s

L=[123, 10, 13, 15, 23]

print(sum3(L))

You might also like