printable version
Test 2 Review B
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
Problem R2b.1.
Why does Python use modules, rather than simply building all
desirable functions into the language?
Building all desirable functions into the language would
introduce a huge number of names that one would want to avoid
when choosing a variable name, since choosing a variable of the
same name would mean that the function of the same name would be
inaccessible.
Alternative answer: Modules provide a mechanism
for people to build libraries of additional functionality beyond
what's built in Python, for others to use in their own Python
programs.
Problem R2b.2.
Write a program that computes and displays the value of the
following expression. (All angles in radians.)
sin 1 + sin 2 + sin 3 + … + sin 10
import math
total = 0
for x in range(1, 11):
total = total + math.sin(x)
print(total)
Problem R2b.3.
The following two code fragments are identical, except that
Fragment A uses elif
where B uses if
.
Give an example value for score
where the
fragments behave differently, and explain the
difference in behavior.
Fragment A |
Fragment B |
if score >= 90:
print('A')
elif score >= 70:
print('C')
else:
print('F')
| if score >= 90:
print('A')
if score >= 70:
print('C')
else:
print('F')
|
If score
is 92, then Fragment A will display just
“A
”, while Fragment B will display
“A
” and “C
” on
separate lines.
(The two fragments behave identically when score
is
below 90.)
Problem R2b.4.
Assume year
is an integer representing a year between 2001 and 2399.
Below, complete the if
statement so that it tests whether
year
represents a leap year.
(Recall that leap years occur when the year is a multiple of 4
but not of 100. You don't need to worry about multiples of
400.)
if
print(str(year) + ' is a leap year.')
if year % 4 == 0 and year % 100 != 0:
print(str(year) + ' is a leap year.')
Problem R2b.5.
Complete the below if
statement
so that the body executes when
the square of x
isn't between 99 and 101.
if :
x = (x + 1.0 / x) / 2.0
if x * x < 99 or x * x > 101
Problem R2b.6.
Suppose we have a vertical line segment from
(lx
,ly0
) to
(lx
,ly1
) (where
ly0
< ly1
).
What should go into an if
statement's condition
to test whether a point
(px
,py
) lies on that line?
if :
print('point on line')
px == lx and py >= ly0 and py <= ly1
Problem R2b.7.
What is the output of the following program?
word = 'quintessential'
line = ''
for i in range(len(word)):
for c in word[:i]:
if c == word[i]:
line = line + c
break
print(line)
senti
Problem R2b.8.
Translate the following program to an equivalent program that
doesn't use a break
statement.
word = input()
c = '(none)'
for i in range(1, len(word)):
if w[i] == w[i - 1]:
c = w[i]
break
print(c)
word = input()
i = 1
while i < len(word) and w[i] != w[i - 1]:
i += 1
if i == len(word):
print('(none)')
else:
print(w[i])