Python - MCQ-II With Answers and Chapter Summaries
Python - MCQ-II With Answers and Chapter Summaries
Literals are data that are entered directly into the string.
code.
An expression produces data. The simplest ex-
Data has type, for example, int (integer), pression is a literal.
float (real number with finite precision), and
str (string, a collection of characters). There are numerous arithmetic operators. Bi-
nary operators (which require two operands) in-
type() returns the type of its argument. clude:
\n is used in a string to indicate the newline Floor division (//) yields a whole number
character. (which may be either an int or a float, de-
pending on the operands). The result is the
Characters in a string may be escaped by pre- largest whole number that does not exceed the
ceding the character with a backslash. This value that would be obtained with float divi-
causes the character to have a different mean- sion.
ing than usual, e.g., a backslash can be placed
before a quotation mark in a string to prevent Modulo (%) yields the remainder (which may
it from indicating the termination of the string; be either an int or a float, depending on
the quotation mark is then treated as part of the the operands) after floor division has been per-
formed.
2.10. REVIEW QUESTIONS 43
An lvalue is a general name for something that A magic number is a numeric literal whose un-
can appear to the left side of the assignment op- derlying meaning is difficult to understand from
erator. It is typically a variable that must be a the code itself. Named constants should be used
valid identifier. in the place of magic numbers.
(a) 7 + 23
(b) 7 + 23 = 30
44 CHAPTER 2. CORE BASICS
(c) 30
(d) This produces an error.
(a) _1_2_3_
(b) ms.NET
(c) WoW
(d) green-day
(e) big!fish
(f) 500_days_of_summer
(a) a1b2c
(b) 1a2b3
(c) a_b_c
(d) _a_b_
(e) a-b-c
(f) -a-b-
(g) aBcDe
(h) a.b.c
4. Suppose the variable x has the value 5 and y has the value 10. After executing these state-
ments:
x = y
y = x
(a) 5 and 10
(b) 10 and 5
(c) 10 and 10
(d) 5 and 5
5. True or False: “x ** 2” yields the identical result that is produced by “x * x” for all
integer and float values of x.
6. True or False: “x ** 2.0” yields the identical result that is produced by “x * x” for all
integer and float values of x.
print(5 + 6 % 7)
8. What is the output from the print() statement in the following code?
x = 3 % 4 + 1
y = 4 % 3 + 1
x, y = x, y
print(x, y)
(a) 2 4
(b) 4 2
(c) 0 3
(d) 3 0
(a) 3 4 7
(b) x y 7
(c) x y x + y
(d) 3 4 x + y
(e) x y 34
For each of the following, determine the value to which the expression evaluates. (Your answer
should distinguish between floats and ints by either the inclusion or exclusion of a decimal
point.)
10. 5.5 - 11 / 2
11. 5.5 - 11 // 2
12. 10 % 7
46 CHAPTER 2. CORE BASICS
13. 7 % 10
14. 3 + 2 * 2
15. 16 / 4 / 2
16. 16 / 4 * 2
19. The following code is executed. What is the output from the print() statement?
x = 15
y = x
x = 20
print(y)
(a) 15
(b) 20
(c) y
(d) x
(e) This produces an error.
2.10. REVIEW QUESTIONS 47
20. The following code is executed. What is the output from the print() statement?
result = "10" / 2
print(result)
(a) 5
(b) 5.0
(c) ’"10" / 2’
(d) This produces an error.
21. The following code is executed. What is the output from the print() statement?
x = 10
y = 20
a, b = x + 1, y + 2
print(a, b)
(a) 10 20
(b) 11 22
(c) ’a, b’
(d) ’x + 1, y + 2’
(e) This produces an error.
26. True or False: If both m and n are ints, then “m / n” and “m // n” both evaluate to
ints.
27. True or False: The following three statements are all equivalent:
x = (3 +
4)
x = 3 + \
4
x = """3 +
4"""
48 CHAPTER 2. CORE BASICS
(a) 14.3
(b) 14.0
(c) 2
(d) 14
(e) 16
30. Assume the float variable ss represents a time in terms of seconds. What is an appropriate
statement to calculate the number of complete minutes in this time (and store the result as an
int in the variable mm)?
(a) mm = ss // 60
(b) mm = ss / 60
(c) mm = ss % 60
(d) mm = ss * 60
31. To what values does the following statement set the variables x and y?
x, y = divmod(13, 7)
(a) 6 and 1
(b) 1 and 6
(c) 6.0 and 2.0
(d) This produces an error.
int(): Returns the integer form of its argu- Functions such as the four listed above can be
ment. nested. Thus, for example, float(input())
can be used to obtain input in string form which
float(): Returns the float form of its ar- is then converted to a float value.
gument.
-2 * 3 + 5
(a) -16
(b) -1
(c) ’-2 * 3 + 5’
(d) This produces an error.
50
(a) ’50 + 1’
(b) 51
(c) 50
(d) This produces an error.
50
(a) ’50 + 1’
(b) 51
(c) 50
(d) This produces an error.
2 + 3 * -4
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
x = float(input("Enter x: "))
print("x =", x)
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
3.5. REVIEW QUESTIONS 63
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
64 CHAPTER 3. INPUT AND TYPE CONVERSION
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
16. True or False: All of the following are acceptable arguments for the int() function: 5,
5.0, "5", and "5.0" (these arguments are an int, a float, and two strs, respectively).
17. True or False: All of the following are acceptable arguments for the float() function: 5,
5.0, "5", and "5.0".
18. True or False: All of the following are acceptable arguments for the eval() function: 5,
5.0, "5", and "5.0".
19. True or False: The string "5.0, 6.0" is an acceptable argument for the eval() function
but not for the float() function.
CONDITIONAL STATEMENTS
2. Consider the following code. When prompted for input, the user enters the string monday.
What is the output?
day = input("What day is it? ")
day = day.lower()
if day != ’saturday’ and day != ’sunday’:
print("Yep.")
else:
print("Nope.")
print(wanted)
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
a = 5
b = -10
if a < b or a < 0 and b < 0:
print("Yes, it’s true.")
else:
print("No, it’s false.")
(a) True
(b) False
11.10. REVIEW QUESTIONS 293
print(is_lower("t"))
(a) True
(b) False
(c) None
(d) This code produces an error
(a) True
(b) False
(c) None
(d) This code produces an error.
data1 = [5, 3, 2, 2, 0]
data2 = [5, 2, 3, 2, 0]
print(monotonic(data1), monotonic(data2))
data = [5, 3, 2, 2, 0]
swapper(data)
print(data)
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
(a) True
(b) False
(c) 0
(d) 10
(a) 4
(b) 1
(c) 0
(d) -1
(e) None of the above.
(a) 4
(b) 1
(c) 0
(d) -1
(e) None of the above.
19. What is the value returned by the function func1() when it is called in the following code?
def func1(xlist):
for x in xlist:
if x < 0:
return False
return True
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
20. What is the value returned by the function func2() when it is called in the following code?
def func2(xlist):
for i in range(len(xlist) - 1):
if xlist[i] + xlist[i + 1] == 0:
return True
return False
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
The template for defining a function is: If comma-separated expressions are given as
part of the return statement, the values of
def <function_name>(<params>): these expressions are returned as a collection of
<body> values that can be used with simultaneous as-
signment. The values are in a tuple as de-
where the function name is a valid identifier, the scribed in Chap. 6.
formal parameters are a comma-separated list
of variables, and the body consists of an arbi- Function definitions may be nested inside other
trary number of statements that are indented to functions. When this is done, the inner function
the same level. is only usable within the body of the function in
which it is defined. Typically such nesting is not
A function is called/invoked by writing the func- used.
tion name followed by parentheses that enclose
the actual parameters which are also known as The scoping rules for functions are the same as
the arguments. for variables. Anything defined inside a func-
tion, including other functions, is local to that
A function that does not explicitly return a value function. Variables and functions defined exter-
is said to be a void function. Void functions re- nal to functions have global scope and are visi-
turn None. ble “everywhere.”
A variable defined as a formal parameter or de- Often programs are organized completely in
fined in the body of the function is not defined terms of functions. A function named main()
is, by convention, often the first function called
outside the function, i.e., the variables only have
local scope. Variables accessible throughout a at the start of a program (but after defining all
program are said to have global scope. the functions). The statements in main() pro-
vide the other function calls that are necessary to
Generally, a function should obtain data via its complete the program. Thus, the program con-
parameters and return data via a return state- sists of a number of function definitions and the
ment. last line of the program file is a call to main().
print() does not return anything (it gener- An optional parameter it created by assigning
ates output) and the return statement does not a default value to the formal parameter in the
print anything (it serves to return a value). header of the function definition.
x, y = f(5)
print(x + y)
(a) 7 10
(b) 17
(c) x + y
(d) This produces an error.
(e) None of the above.
2. True or False: Names that are valid for variables are also valid for functions.
3. What output is produced by the print() statement when the following code is executed?
def calc_q1(x):
q = 4 * x + 1
return q
calc_q1(5)
print(q)
(a) 24
(b) 21
(c) q
(d) This produces an error.
(e) None of the above.
4. What is the value of q after the following code has been executed?
def calc_q2(x):
q = 4 * x + 1
print(q)
q = calc_q2(5)
(a) 24
(b) 21
(c) This produces an error.
(d) None of the above.
5. What is the value of q after the following code has been executed?
q = 20
def calc_q3(x):
q = 4 * x + 1
return q
q = calc_q3(5)
4.10. REVIEW QUESTIONS 89
(a) 24
(b) 21
(c) This produces an error.
(d) None of the above.
6. What is the output produced by the print() statement in the following code?
def calc_q4(x):
q = 4 * x + 1
print(calc_q4(5))
(a) 24
(b) 21
(c) q
(d) This produces an error.
(e) None of the above.
def get_input():
x = float(input("Enter a number: "))
return x
def main():
get_input()
print(x ** 2)
main()
At the prompt the user enters 2. What is the output of this program?
(a) x ** 2
(b) 4
(c) 4.0
(d) This produces an error.
(e) None of the above.
def main():
print(get_input() ** 2)
main()
At the prompt the user enters 2. What is the output of this program?
(a) get_input() ** 2
(b) 4
(c) 4.0
(d) This produces an error.
(e) None of the above.
z = f1(3, 3) + 1
4.10. REVIEW QUESTIONS 91
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
z = f2(3, 3) + 1
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
(e) None of the above.
z = f3(3, 3) + 1
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
(e) None of the above.
z = f3(3) + 1
(a) 3
(b) 3.0
(c) 2
92 CHAPTER 4. FUNCTIONS
x = 10
inc_by_two(x)
print("x = ", x)
lists can be created by enclosing comma- The append() method can be used to ap-
separated expressions in square brackets, e.g., pend its argument to the end of a list. The
[2, "t", 1 + 1]. extend() method can be used to add the ele-
ments of the argument list to the list for
An empty list has no elements, i.e., [] is an which the method is invoked. The sort()
empty list. method sorts the elements of a list in place,
i.e., a new list isn’t created but rather the orig-
Two lists can be concatenated using the + op- inal list is changed.
erator.
An individual element of a list can be ac-
6.11. REVIEW QUESTIONS 133
cessed via an integer index. The index is given spectively. inc may be positive or negative.
in square brackets following the list. The in-
dex represents an offset from the first element; Given a list xlist, range(len(xlist))
hence the first element has an index of 0, e.g., will produce, in order, all the valid indices for
xlist[1] is the second element of xlist. this list.
len(): returns the length of its argument as an The range() function can be used as the iter-
integer. When the argument is a list, len() able in the header of a for-loop. This can be
returns the number of elements. done either to produce a counted loop where the
loop variable is not truly of interest or to pro-
In general, for a list xlist, the last element has duce the valid indices of a list (in which case
an index of len(xlist) - 1. the loop variable is used to access the elements
of the list).
A for-loop uses the following template:
for <item> in <iterable>: list(): returns the list version of its ar-
<body> gument. (This function can be used to obtain
a list containing all the values generated by
where <item> corresponds to the loop vari- the range() function. However, in practice,
able and is any valid identifier (or lvalue), list() is not used with range().)
<iterable> is an object such as a list that
returns data sequentially, and the body is an ar- tuples are similar to lists but the elements
bitrary number of statements that are indented to of a tuple cannot be changed while the ele-
the same level. ments of a list can be, i.e., tuples are im-
mutable while lists are mutable.
range(): function used to produce integers.
The general form is range(start, stop, lists and tuples can be used in simultane-
inc). The integers that are produced start at ous assignments. They appear on the right side
start. Each successive term is incremented of the equal sign and the number of lvalues to
by inc. The final value produced is the “last” the left of the equal sign must equal the number
one before stop. Both inc and start are of elements in the list or tuple.
optional and have default values of 1 and 0, re-
2. True or False: The index for the first element of a list is 1, e.g., xlist[1] is the first
element of the list xlist.
(a) [3, 4]
(b) [[3, 4]]
(c) 3, 4
(d) 3 4
(e) None of the above.
5. What is the value of xlist2 after the following statement has been executed?
xlist2 = list(range(-3, 3))
6. What is the value of xlist3 after the following statement has been executed?
xlist3 = list(range(-3, 3, 3))
(a) [-3, 0, 3]
(b) [-3, 0]
(c) [-2, 1]
(d) This produces an error.
7. What is the value of xlist4 after the following statement has been executed?
xlist4 = list(range(-3))
6.11. REVIEW QUESTIONS 135
(a) []
(b) [-3, -2, -1]
(c) [-3, -2, -1, 0]
(d) This produces an error.
x = multiply_list(1, 4)
(a) 24
(b) 6
(c) 2
(d) 1
True or False: This function returns a list consisting of the two parameters passed to the
function.
11. Consider the following function:
def f2(x, y):
return x, y
136 CHAPTER 6. LISTS AND FOR-LOOPS
True or False: This function returns a list consisting of the two parameters passed to the
function.
True or False: This function returns a list consisting of the two parameters passed to the
function.
True or False: This function prints a list consisting of the two parameters passed to the
function.
True or False: This function prints a list consisting of the two parameters passed to the
function.
(a) 3210
(b) 3 2 1 0
(c) [3, 2, 1, 0]
(d) This produces an error.
(e) None of the above.
a = 1
b = 2
xlist = [a, b, a + b]
a = 0
b = 0
print(xlist)
(a) 10
(b) 12
(c) 4
(d) This produces an error.
(e) None of the above.
(a) aa bb cc
(b) cc bb aa
(c) This produces an error.
(d) None of the above.
(a) [0, 1, 2, 3, 4]
(b) [1, 2, 3, 4, 5]
(c) [0, 1, 2, 3, 4, 5]
(d) None of the above.
21. Which of the following headers is appropriate for implementing a counted loop that executes
4 times?
(a) for i in 4:
(b) for i in range(5):
(c) for i in range(4):
(d) for i in range(1, 4):
main()
(a) 2
4
8
(b) 4
8
(c) 4
8
16
(d) 16
6.11. REVIEW QUESTIONS 139
23. The following fragment of code is in a program. What output does it produce?
fact = 1
for factor in range(4):
fact = fact * factor
print(fact)
(a) 120
(b) 24
(c) 6
(d) 0
24. What is the output from the following program if the user enters 5.
def main():
n = eval(input("Enter an integer: "))
ans = 0
for x in range(1, n):
ans = ans + x
print(ans)
main()
(a) 120
(b) 10
(c) 15
(d) None of the above.
(a) s c o r e
(b) e r o c s
(c) 4 3 2 1 0
(d) None of the above.
26. The following fragment of code is in a program. What output does it produce?
140 CHAPTER 6. LISTS AND FOR-LOOPS
(a) score
(b) erocs
(c) scor
(d) 01234
(e) None of the above.
27. The following fragment of code is in a program. What output does it produce?
s = [’s’, ’c’, ’o’, ’r’, ’e’]
sum = ""
for i in range(len(s)):
sum = s[i] + sum
print(sum)
(a) score
(b) erocs
(c) scor
(d) 01234
(e) None of the above.
28. What is the value returned by the following function when it is called with an argument of 3
(i.e., summer1(3))?
def summer1(n):
sum = 0
for i in range(1, n + 1):
sum = sum + i
return sum
(a) 3
(b) 1
(c) 6
(d) 0
6.11. REVIEW QUESTIONS 141
29. What is the value returned by the following function when it is called with an argument of 4
(i.e., summer2(4))?
def summer2(n):
sum = 0
for i in range(n):
sum = sum + i
return sum
(a) 3
(b) 1
(c) 6
(d) 0
sum = sum + x
return sum
5. Assume xlist is a list of lists where the inner lists have two elements. The second
element of these inner lists is a numeric value. Which of the following will sum the values
of the second element of the nested lists and store the result in sum?
(a) sum = 0
for item in xlist:
sum = sum + item[1]
(b) sum = 0
for one, two in xlist:
sum = sum + two
(c) sum = 0
for i in range(len(xlist)):
sum = sum + xlist[i][1]
(a) 123246369
(b) 0000012302460369
(c) 000012024
(d) None of the above.
(a) a
ba
cba
(b) a
ab
abc
(c) a
ab
(d) This code produces an error.
(a) gasopr
(b) gr
(c) rshpe
(d) rshper
(a)
r
ro
(b) r
ro
row
(c) ro
row
(d) None of the above.
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
(d) None of the above.
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
Strings can be concatenated using the plus oper- • split(): Returns a list of elements
ator. With operator overloading, a string can be obtained by splitting the string apart at the
repeated by multiplying it by an integer. specified substring argument. Default is
to split on whitespace.
Indexing and slicing of strings is the same as for
lists and tuples (but working with charac- • join(): Concatenates the (string) ele-
ters rather than elements). ments of the list argument with a given
string inserted between the elements. The
The len() function returns the number of char- insertion may be any string including an
acters in its string argument. empty string.
• capitalize(), title(), lower(),
The str() function returns the string represen-
upper(), swapcase(): Case meth-
tation of its argument.
ods that return a new string with the case
ASCII provides a mapping of characters to set appropriately.
numeric values. There are a total of 128 • count(): Returns the number of times
ASCII characters, 95 of which are printable (or the substring argument occurs in a given
graphic) characters. string.
The ord() function returns the numeric value • find() and index(): Return the in-
of its character argument. The chr() function dex at which the substring argument oc-
returns the character for its numeric argument. curs within a given string. Optional argu-
ord() and chr() are inverses. ments can be used to specify the range of
the search. find() returns -1 if the sub-
An escape sequence within a string begins with string is not found while index() raises
the backslash character which alters the usual an exception if the substring is not found.
meaning of the adjacent character or characters.
• lstrip(), rstrip(), strip():
For example, ’\n’ is the escape sequence for
Strip whitespace from a given string (from
the newline character.
the left, right, or from both ends, respec-
tively).
9.9. REVIEW QUESTIONS 231
(a) J
(b) e
(c) Jane
(d) a
(a) J
(b) e
(c) Jane
(d) a
(a) Ja
(b) Jan
(c) an
(d) ane
4. What is the output from the following program, if the input is Spam And Eggs?
232 CHAPTER 9. STRINGS
def main():
msg = input("Enter a phrase: ")
for w in msg.split():
print(w[0], end="")
main()
(a) SAE
(b) S A E
(c) S S S
(d) Spam And Eggs
(e) None of the above.
(a) Msssspp
(b) M ssissippi
(c) Mi ssi ssi ppi
(d) M ss ss pp
6. ASCII is
7. What function can be used to get the ASCII value of a given character?
(a) str()
(b) ord()
(c) chr()
(d) ascii()
(e) None of the above.
(a) sens
(b) ens
(c) en
(d) sen
10. What is an appropriate for-loop for writing the characters of the string s, one character per
line?
(a) for ch in s:
print(ch)
(b) for i in range(len(s)):
print(s[i])
(c) Neither of the above.
(d) Both of the above.
11. The following program fragment is meant to be used to find the sum of the ASCII values for
all the characters in a string that the user enters. What is the missing line in this code?
phrase = input("Enter a phrase: ")
ascii_sum = 0 # accumulator for the sum
for ch in phrase:
##### missing line here
print(ascii_sum)
(a) ’A2’
(b) ’C’
(c) 67
(d) An error.
(e) None of the above.
print(s1)
(a) A Toyota
(b) atoyoT A
(c) None of the above.
print(s1)
(a) A Toyota
(b) atoyoT A
(c) None of the above.
print(s1)
9.9. REVIEW QUESTIONS 235
(a) A Toyota
(b) atoyoT A
(c) None of the above.
16. What is the value of z after the following has been executed:
s = ’’
for i in range(-1, 2):
s = s + str(i)
z = int(s)
(a) 0
(b) 2
(c) -1012
(d) -101
(e) This code produces an error.
17. What is the value of ch after the following has been executed?
ch = ’A’
ch_ascii = ord(ch)
ch = chr(ch_ascii + 2)
(a) ’A’
(b) 67
(c) ’C’
(d) This code produces an error.
18. What is the output produced by the print() statement in the following code?
s1 = "I’d rather a bottle in front of me than a frontal lobotomy."
s2 = s1.split()
print(s2[2])
(a) ’
(b) d
(c) rather
(d) a
(e) bottle
19. What is the output produced by the print() statement in the following code?
236 CHAPTER 9. STRINGS
(a) ’
(b) d
(c) rather
(d) a
(e) bottle
(f) None of the above.
20. The variable s contains the string ’cougars’. A programmer wants to change this variable
so that it is assigned the string ’Cougars’. Which of the following will accomplish this?
(a)
s.upper()
(b)
s[0] = ’C’
(c)
s = ’C’ + s[1 : len(s)]
(d)
s.capitalize()
(a) aJ
(b) naJ
(c) na
(d) en
(e) None of the above.
22. After the following commands have been executed, what is the value of x?
s = "this is a test"
x = s.split()
9.9. REVIEW QUESTIONS 237
23. After the following commands have been executed, what is the value of y?
s = "this is a test"
y = s.split("s")
24. Recall that the str() function returns the string equivalent of its argument. What is the
output produced by the following:
a = 123456
s = str(a)
print(s[5] + s[4] + s[3] + s[2])
25. What is the value of count after the following code has been executed?
s = "He said he saw Henry."
count = s.count("he")
(a) 0
(b) 1
(c) 2
(d) 3
(e) None of the above.
26. What is the value of s2 after the following has been executed?
s1 = "Grok!"
s2 = s1[ : -2] + "w."
(a) Grow.
(b) kw.
(c) k!w
(d) None of the above.
27. What is the value of s2 after the following has been executed?
s1 = "Grok!"
s2 = s1[-2] + "w."
(a) Grow.
(b) kw.
(c) k!w
(d) None of the above.
238 CHAPTER 9. STRINGS
28. What is the value of s2 after the following has been executed?
s1 = "Grok!"
s2 = s1[-2 : ] + "w."
(a) kw.
(b) Grow.
(c) k!w
(d) None of the above.
The get() method can be used to obtain the der. (Similar to the sort() method for lists,
value associated with a key. If the key does not the order can be further controlled by providing
exist, by default, get() returns None. How- a key function whose output dictates the values
ever, an optional argument can be provided to to be used for the sorting. Additionally, set-
specify the return value for a non-existent key. ting the optional argument reverse to True
causes sorted() to reverse the order of the
The keys() method returns the keys of a dic- items.)
tionary. When a dictionary is used as an iter-
able (e.g., in the header of a for-loop), by de- The values() method returns the values in
fault the iteration is over the keys. Thus, if d is the dictionary. Thus, if d is a dictionary,
a dictionary, “for k in d:” is equivalent to “for v in d.values():” cycles through
“for k in d.keys()”. the values of the dictionary.
The sorted() function can be used to sort The items() method returns the key-value
the keys of a dictionary. Thus, “for k in pairs in the dictionary.
sorted(d):” cycles through the keys in or-
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
(a) george
(b) washington
(c) dc
(d) This code produces an error.
ANSWERS: 1) b; 2) d; 3) a; 4) b; 5) b; 6) c; 7) a; 8) c; 9) b;
10.3. CHAPTER SUMMARY 251
FILES
The stream position indicates the next A file object can be used as the iterable in a for-
character to be read from a file. When the file loop.
is first opened, the stream position is zero.
The close() method is used to close a file ob-
Contents of a file can be obtained using the fol- ject. It is an error to read from a closed file.
lowing file-object methods:
The write() method can be used to write a
• read(): Returns a string corresponding string to a file.
to the contents of a file from the current
A print() statement can also be used to print
stream position to the end of the file.
to a file (i.e., write a string to a file) using the
• readline(): Returns, as a string, a sin- optional file argument. A file object must be
gle line from a file. provided with this argument.
• readlines(): Returns a list of
strings, one for each line of a file, from the The writelines() method takes a sequence
current stream position to the end of the of strings as its argument and writes them to the
file (newline characters are not removed). given file as a continuous string.
252 CHAPTER 10. READING AND WRITING FILES
(a) list
(b) str
(c) file object
(d) None of the above.
(e) This code produces an error.
For problems 2 through 9, assume the file foo.txt contains the following:
This is
a test.
Isn’t it? I think so.
10. What is contained in the file out.txt after executing the following?
file = open("out.txt", "w")
s = "this"
print(s, "is a test", file=file)
file.close()
11. What is contained in the file out.txt after executing the following?
file = open("out.txt", "w")
s = "this"
file.write(s, "is a test")
file.close()
12. What is contained in the file out.txt after executing the following?
file = open("out.txt", "w")
s = "this"
file.write(s + "is a test")
file.close()
254 CHAPTER 10. READING AND WRITING FILES
13. What is contained in the file out.txt after executing the following?
file = open("out.txt", "w")
s = "this"
file.write("{} {}\n".format(s, "is a test"))
file.close()