Data Handling

Chapter 3

DATA HANDLING

Check Point 3.1

Q1.      What are the built-in core data types of Python?

 Ans.    The following are the built-in core data types of Python.

·         Numbers (int, float, complex)

·         String

·         List

·         Tuple

·         Dictionary

 Q2.      What do you mean by Numeric types? How many numeric data types doe Python provide?

 Ans.    Numeric data types are the different types of the numbers supported by Python. The following are the numeric data types:

·         Integers Numbers

o   Integers (singed)

o   Booleans

·         Floating-Point Number

·         Complex Numbers

 

Q3.      What will be the data types of following two variables?

            A=2147483647

            B = A+1

 Ans.    Integer types

 Q4.     What are Boolean numbers? Why are they considered as a type of integers in Python?

 Ans.   Boolean numbers represent the truth values ‘False’ and ‘True’.  These numbers are considered as a type of integers as the value ‘False’ and ‘True’ behave like the values 0 and 1 respectively.

 Check Point 3.2

 Q1.      What are floating point numbers? When are they preferred over integers?

 

Ans.    A number that has fractional part is called a floating-point number. Floating point numbers are preferred over integers for the following reasons.

(a)  They can represent values between the integers.

(b)  They can represent a much greater range of values.

 

Q2.      What are complex numbers? How would Python represent a complex number with real part as 3 and imaginary part as – 2.5?

 Ans.    In Python a complex number is represented in the form A+Bj. It is made up or two parts: real and imaginary. Where ‘A’ is  ‘B’ are real component and ‘j’  is the imaginary number equal to square root of -1 ( . Python would represent a complex number with real part as 3 and imaginary part as – 2.5 and 3-2.5j.

 Q3.      What will be the output of following codes?

            p=3j

            q=p+(1+1.5j)

            print(p)

            print(q)

 Ans.   print(p)

                        Output: 3j

            print(q)

                        Output: 1+4.5j

 

Q4.      What will be the output of following code?

            r= 2.5+3.9j

            print(r.real)

            print(r.imag)

 

Ans.    print(r.real)

                        Output : 2.5

            print(r.imag)

                        Output: 3.9

 Q5.      Why does Python uses symbol ‘j’ to represent imaginary part of a complex number instead of the conventional ‘i’?

 Ans.    Python adhere to electrical engineering convention. In electrical engineering the symbol ‘i’ is used to represent current and they use the symbol ‘j’ is used for the square root of -1. It is therefore Python uses symbol ‘j’ to represent imaginary part of a complex number instead of the conventional ‘i'.

 

Check Point 3.3

                       

Q1.      What is String data type in Python?

 

Ans.    A string is a collection of one or more characters put in a single quote, double      quote or triple quote. Ex: ‘ab’, “424”, etc.

 Q2.      What are two internal subtypes of String data in Python?

             The following are two internal subtypes of String data in Python:

(a)  Unicode string – class (str – now in Python 3)

(b)  Byte string – class (byte)

 Q3.      How are str type strings different from Unicode Strings? 

 

Ans.    In Python 2 str type of strings were stored in the form of bytes and Unicode Strings were stored in Unicode code points. But in Python 3, by default all the str type strings are stored in Unicode code points.

 Q4.      What are List and Tuple data types of Python?

 Ans.   The List and Tuple are compound data type in Python.  A list in Python represents a list of comma-separated values of any data type between square brackets. Ex: [4,5,6,7]

             A tuple is also a list of comma-separated values of any data type but placed within parentheses. Ex: (3,4,5,6,7)

 Q5.      How is a list type different from type data type of Python?

 Ans.    The values in a list are placed with square brackets and a list is a mutable data type. Whereas, the values in a tuple are placed within parenthesis and a tuple is an immutable data type.

 Q6.      What are Dictionaries in Python?

 Ans.    Dictionaries are unordered set of comma-separated key:value paints, within curly brackets ({}).

            Example: 

            {‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4}

 Q7.      What do you understand by mutable and immutable objects?

 Ans.    Mutable objects are those whose value can be changed their values in place.

            Ex:  list dictionaries and sets.

 Immutable objects are those that can never change their values in place.

            Ex:  integers, floating point numbers, Booleans, strings tuple.

  

Check Point 3.4      

 Q1.      What is the function of operators? What are arithmetic operators? Give their examples.

 

Ans.    Operators are the symbols or sometimes words that triggers operation/action on data.  Arithmetic operators performed arithmetic operations on the operands.  Ex:  +, -, *, **, %, /, // etc.

 Q2.      How is ‘unary +’ operator different from ‘+’ operator? How is ‘Unary –‘ operator different from ‘-‘ operator?

 Ans.    The ‘unary +’ operator acts on one operand and evaluates the value of the argument.  Whereas, the ‘+’ operator acts on two operands and add the two arguments.

             The ‘unary -’ operator acts on one operand and reverses the sign of the value or the operand.  Whereas the ‘-‘ operator acts on two operands and evaluates the difference of the two values.  

 Q3.      What are binary operators? Give examples of arithmetic binary operators.

 Ans.    Binary operators act upon two operands. Example of binary arithmetic operators are: +, -, *, **, %, /, // etc.

 Q4.      What does the modulus operator % do? What will be the result of 7.2%2.1 and 8%3?

 Ans.    The modulus % operator finds the remainder of its first operand relative to the second. 7.2%2.1 will evaluate to 0.8999999….. and 8%3 will evaluate to 2.

 Q5.      What will be the result of 5.0/3 and 5.0//3?

 Ans.    5.0/3 will yield 1.6666…. as result the 5.0//3 will evaluate to 1.0.

 Q6.      How will you calculate 4.55 in Python?

      Ans.    4.5**5

  Check Point 3.6

 Q1.      What is the function of logical operators? Write the expression involving a logical operator to test if marks are 55 and grade is ‘B’.

 Ans.    Logical operators are symbols or words used to connect two or more expressions.

            Example:  marks==55 and grade==’B’

 Q2.      What is the result of following expression: a>==b and (a+b)>a if

            (i) a=3, b=0    (ii) a=7, b=7

 Ans.    (i) False      (ii) True

 Q3.      a= 15.5, b==15.5 then why is  a is b false while a==b is true.

 Ans.    The ‘==’ operator compare two values of the objects so is evaluates true because the values are same. Whereas, the identity operator ‘is’ compares the memory locations of the objects. The variable ‘a’ and ‘b’ referencing the different memory location of the float number 15.5, therefore it evaluates false.

 Check Point 3.7

 Q1.      What is an expression? How many different types of expressions can you have in Python?

 

Ans.    An expression is a valid combination of atoms and operators. There are different types of expressions in Python e.g. Arithmetic Expression, Relational Expression, Logical Expression, String Expression, etc.

 Q2.      What is atom in context of expression?

 Ans.    Atom in a Python expression could be anything from literals, identifier, and values-in-enclosures like tuples, strings, lists, dictionaries, sets, etc.

 Q3.      What is type conversion (coercion)? How does Python perform it?

 Ans.    In an expression which has different types of data, python automatically converts all operands up to the type of the largest operand without programmer’s intervention, this we called type conversion (coercion) or implicit type conversion.

  

Check Point 3.8

 Q1.      Are the following expressions equal? Why/why not?

(i)            X or y and not z

(ii)          (x or y) and (not z)

(iii)         (x or (y and (not z)))

Ans.    The first and the third expressions are equal because they have same associativity of operators. The second expression is different because of different associativity of the operators.

 Q2.      State when would only first argument be evaluated and when both first and second arguments are evaluated in the following expressions. If a=5, b=10, c=5, d=0.

(i)            b>c and c>d

(ii)          a<=b or c<=d

(iii)         (b+c)<=a and not (c<a)

(iv)         b<d and d<a

 Ans.    (i) both the arguments

            (ii) only the first argument

            (iii) only  the first argument 

            (iv) only the first argument

 

            Reasons:

1. In ‘or’ evaluation, Python only evaluates the second argument if the irst one is falsevalue

2. In ‘and’ evaluation, Python only evaluates the second argument is the first one is truevalue.

Q3.      What is type casting?

 

Ans.    In an expression with values of mixed data types, the programmer can forcefully convert the resultant value to a data type of his choice. This we call type casting or an explicit type conversion.

 

Q4.      How is implicit type conversion different from explicit type conversion?

 

Ans.    In implicit type conversion, python automatically converts all operands up to the type of the largest operand without programmer’s intervention, whereas, in explicit type conversion, the programmer forcefully converts the resultant value to a data type of his choice.

 

 Assignment  

(Note: The questions that have already appeared and been answered above have been skipped here)

Type A : Short Answer Questions.

Q1.      How are these numbers different from one another?  33 ,  33.0, 33j,  33+j

Ans.    33 – integer type , 33.0 floating number type, 33j complex (imaginary part)

            33+j – Not any type 

 

Q2.      The complex numbers have two parts: real and imaginary. In which type are r       real and imaginary parts represented?

 Ans.    Floating point type.

 Q3.      What will the following code print?

            St1 = ‘ ‘ ‘Hell <┘

                        o’’’

            str2 = ‘ ‘ ‘Hell\

                           o’’’

            print(len(str1)>len(str2))

Ans.    True

Q4.      What are three internal key-attributes of a value-variable in Python? Explain with example.

Ans.    A value-variable has the following three attributes.

(a)  The Type of an object: It means data type of the object. Ex: a=5, its type is integer.

(b)  The Value of an object: This is the value the object contains. Ex: a=5, the value it holds is 5.

(c)  The Id of an object: Id of an object is the memory location of the object.

Q5.      Is it true that if two objects return True for is operator, they will also return True for == operator?

Ans.    No, it is not always true that two objects return True for is operator, they will also return True for == operator? It is because the ‘==’ operator compare two values of the objects and the identity operator ‘is’ compares the memory locations of the objects. Python sometimes creates two memory locations for the same value.

Q6.      Are these values equal? Why/why not?

(i)            20 and 20.0                           (ii) 20 and int(20)

(ii)          Str(20) and str(20.0)             (iv) ‘a’ and “a”

 

Ans.    (i)         Yes – because both are the numeric data of same value.      

(iii)         Yes – because both are integer data of same value.

(iv)         No – because both values are strings of different data types.

(v)          Yes – both are same value of same data type

 Q7. What is the difference between implicit type conversion and explicit type conversion?

Ans.    When python automatically converts all operands up to the type of the largest operand without programmer’s intervention, this we called type conversion (coercion) or implicit type conversion.

            When the programmer forcefully converts one type of data to another type, it is called explicit type conversion.

 Q8.      Give str1= “Hello”, what will be the values of?

(a)  str1[0]    (b) str1[1]    (c) str1[-5]     (d) str1[-4]     (e) str1[5]

 Ans.    (a) ‘H’         (b) ‘e’     (c) ‘H’    (d) ‘e’    (e)  Python will report error because index 5 is beyond the given string length.

 Q9.      If you give the following for str1=”Hello”, why does Python report error?

            str1[2]=’p’

 Ans.  Python will report error because strings are immutable data type. We cannot modified strings in place.

 Q10. What are augmented assignment operators? How are they useful?

 Ans.    The augmented assignment operators combine an operator with assignment and allow us to assign new value to the variable after arithmetic calculation is done on the variable and other given values.

           Example:  a+=5, b-=3, etc.

 Q11. Given three Boolean variables a, b, c as: a=False, b=True c=False

            Evaluate the following Boolean expressions:

(a)  a and b     (b)  b or c   (c) not a and b    (d) (a and b) or not c

(e)  not b and not (a or c)  (f) not ((not b or not a ) and c) or a

 Ans.    (a) False      (b) True    (c) True  (d)  True   (e) False (f) True

 Q12.    What would following code fragments result in? Given x=3

(a)  1<x    (b) x>=4   (c) x==3  (d) x==3.0   (e) “Hello” ==”Hello”

(f) “Hello”>”hello” (g) 4/2==2.0   (h) 4/2==2    (i) x<7 and 4>5

 Ans.   (a) True (b) False  (c) True   (d) True)   (e) True (f) False  (g)  True (h) True

(i)            False

 Q13.    Int(‘a’) produces error. Why?

 Ans.    int(‘a’) produces error because ‘a’ is string type and not an integer type of data.

 Q14.    int(‘a’) produces error but following expression having int(‘a’) in it, does not return error. Why?

            len(‘a’)+2 or int(‘a’)

 Ans.    Python does not produce any error in the given expression because the ‘or’ operator does not test the second operand/value if the first one is found to be true(truthiness). Here len(‘a’)+2 is true(it contain some value) so the int(‘a’) is ignored.

 Q15.    Write expression to convert the values 17, len(‘ab’) to

            (i) integer        (ii) str     (iii) Boolean values

 

Ans.    (i) int(17), int(len(‘ab’))  

            (ii) str(17),  str(len(‘ab’))

            (iii) bool(17),  bool(len(‘ab))

 Q16.    Evaluate and justify:  (i) 22/17==37/47+88/83  (ii) len(‘375’)**2

 Ans.   (i)  22/17==37/47+88/83

                 1.2941….  ==  0.7872… + 1.0602

                 1.2941… == 1.7484

                  Both values on left and right are not equal hence will be evaluated – False

             (ii) len(‘375’)**2

                 3**2   (length of the string ‘375’ = 3)

                 9  (3 to power 2 = 9)

 Q17.    Evaluate and justify: (i) False and None  (ii) 0 and None  (iii) True and None

(v)          None and None

 Ans.    (i) False and None è False (the ‘and’ returns the first operand if it is false)

            (ii) 0 and None è 0  (the ‘and’ returns the first operand if it is false)

(iii) True and None è None (nothing will print) (the ‘and’ returns the second  

      operand if the first one is true)

(iv) None and None è None (the ‘and’ returns the first operand if it is false)

 Q18.    Evaluate and justify:

(a)  0 or None and “or”

(b)  1 or None and ‘a’ or ‘b’

(c)  False and 23

(d)  23 and False

(e)  not(1==1 and 0 !=1)

(f)   “abc”==”Abc” and not(2==3 or 3==4)

(g)  False and 1==1 or not True or 1==1 and False or 0==0

 Ans.    (a)           0 or None and “or”

à0 or None    (at first ‘and’ operator will be evaluated ( it has higher

                    precedence than ‘or’ operator) and it will evaluate None)

                     àNone and “or” 

è Will result in None (Nothing will printed – and operator will result the first operand if is false)

 

(b)  1 or None and ‘a’ or ‘b’

è At first None and ‘a’ will result in None ( ‘and’ operator has higher precedence)

è Now the expression becomes

   1 or None or ‘b’

è Now 1 or None will evaluated and will result in

1 (‘or’ operator returns the first operand if is true)

è Now the expression becomes

1 or ‘b’  and will result in  1

 

(c)    False and 23  - this will evaluated to:

False (‘and’ operator returns the first operand if it is false)

 

(d)  23 and False – will evaluated to:

False (‘and’ operator returns the second operand if first one is true)

 

(e)  not(1==1 and 0 !=1)

first the expression within the bracket will evaluated and will become

Not(True and True) (relational operators have higher precedence then and operator)

At next step the expression will become

Not(True)  (True and True = True)

Then it will evaluate to:

False

 

(f)   “abc”==”Abc” and not(2==3 or 3==4)

“abc”== “Abc” and not(False or False)

“abc”== “Abc” and not(False)

“abc” == “Abc” and True

False and True

False

 

(g)  False and 1==1 or not True or 1==1 and False or 0==0

False and True or not True or True and False or True

False or not True or False or True

False or False or False or True

False or False or True

False or True

True

 

Q19.    Write an expression that uses exactly 3 arithmetic operators with integer literals and produces result at 99.

 Ans.  99*2//2   (Note: there may many expression that you can write)

 Q20.    Add parentheses to the following expression to make the order of evaluation more clear

            y%4==0 and y%100 !=0 or y%400==0

 Ans.    (((y%4)==0) and ((y%100) !=0)) or ((y%400)==0))

 Application Based Questions

 Q1. What is the result of produced by (i) bool(0)   9ii) bool(str(0)? Justify the outcome.

 Ans.  (i) False  - the truthiness of 0 is false.

          (ii) True – the truthiness of any string is true. (here 0 is a string data)

 Q2. What will be the output, if input for both the statements is 5+4/2?

            6==input(value 1:”)

            6== int(input(value 2:”)

 Ans.    In the first case the output will be “False”

            In the second case Python will report Error.

 Q3.      Following code has an expression with all integer values. Why is the result in floating point form?

            a, b, c = 2,3,6

            d=a+b*c/b

            print(d)

 Ans.    It is because the division operator ‘/’ always returns the result in floating point form.

 Q4.      What will the following code print?

                 (a)  a = va = 3                                     (b) a =3

b = va = 3                                           b =3.0

print(a,b)                                            print( a==b)

                                                            print (a is b)

 Ans.    (a)  3   3       (b)  True   True

 Q5.      What will be output produced by following code? State reason for this output.

             a, b, c = 1, 1, 2

            d= a+b

            e = 1.0

            f = 1.0

            g = 2.0

            h = e + f

            print (c==d)

            print (c is d)

            print (g==h)

            print (g is h)

 

Ans.    True

            True

            True

            False – for floating point number Python create separate memory locations.

 Q6.      What will be the output produced by following code? State reason.

            a = 5 -4-3

b = 3**2**3

print(a)

print(b)

 Ans.    -2

            6561

 Programming Practice Based Questions

 Q1.Write a program to obtain principal amount, rate of interest and time from user and compute simple interest.

 Ans.

                  amount=int(input('Enter the amount:'))

rate=int(input('Enter the rate:'))

time=int(input('Enter the time:'))

si=(amount*rate*time)/100

print('The simple Interest will be:', si)

 

Q2. Write a program to obtain temperatures of 7 days (Monday to Sunday) and then display average temperature of the week.

 Ans.

                         sum1=0

for b in range(1,8):   

    temp= float(input("Enter the tempratue on ",))

    sum1+=temp

average=sum1/7

print("The average of temperature of 7 days :", average)

 

Q3.  Write a program to obtain x, y , z from user and calculate expression: 4x2+3y3+9z+6π

 

Ans. 

 

            x= int(input("Enter the tempratue on ",))

y= int(input("Enter the tempratue on ",))

z= int(input("Enter the tempratue on ",))

result=4*x**2+3*y**3+9*+6*22/7

print("The average of temperature of 7 days :", result)

 

Q4. Write a program that reads a number of seconds and print in the form : mins and seconds.

 

            x=int(input("Enter the number of second :"))

minute=x//60

second=x%60

print(x, "Seconds makes :", minute, "Minutes and", second, "Seconds")

 

Q5. Write a program that reads from user: (i) an hour between 1 to 12 and (ii) number of hours ahead. The program should then print the time after those many hours.

 

Ans.

 

 

hour=int(input("Enter hour betwee 1-12 :"))

ahead=int(input("How many hours ahead :"))

time= hour+ahead

if time>12:

    time=time-12

print("Time at that time would  :", time, "o'clock")

 

Q6. Write a program to take year as input and check if it is a leap year or not.

 

year=int(input("Enter the year"))

if year%4==0:

                        print("It is a leap year")

else:

                        print ("It is not a leap year")

 Q7. Write a program to take two numbers and print if the first number is fully divisible by second number or not.

 Ans.

 first=int(input("Enter the firt nunber:"))

second=int(input("Enter the second number :"))

if first%second==0:

    print("The first number is completely divisible by the second")

else:

    print("The first number is not divisible by the second number")

 

Q8. Write a program to take a 2-digit number and then print the reversed number.

 

num=int(input("Enter the 2-digit number :"))

ones=num%10

tens=num//10

reverse=ones*10+tens

print("The rverse of number is :", reverse)

 Q9.  Try writing program (similar to previous one) for three digit number and print in reverse order.

 Ans.

 num=int(input("Enter the 2-digit number :"))

ones=num%10

newnum=num//10

tens=newnum%10

reverse=ones*10+tens

hundred=newnum//10

reverse=reverse*10+hundred

print("The rverse of number is :", reverse)

                                                                                                                 

Q10. Write a program to take two inputs for day, month and then calculate which day of the year, the given date is. For simplicity, take 30 days for all months. For example, if you give input as: Day3, Month2 then it should print “Day of the year: 63.

 Ans.

 months=int(input("Enter the number of month :"))

days=int(input("Enter the number of days :"))

sum1=months*30+days

print("Day of the year is :", sum1)

 

 

 

 

 


Comments

Popular posts from this blog

The Road Not Taken

Chapter 4 The Basic Writing Skills

The Fun They Had