Friday, 30 August 2019

Assignments on Python Data Types


Revision  Python Data Types
1. List all data types and write one example of each type.
2.  What is the difference between mutable and immutable data type? Give examples of each. 
3. Which of the following is true?
    a)   All keywords in python are in lower case
    b)   All variable names are case sensitive  
4.  Identify valid variable names from the following:
My_string_1 , 1ststring , Id , id , True , class
5. Which of the following is not a keyword?
eval, string , str , id , type
6.  Which of the following is a valid assignment statement?
     a)   a ; b ; c = 10  20 30                 b) a_b_c = 10 , 20 , 30
c)   a, b, c = 10 , 20 , 30               d) a b c = 10 20 30
7. If x=2 , What will be the output of the following:
          a) print(“x”)                             b) print( ‘x’ )                                                  c) print(x)
          d) print (‘x’ + 2 )                      d) print(‘x +  2’)            
e) print(‘x’ * 2)                         f) print( x * 2 )
8. Pick the correct assignment statement from the following and Justify your answer:
a) school = ‘Hans
                  raj’
b) school = “Hans
                  raj”
c) school='''Hans
                  raj'''
9. Write the output produced by the following statements:
          a) print(‘You\tare\tyour\nchoices’)
          b) print(‘\‘How old are you ?\’, he asked’)
          c) print('"Don\'t\ttalk in the class"')
10. Given a=15,b=9,c=1, Evaluate the following:
a) a % 4 + ( 3 + b // 4 ) – 2 ** c * 3
b)  a < c and b < c or  not ( a > c )
c) a != b or a > b and c == 1
11. What is a comment? Identify the comments in the following code snippet:
          # function to calculate area of a rectangle
def area(l,b):     # function definition
                   return l*b
print('Area=' , area(2,3) )  # function call
12. Given quote = “focus and win 100%”. Write the output produced by the following:
          a) quote[ -1]         b) quote[1]           c) quote[ len(quote) – 4 : ]
          d) quote[ : len(quote) – 4 ]               e) quote [ 6 : -5 ]
          f) quote.upper()                                 g) quote.title()
          h) quote.find(‘us’)                             i) quote.find(‘n’,10)
13. Given one = [ 11 ,22 ,33 ] and two = [ 33 , 55 ]. Write the output produced by the following:
            a) print( one[len(one) - 2 ] )              b) print( sum(two) // len(two) )
          c) print( max(one) // 10 )                            d) print( max(one) – min(one) )
          e) print(one.count(1))                        f) print(one.count(11))
          g)  two[1]=44                                    h) one.extend(two)                                i) tuple(one)
              print(two)                                           print(one)
14. Given odd=(1,3,[5, 7] , 9). Write the output produced by the following:
          a) odd[1:]             b) del odd[1]        c) odd[2][0] = 9   d) del odd[2][0]
                                                                                                               print odd
15. Given even=(2,4,6) . Write the output produced by the following:
          a) even[0] = 100                                        b)  a = list(even)
                                                                                  even[0] = 100
                                                                                  print(even)
16. Which of the following statement are correct for a dictionary?
          a) Record = { ‘name’ : [‘hansraj’] , ‘address’ : ‘punjabi bagh’ }
b) Record = { ‘name’ : [‘hansraj’] , ‘address’ : [‘punjabi bagh’] }
c) Record = { [‘name’] : ‘hansraj’ , [‘address’] : ‘punjabi bagh’ }
d) Record = { ‘name’ : [‘hansraj’] , ‘address’ : ‘punjabi bagh’ }
e) Record = { ('school') : ['hansraj'] , ('address') : ['punjabi bagh'] }
f) Record = { ('school') : ('hansraj') , ('address') : ('punjabi bagh') }
g) Record = { 'school' : 'hansraj' , 'address' : 'punjabi bagh' }

17. Given details =  { ‘exam’ : ‘Term1’ , ‘start’ : 9 , ‘end’ : 12  }.
      What will be the output of the following:
          a) print ( details.get(‘exam’) )               b) details[‘exam’]
          c) del details[‘end’]                              d) details[‘exam’] = ‘Half Yearly’
                                                                                 print(details)


Assignment questions of Selection and Iteration


Revision  Python Control Structures
1. Name the flow control statement used in each of the following:
a) Execute program statements in a sequence
b) Make a decision
c) Select one of the two alternatives
d) Select from one of the several alternatives
e) Repeat a set of statements determinate number of times
f) Repeat a set of statements as long as the condition is True, indeterminate times
2.  Find the output produced by the following code snippets:
(a) for the input:
(i) 6   (ii) 9  (iii) 4  (iv)  2
n = int(input('Enter number of sides:'))
print('Figure',end=":")
if n==1 or n==2 :
    print('Line / parallel lines')
elif n == 3 :
    print('Triangle')
elif n == 4 :
    print('Quadrilateral')
elif n== 5 :
    print('Pentagon')
elif n == 6 :
    print('Hexagon')
else :
    print('Not in range')

(b) for the input:
(i) 1   (ii) 12  (iii) 123  (iv)  1234
num  = int(input('enter a number '))
if num > 9 and num <= 99 :
    print(num , 'is a two digit number')
elif num > 99 and num <= 999 :
    print(num , 'is a three digit number')
else :
    print(num , ' is less than 10 or greater than 999' )

(c )for the input:
 (i) a=15  (ii) a=18, b=yes (iii) a=18, b=no 
a = int(input('Enter your age '))
if a >= 18:
    b = input('Do you have a license? ')
    if b == 'yes' :
        print('eligible to drive')
        print('go on')
    else :
        print('get a license')
else :
    print('under age')
print('thank you for the info')
(d) for the input:
(i) age=10 (ii) age=15 (iii) age=20
if age >= 18 :
    print('Adult')
else :
    if age >= 13:
        print('Teenager')
    else :
        print('Child')

(e) for the input:
ph=5, ph=10, ph=15, ph=7
Lst1 = range(1,7)
Lst2 = range(8,15)
ph = int(input('Enter pH '))
if ph in Lst1 :
    print('Acidic')
elif ph == 7:     
    print('Neutral')
elif ph in Lst2 :
    print('Basic')
else :
    print('Invalid')

(f)for parameters :
(i)   a, b =’Ashish’ , ‘Sharma’
(ii)   a, b = None, None
     
def greeting(a,b) :
    if a == None and b == None :
        print('Hello World')
    else :
        print('Hello ' + b[0:2] + ' ' + a)

greeting(a,b)

3. Rewrite the following code in Python after removing all syntax error(s). Underline each correction done in the code.
I
num = integer(input('Enter a number'))
if num % 10 == 0
          print(Divisible by 10)
else
          print(Not divisible by 10)
II
Def show(d)
    If d == 'saturday' or d == 'sunday' :
    print 'weekend'
    else :
    print 'weekday'
 return

4. Write a if statement to assign result as ‘Pass’ if marks greater than or equal to 33, otherwise assign
    result as ‘Fail’.
5.  Write a if statement to display  “Belongs to family” if num is divisible by 5, otherwise display “Not in
    family”.
6. Write if statement to assign weather as ‘hot’ if temp is 30 or above , assign weather as ‘pleasant’ if
    temp is between 10 and 31, assign weather as ‘cold’ if temp is below 10.
7. Write a program to input name and marks out of 100 each in 5 subjects. Calculate the
    percentage [ perc = grandtotal / 5 ] and display result as ‘Pass’ or ‘Fail’. Also display the remarks
    according to the following criteria:
          Percentage                        Remarks
          80 and above                    Outstanding
         Between 70 and 79             Distinction
          Between 60 and 69             First Division
8. Write the output of the following range() statements
a)
range(10)

b)
range(1,10)

c)
range(1,10,2)

d)
range(10,0,-1)

e)
range(10,0,-2)

f)
range(2,11,2)

g)
range(-5,5)

h)
range(1,2)

i)
range(1,1)

j)
range(1,-1)

k)
range(1,-1,-1)

l)
range(0)

9.  How many times will the following loops be executed? Also write the output.
a)
a = 10
while a <= 100 :
       print(a)
       a += 10
d)
a = 10
while a <= 20 :
       if a % 5 == 0 :
             print(a)
       a += 2
b)
a = 10
while a > 1 :
       print(“*”)
       a -= 1 
e)
for a in range(10, 0,-2):
     print( a // 2 , end=”:”)
 

c)
a = 10
while a > 1
       print( a * a )
       a -= 2
f)
for a in range(50,0,-10) :
      print(a, end=’,’)

10. Write the output produced by the following code fragments:
(a)
(b)
(c)
num = 1825
acc = 0
while num > 0 :
    d = num % 10
    if d % 2 == 0 :
        acc += d //2
    else:
        acc += d ** 2
    num = num // 10
print(acc)
num = 1825
ctr = 0
while num > 0 :
    d = num % 10
    ctr += 1
    num = num // 10
print(ctr)
num = 1825
p = 1
while num > 0 :
    d = num % 10
    p *= d
    num = num // 10
print(p)

11. The following function convert() is written in a file fun.py
def convert(dollar) :
    rs = dollar * 71
    return rs
Write the statement to execute this function at python shell for parameter 5. Also write the output produced.
12. The following functions area() and peri() are defined in the module square.py
def area(s) :
    return s * s
def peri(s) :
     return 4 * s
Write the statements to execute these function at python shell for parameter 5.
13. Consider the following function definitions, predict the output for the given function call statements:
(a)
(b)
©
def multiply(a,b=1):
    return a * b

print(multiply(5,2))
print(multiply(5))
def repeat(a=10,b='@') :
    for i in range(a) :
        print(b, end='')

repeat(5,'*')
repeat(4)
repeat()
repeat(b='#',a=3)






Loops are used to iterate over elements of a sequence, it is often used when a piece of code which you want to repeat “n” number of time.

A for loop is used for iterating over a sequence (that is either a list, a tuple or a string).

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Syntax:
for var in sequence:

statements(s)

else:

statements(s)

Here, val is the variable that takes the value of the item inside the sequence on each iteration. Else statement(s) will be executed when loop terminated normally(without break statement)


Q Show 0 to 4

for i in 0,1,2,3,4:

print (i)

or

for i in range(5):

print(i)





We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).


We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided, start value is 0 if not provided.




Q1 Show 1 to 10

for i in range (1,11):

print (i)




Q2 Show 10 to 1 horizontally

for i in range(10,0,‐1):

print (i,end=" ")



Q3 Show 1st 10 even nos

for i in range (0,20,2):

print (i)

else:

print("finished")


  

Q4 Show sum of 1st 10 nos

s=0

for i in range (1,11):

s=s+i

print (‘sum =,s)



Q5 Take a no and show table of it

a=int(input('enter anyno'))

for i in range (1,11):

print (i*a)

  



Q6 Take a no and show table of it in proper format

a=int(input('enter anyno'))

for i in range (1,11):

print (i,'*',a,'=',i*a)



  

Q7 Show factorial of 5

f=1

for i in range (1,6):

f=f*i

print ("factorial of 5 is ", f)


Q8 Take a no and show factorial of it

f=1

a=int(input("enter any no"))

for i in range (1,a+1):

f=f*i

print ('factorial of',a,'is',f)



Q9 Take a no and check prime or not

a=int(input("enter any no"))

k=0

for i in range(2,a):

if(a%i==0): k=1 break
if k==0:

print("prime ")

else:

print("not prime")



Q10 Take a no and check prime or not using for else

a=int(input("enter any no"))

for i in range(2,a):

if(a%i==0):

print(a,"is not prime no")

break

else:                                # else will be executed when for loop complete its sequence (break not executed)

print("prime ");





Q11 Print the format

*

* *

* * *

* * * *

for i in range(1,5):

print("*"*i)


  

break is used to exit a for loop or a while loop,





whereas continue is used to skip the current block, and return to the "for" or "while" statement.













: