Solutions to Quiz 2
CMPT 120, Spring 2005
1. What is a variable?
Ans:
A variable is a name that refers to a value.
or
2. What is a Boolean expression?
Ans: An expression that evaluates to a Boolean value (True or False).
3. List Python's Comparision operators.
Ans: ==, !=, <, >, <=, >=
4. List Python's logical operators.
Ans: and, or, not
5. Are you allowed to use digits in a variable's name? Explain your
answer.
Ans: You can use digits in a variables name. But the name should not start with a digit.
6.
a) What does the following print?
>>> 1 * 2 + 3 * 4
Ans: 14
b) What does the following print?
>>> 1 * (2 + 3) * 4
Ans: 20
c) How do you convert '97' to a number?
Ans: float('97') or int('97')
d) How do you convert the string '58.8' to a number?
Ans: float('58.8')
e) How do you convert the number 7993.64 to a string?
Ans: str(7993.64)
f) What is the difference between 2.6 and "2.6"?
Ans: 2.6 is a floating point number which can be used in
normal mathematical operations.
"2.6" is a string and it cannot be used with
mathematical operations.
7. Write a Python program that calculates and prints on the screen the number of seconds in a year.
Ans:
secs = 60
mins = 60
hrs = 24
days = 365
secs_in_a_year = days * hrs * mins *
secs
print "The number of seconds in a
year are", secs_in_a_year
8. Write a Python program that accepts an integer from the user and prints a message saying if x is divisible by 3 or if it is not.
Ans:
x = raw_input("Enter an
integer: ")
x = int(x)
if x%3 == 0:
print
"The number is divisible by 3"
else:
print
"The number is not divisible by 3"
9. Convert numbers 231 and 24 in binary and add them up.
Ans:
231 = 11100111
24 = 11000
---------------
11111111 = 255
10. Convert number 1110111 to decimal.
Ans: 1 1 1 0 1 1 1
1*26
+ 1*25 + 1*24 + 0*23 + 1*22 +
1*21 + 1*20 =
64 +
32 + 16 +
0 + 4 + 2
+ 1 =
= 119
11. Represent number -3 in two's complement notation. Use for bits.
Ans:
+3 in four bits is: 0011
flip
digits: 1100
(1's complement)
add one:
1101
(2's complement)
Hence, -3 =
1101 in 2's complement notation
Bonus 1: How many positive integers can be represented in 32 bits?
Ans: 232 numbers (if zero is considered as a
positive integer)
Bonus 2: What is the range of integers (positive or negative) that can be
represented in 16 bits?
Ans: -215 to 215 - 1 (-32768 to
32767)