Friday, January 14, 2022

Python Exercises for ICT Students

Question
Write a Python function to sum all elements in a list which is passed as parameter and return the sum value.

Answer
#function to sum list
def Lsum(L):
    s=0
    for i in L:
        s=s+i
    return s

#call the function
sales=[15000,20000,3000,12000,5000,8900]
print(Lsum(sales))

Question
The factorial of a positive integers n is defined as n x (n-1) x (n-2) x ......x 3 x 2 x1.
Write a python function to return the factorial value of a given integer.

Answer
#function to find factorial value to a given number
def fact(n):
    Fact=n
    while (n>1):
        n=n-1
        Fact=Fact*n        
    return Fact

#call the function
N=int(input("Enter a number?"))
print(fact(N))

Question
Write a Python program to transform the data from in.csv file content to out.csv file. Content of the in.csv file is given below. The out.csv file should have total value as additional data.
 
Peter,80,90
David,100,75
Black,50,60

 Answer
f1=open("in.txt","r")
f2=open("out.csv","w")
for line in f1:
    items=line.strip().split(",")
    tot=int(int(items[1])+int(items[2]))
    print(items[0],items[1],items[2],tot,file=f2)
f1.close()
f2.close() 

Question
  1. Describe how you would determine whether a given positive integer is odd or even
  2. Develop a flowchart to represent an algorithm, based on the method suggested in (i) above, to decide whether a given positive integer is odd or even.
  3. Convert the flowchart you have obtained for the above (ii) into a pseudo code.
  4. Convert the pseudo code obtained in (iii) into a Python program.

Answers
i) 
Divide the given integer by 2 and get the remainder. 
If the remainder is 0 then the number is even otherwise the number is odd. 
(note: if we divide any number by 2 then remainder will be 0 or 1 only)




ii)
Flowchart to find odd or even
iii)
Pseudo code
Start
input N
R=N%2      #divide the number by 2 and get the remainder to R
if (R=1) then
	display  "the number is odd"
else
	display "The number is even"
endif
End




iv)
#Python Program
N=int(input("Enter a positive Integer?"))
R=N %2
if (R==1):
    print("The number is odd")
else:
    print("The number is even")


Sample Output
Enter a positive Integer?101
The number is odd

Enter a positive Integer?27
The number is odd 



No comments:

Post a Comment