Learn Python by Examples
Python Questions and answers selected from past papers
Question 1)
Write Python program to computes the sum of integer from 1 to 10 (including 1 and 10)?
Program tot=0 i=1 while i<=10: tot=tot+i i=i+1 print ('Total of 1 to 10=',tot) Output Total of 1 to 10= 55
Question 2)
What would be the value of the variable temp after executing the statements temp=[23,45,2,-2,0][:3] of Python program?
Program temp=[23,45,2,-2,0][:3:] print(temp) Output [23, 45, 2]
Question 3)
What would be the value of the variable x after executing the statements x=3-4*6/3+12/4*3 of Python program?
Program x=3-4*6/3+12/4*3 print(x) Output 4.0
Question 4)
Factorial of a positive integer n is defined as n x (n-1) x (n-2) x ....3 x 2 x 1.
i) Propose an algorithm by using a Pseudocode to print the factorial of a given positive integer n.
ii) Write a Python program to implement your Pseudocode.
iii) Write a Python Function to implement your Pseudocode.
i) start input n i=n tot=1 while i>=1 tot=tot*i i=i-1 endwhile print tot end ii) Program n=eval(input('Enter a positive integer?')) i=n tot=1 while i>=1: tot=tot*i i=i-1 print('Factorial value of',n,'=',tot,sep=' ') Output Enter a positive integer?5 Factorial value of 5 = 120 iii) #define a function def my_factorial(): n=eval(input('Enter a positive integer?')) i=n tot=1 while i>=1: tot=tot*i i=i-1 print('Factorial value of',n,'=',tot,sep=' ') #call the function my_factorial() Output Enter a positive integer?5 Factorial value of 5 = 120
Note :
Another way to define the algorithm is given below where input variable n directly assign to the multiplication variable value tot but remember to get correct answer, statements' order should be changed within the repetition.
Carefully compare both algorithm.
#define a function def my_factorial(): n=eval(input('Enter a positive integer?')) tot=n while n>1: n=n-1 tot=tot*n print('Factorial value of',tot,'=',tot,sep=' ') #call the function my_factorial()
Question 5)
a) The outputs of the flowchart
b) Write correct pseudo code
Output a) 11, 22, 44 b) Pseudocode start r=5 s=3 do r=r+s s=r+3 print s while (r<25)
Note:
Programming languages such as Pascal, C, Java are having do..while and repeat...until repetition; but Python doesn't have repeat...until. The Python code to simulate the repeat...until is given below.
r=5 s=3 while True: r=r+s s=r+3 print(s) if r>=25: break
No comments:
Post a Comment