Core basics

Input and type converion
Conditional Statements
Function
List and for-loops
More on for-loops_list_iterables
Strings
Dictionaries
Files

2.9 Chapter Summary
Literals are data that are entered directly into the
code.
Data has type, for example, int (integer),
float (real number with finite precision), and
str (string, a collection of characters).
type() returns the type of its argument.
A literal float has a decimal point or contains the power-of-ten exponent indicator e,
e.g., 1.1e2, 11e1, and 110.0 are equivalent

floats.
A literal int does not contain a decimal point
(nor the power-of-ten exponent indicator e).
A literal str is enclosed in either a matching
pair of double or single quotes. Quotation marks
can be repeated three times at the beginning and
end of a string, in which case the string can span
multiple lines.

\n is used in a string to indicate the newline

character.
Characters in a string may be escaped by preceding the character with a backslash. This
causes the character to have a different meaning than usual, e.g., a backslash can be placed
before a quotation mark in a string to prevent
it from indicating the termination of the string;
the quotation mark is then treated as part of the
string.

An expression produces data. The simplest expression is a literal.
There are numerous arithmetic operators. Binary operators (which require two operands) include:
+, – ⇔ addition and subtraction
/, // ⇔ float and floor division
% ⇔ modulo (or remainder)
* ⇔ multiplication
** ⇔ exponentiation
float division (/) yields a float regardless of the types of the operands. For all other
arithmetic operators, only when both operands
are integers does the operation yield an integer.
Said another way, when either or both operands
are floats, the arithmetic operation yields a
float.
Floor division (//) yields a whole number
(which may be either an int or a float, depending on the operands). The result is the
largest whole number that does not exceed the
value that would be obtained with float division.
Modulo (%) yields the remainder (which may
be either an int or a float, depending on
the operands) after floor division has been performed.

CORE BASICS

2.10. REVIEW QUESTIONS 43
divmod(a, b): equivalent to ⇒ a // b,
a % b.
Evaluation of expressions containing multiple
operations follows the rules of precedence to determine the order of operation. Exponentiation
has highest precedence; multiplication, integer
and float division, and modulo have equal
precedence which is below that of exponentiation; addition and subtraction have equal precedence which is below that of multiplication, division, and modulo.
Operations of equal precedence are evaluated
left to right except for exponentiation operations
which are evaluated right to left.
The negative sign (-) and positive sign (+) can
be used as unary operators, e.g., -x changes the
sign of x. The expression +x is valid but has no
effect on the value of x.
Parentheses can be used to change the order or
precedence.

Statements are complete commands.
The equal sign = is the assignment operator.
The value of the expression on the right side of
the equal sign is assigned to the lvalue on the
left side of the equal sign.
An lvalue is a general name for something that
can appear to the left side of the assignment operator. It is typically a variable that must be a
valid identifier.

A variable can also be thought of as a name
within a namespace. A namespace maps names
to their corresponding values (or objects).
followed by any number of letters, digits, and
underscores.

There are 33 keywords that cannot be used as
identifiers.
Augmented operators can be used as shorthand
for assignment statements in which an identifier appears in an arithmetic operation on the left
side of the equal sign and on the the right side
of the assignment operator. For example, x +=
1 is equivalent to x = x + 1.
Simultaneous assignment occurs when multiple comma-separated expressions appear to the
right side of an equal sign and an equal number
of comma-separated lvalues appear to the left
side of the equal sign.
A statement can span multiple lines if it is enclosed in parentheses or if the newline character
at the end of each line of the statement (other
than the last) is escaped using a backslash.
Multiple statements can appear on one line if
they are separated by semicolons.
A magic number is a numeric literal whose underlying meaning is difficult to understand from
the code itself. Named constants should be used
in the place of magic numbers.

2.10 Review Questions

1. What does Python print as a result of this statement:
print(7 + 23)
(a) 7 + 23
(b) 7 + 23 = 30
44 CHAPTER 2. CORE BASICS
(c) 30
(d) This produces an error.

2. Which of the following are valid variable names?
(a) _1_2_3_
(b) ms.NET
(c) WoW
(d) green-day
(e) big!fish
(f) 500_days_of_summer

3. Which of the following are valid identifiers?
(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 statements:
x = y
y = x
what will the values of x and y be, respectively?
(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.

7. What does Python print as a result of this statement?
2.10. REVIEW QUESTIONS 45
print(5 + 6 % 7)
(a) This produces an error.
(b) 5 + 6 % 7
(c) 11
(d) 4

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

9. What is the output produced by the following code?
x = 3
y = 4
print(“x”, “y”, x + y)
(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

17. Given that the following Python statements are executed:
a = 2
b = a + 1 // 2
c = a + 1.0 // 2
d = (a + 1) // 2
e = (a + 1.0) // 2
f = a + 1 / 2
g = (a + 1) / 2
Determine the values to which the variables b through g are set.

18. What output is produced when the following code is executed?
hello = “yo”
world = “dude”
print(hello, world)
(a) hello, world
(b) yo dude
(c) “yo” “dude”
(d) yodude
(e) This produces an error.
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.
22. True or False: In general, “x / y * z” is equal to “x / (y * z)”.
23. True or False: In general, “x / y ** z” is equal to “x / (y ** z)”.
24. True or False: In general, “w + x * y + z” is equal to “(w + x) * (y + z)”.
25. True or False: In general, “w % x + y % z” is equal to “(w % x) + (y % z)”.
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
28. Given that the following Python statements are executed:
x = 3 % 4
y = 4 % 3
What are the values of x and y?
29. To what value is the variable z set by the following code?
z = 13 + 13 // 10
(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.
ANSWERS: 1) c; 2) a and c are valid; 3) a, c, d, and g are valid; 4) c; 5) True; 6) False, if x is an
integer x * x yields an integer while x ** 2.0 yields a float; 7) c; 8) b; 9) b; 10) 0.0; 11)
0.5; 12) 3; 13) 7; 14) 7; 15) 2.0; 16) 8.0; 17) b = 2, c = 2.0, d = 1, e = 1.0, f =
2.5, g = 1.5; 18) b; 19) a; 20) d; 21) b; 22) False (the first expression is equivalent to “x * z
/ y”); 23) True; 24) False; 25) True; 26) False (“m / n” evaluates to a float); 27) False (the
first two are equivalent arithmetic expressions, but the third statement assigns a string to x); 28) 3
and 1; 29) d; 30) a; 31) b.
3.4 Chapter Summary
input(): Prompts the user for input with its
string argument and returns the string the user
enters.
int(): Returns the integer form of its argument.
float(): Returns the float form of its argument.
eval(): Returns the result of evaluating its
string argument as any Python expression, including arithmetic and numerical expressions.
Functions such as the four listed above can be
nested. Thus, for example, float(input())
can be used to obtain input in string form which
is then converted to a float value.
3.5 Review Questions
1. The following code is executed
x = input(“Enter x: “)
In response to the prompt the user enters
INPUT AND TYPE CONVERSION
60 CHAPTER 3. INPUT AND TYPE CONVERSION
-2 * 3 + 5
What is the resulting value of x?
(a) -16
(b) -1
(c) ’-2 * 3 + 5’
(d) This produces an error.
2. The following code is executed
y = int(input(“Enter x: “)) + 1
In response to the prompt the user enters
50
What is the resulting value of y?
(a) ’50 + 1’
(b) 51
(c) 50
(d) This produces an error.
3. The following code is executed
y = int(input(“Enter x: “) + 1)
In response to the prompt the user enters
50
What is the resulting value of y?
(a) ’50 + 1’
(b) 51
(c) 50
(d) This produces an error.
4. The following code is executed
x = input(“Enter x: “)
print(“x =”, x)
In response to the prompt the user enters
3.5. REVIEW QUESTIONS 61
2 + 3 * -4
What is the output produced by the print() statement?
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
5. The following code is executed
x = int(input(“Enter x: “))
print(“x =”, x)
In response to the prompt the user enters
2 + 3 * -4
What is the output produced by the print() statement?
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
6. The following code is executed
x = int(input(“Enter x: “))
print(“x =”, x)
In response to the prompt the user enters
5.0
What is the output produced by the print() statement?
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
7. The following code is executed
62 CHAPTER 3. INPUT AND TYPE CONVERSION
x = float(input(“Enter x: “))
print(“x =”, x)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
8. The following code is executed
x = eval(input(“Enter x: “))
print(“x =”, x)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
9. The following code is executed
x = input(“Enter x: “)
print(“x =”, x)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 5.0
(b) x = 5
(c) This produces an error.
(d) None of the above.
3.5. REVIEW QUESTIONS 63
10. The following code is executed
x = int(input(“Enter x: “))
print(“x =”, x + 1.0)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
11. The following code is executed
x = float(input(“Enter x: “))
print(“x =”, x + 1)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
12. The following code is executed
x = eval(input(“Enter x: “))
print(“x =”, x + 1)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.

64 CHAPTER 3. INPUT AND TYPE CONVERSION- python revision tour class 12 mcq
13. The following code is executed
x = input(“Enter x: “)
print(“x =”, x + 1)
In response to the prompt the user enters
5
What is the output produced by the print() statement?
(a) x = 6.0
(b) x = 6
(c) This produces an error.
(d) None of the above.
14. The following code is executed
x = eval(input(“Enter x: “))
print(“x =”, x)
In response to the prompt the user enters
2 + 3 * -4
What is the output produced by the print() statement?
(a) x = -10
(b) x = -20
(c) x = 2 + 3 * -4
(d) This produces an error.
(e) None of the above.
15. What is produced by the print() statement in the following code?
s = “8 / 4 + 4″
print(s, eval(s), sep=” = “)
What is the resulting value of y?
(a) This produces an error.
(b) 8 / 4 + 4 = 6
(c) 6.0 = 6.0
(d) 8 / 4 + 4 = 6.0
(e) None of the above.
3.6. EXERCISES 65
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.
ANSWERS: 1) c; 2) b; 3) d, the addition is attempted before conversion to an int; 4) c; 5)
d; 6) c; 7) a; 8) b; 9) b; 10) a; 11) a; 12) b; 13) c, cannot add string and integer; 14) a; 15) d; 16)
False; 17) True; 18) False, the argument must be a string; 19) True.
289
11.9 Chapter Summary
Python provides the Boolean literals True and
False.
When used in a conditional statement, all objects are equivalent to either True or False.
Numeric values of zero, empty containers (for
example, empty strings and empty lists),
None, and False itself are considered to be
False. All other objects are considered to be
True.
The bool() function returns either True or
False depending on whether its argument is
equivalent to True or False.
The template for an if statement is
if <test_expression>:
<body>
CONDITIONAL STATEMENTS
290 CHAPTER 11. CONDITIONAL STATEMENTS
The body is executed only if the object returned
by the test expression is equivalent to True.
if statements may have elif clauses and an
else clause. The template for a general conditional statement is
if <test_expression1>:
<body1>
elif <test_expression2>:
<body2>
… # Arbitrary number
… # of elif clauses.
else:
<bodyN>
The body associated with the first test expression to return an object equivalent to True is
executed. No other body is executed. If none of
the test expressions returns an object equivalent
to True, the body associated with the else
clause, when present, is executed. The else
clause is optional.
The comparison, or relational, operators compare the values of two operands and return
True if the implied relationship is true. The
comparison operators are: less than (<), less
than or equal to (<=), greater than (>), greater
than or equal to (>=), equal to (==), and not
equal to (!=).
The logical operators and and or take two
operands. and produces a True value only
if both its operands are equivalent to True.
or produces a True value if either or both its
operands are equivalent to True. The logical
operator not is a unary operator that negates the
value of its operand.
All comparison operators have higher precedence than logical operators. not has higher
precedence than and, and and has higher
precedence than or. Parentheses can be used to
change the order of precedence of these operators. All math operators have higher precedence
than both comparison and logical operators.
and and or use “shortcircuit” behavior. In
expressions involving and or or, Python only
evaluates as much as needed to determine the final outcome. The return value is the object that
determines the outcome.
The template for a while-loop is:
while <test_expression>:
<body>
The test expression is checked. If it is equivalent to True, the body is executed. The test
expression is checked again and the process is
repeated.
A break statement terminates the current loop.
A continue statement causes the remainder
of a loop’s body to be skipped in the current iteration of the loop.
Both break and continue statements can be
used with either for-loops or while-loops.
The in operator returns True if the left
operand is contained in the right operand and returns False otherwise.
11.10 Review Questions
1. Consider the following code. When prompted for input, the user enters the string SATURDAY.
What is the output?
day = input(“What day is it? “)
day = day.lower()
11.10. REVIEW QUESTIONS 291
if day == ’saturday’ or day == ’sunday’:
print(“Play!”)
else:
print(“Work.”)
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.”)
3. Consider the following code. What is the output?
values = [-3, 4, 7, 10, 2, 6, 15, -300]
wanted = []
for value in values:
if value > 3 and value < 10:
wanted.append(value)
print(wanted)
4. What is the output generated by the following code?
a = 5
b = 10
if a < b or a < 0 and b < 0:
print(“Yes, it’s true.”)
else:
print(“No, it’s false.”)
5. What is the value of x after the following code executes?
x = 2 * 4 – 8 == 0
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
6. What is the output generated by the following code?
292 CHAPTER 11. CONDITIONAL STATEMENTS
a = 5
b = -10
if a < b or a < 0 and b < 0:
print(“Yes, it’s true.”)
else:
print(“No, it’s false.”)
7. What is the output generated by the following code?
a = -5
b = -10
if (a < b or a < 0) and b < 0:
print(“Yes, it’s true.”)
else:
print(“No, it’s false.”)
8. What is the output produced by the following code?
a = [1, ’hi’, False, ’’, -1, [], 0]
for element in a:
if element:
print(’T’, end=” “)
else:
print(’F’, end=” “)
9. Consider the following conditional expression:
x > 10 and x < 30
Which of the following is equivalent to this?
(a) x > 10 and < 30
(b) 10 < x and 30 > x
(c) 10 > x and x > 30
(d) x <= 10 or x >= 30
10. To what value is c set by the following code?
a = -3
b = 5
c = a <= (b – 8)
(a) True
(b) False
11.10. REVIEW QUESTIONS 293
(c) This code produces an error.
11. What is the output produced by the following code?
def is_lower(ch):
return ’a’ <= ch and ch <= ’z’
print(is_lower(“t”))
(a) True
(b) False
(c) None
(d) This code produces an error
12. What is the output produced by the following code?
def is_there(names, query):
for name in names:
if query == name:
return True
print(is_there([’Jake’, ’Jane’, ’Alice’], ’Tom’))
(a) True
(b) False
(c) None
(d) This code produces an error.
13. What output is produced by the following code?
def monotonic(xlist):
for i in range(len(xlist) – 1):
if xlist[i] < xlist[i + 1]:
return False
return True
data1 = [5, 3, 2, 2, 0]
data2 = [5, 2, 3, 2, 0]
print(monotonic(data1), monotonic(data2))
(a) True True
(b) True False
(c) False True
294 CHAPTER 11. CONDITIONAL STATEMENTS
(d) False False
(e) None of the above.
14. What output is produced by the following code?
def swapper(xlist):
for i in range(len(xlist) – 1):
if xlist[i] > xlist[i + 1]:
# Swap values.
xlist[i], xlist[i + 1] = xlist[i + 1], xlist[i]
data = [5, 3, 2, 2, 0]
swapper(data)
print(data)
15. What is the value of x after the following code executes?
y = 10
x = 2 * 4 – 8 or y
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
16. What is the value of x after the following code executes?
y = 10
if 2 * 4 – 8:
x = 2 * 4 – 8
else:
x = y
(a) True
(b) False
(c) 0
(d) 10
17. What is the value of x after the following code executes?
x = 4
while x > 0:
print(x)
x = x – 1
11.10. REVIEW QUESTIONS 295
(a) 4
(b) 1
(c) 0
(d) -1
(e) None of the above.
18. What is the value of x after the following code executes?
x = 4
while x == 0:
print(x)
x = x – 1
(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
func1([5, 2, -7, 7])
(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
func2([5, 2, -7, 7])

 Python basics python loop python basic statement python mcq , python revision tour class 12 mcq

296 CHAPTER 11. CONDITIONAL STATEMENTS
(a) True
(b) False
(c) None of the above.
(d) This code produces an error.
ANSWERS: 1) Play!; 2) Yep.; 3) [4, 7, 6]; 4) Yes, it’s true.; 5) a; 6) No,
it’s false.; 7) Yes, it’s true.; 8) T T F F T F F; 9) b; 10) a; 11) a; 12) c; 13) b;
14) [3, 2, 2, 0, 5]; 15) c (it is 10); 16) d; 17) c; 18) a; 19) b; 20) a.
The template for defining a function is:
def <function_name>(<params>):
<body>
where the function name is a valid identifier, the
formal parameters are a comma-separated list
of variables, and the body consists of an arbitrary number of statements that are indented to
the same level.
A function is called/invoked by writing the function name followed by parentheses that enclose
the actual parameters which are also known as
the arguments.
A function that does not explicitly return a value
is said to be a void function. Void functions return None.
A variable defined as a formal parameter or defined in the body of the function is not defined
outside the function, i.e., the variables only have
local scope. Variables accessible throughout a
program are said to have global scope.
Generally, a function should obtain data via its
parameters and return data via a return statement.
print() does not return anything (it generates output) and the return statement does not
print anything (it serves to return a value).
If comma-separated expressions are given as
part of the return statement, the values of
these expressions are returned as a collection of
values that can be used with simultaneous assignment. The values are in a tuple as described in Chap. 6.
Function definitions may be nested inside other
functions. When this is done, the inner function
is only usable within the body of the function in
which it is defined. Typically such nesting is not
used.
The scoping rules for functions are the same as
for variables. Anything defined inside a function, including other functions, is local to that
function. Variables and functions defined external to functions have global scope and are visible “everywhere.”
Often programs are organized completely in
terms of functions. A function named main()
is, by convention, often the first function called
at the start of a program (but after defining all
the functions). The statements in main() provide the other function calls that are necessary to
complete the program. Thus, the program consists of a number of function definitions and the
last line of the program file is a call to main().
An optional parameter it created by assigning
a default value to the formal parameter in the
4.10 Review Questions
1. The following code is executed
def f(x):
return x + 2, x * 2
x, y = f(5)
print(x + y)
What is the output produced by the print() statement?
FUNCTION
88 CHAPTER 4. FUNCTIONS
(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.
7. What is the output of the print() statement in the following code?
abc = 5 + 6 // 12
print(abc)
(a) This produces an error.
(b) 5 + 6 // 12
(c) 5
(d) 5.5
(e) 6
8. What is the output of the print() statement in the following code?
def = 5 + 6 % 7
print(def)
(a) This produces an error.
(b) 5 + 6 % 7
(c) 11
(d) 4
9. The following code is executed:
90 CHAPTER 4. FUNCTIONS
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.
10. The following code is executed:
def get_input():
x = float(input(“Enter a number: “))
return x
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.
11. What is the value of z after the following code is executed?
def f1(x, y):
print((x + 1) / (y – 1))
z = f1(3, 3) + 1
4.10. REVIEW QUESTIONS 91
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
12. What is the value of z after the following code is executed?
def f2(x, y):
return (x + 1) / (y – 1)
z = f2(3, 3) + 1
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
(e) None of the above.
13. What is the value of z after the following code is executed?
def f3(x, y = 2):
return (x + 1) / (y – 1)
z = f3(3, 3) + 1
(a) 3
(b) 3.0
(c) 2
(d) This produces an error.
(e) None of the above.
14. What is the value of z after the following code is executed?
def f3(x, y = 2):
return (x + 1) / (y – 1)
z = f3(3) + 1
(a) 3
(b) 3.0
(c) 2
92 CHAPTER 4. FUNCTIONS
(d) This produces an error.
(e) None of the above.
15. The following code is executed.
def inc_by_two(x):
x = x + 2
return x
x = 10
inc_by_two(x)
print(“x = “, x)
What is the output produced by the print() statement?
ANSWERS: 1) b; 2) True; 3) d, q is not defined outside of the function; 4) d, the function is a
void function and hence q is None; 5) b; 6) e, the output is None since this is a void function; 7)
c; 8) a, def is a keyword and we cannot assign a value to it; 9) d, the variable x is not defined in
main(); 10) c; 11) d, f1() is a void function; 12) b; 13) b; 14) e, z would be assigned 5.0; 15)
x = 10.
6.10 Chapter Summary
A list is a sequential collection of data. The
data can differ in terms of type, i.e., a list can
be inhomogeneous.
lists can be created by enclosing commaseparated expressions in square brackets, e.g.,
[2, “t”, 1 + 1].
An empty list has no elements, i.e., [] is an
empty list.
Two lists can be concatenated using the + operator.
Repetition of a list can be obtained using the
* operator (where one of the operands is a list
and the other is an integer).
The append() method can be used to append its argument to the end of a list. The
extend() method can be used to add the elements of the argument list to the list for
which the method is invoked. The sort()
method sorts the elements of a list in place,
i.e., a new list isn’t created but rather the original list is changed.
An individual element of a list can be acLISTS AND FOR-LOOPS
6.11. REVIEW QUESTIONS 133
cessed via an integer index. The index is given
in square brackets following the list. The index represents an offset from the first element;
hence the first element has an index of 0, e.g.,
xlist[1] is the second element of xlist.
len(): returns the length of its argument as an
integer. When the argument is a list, len()
returns the number of elements.
In general, for a list xlist, the last element has
an index of len(xlist) – 1.
A for-loop uses the following template:
for <item> in <iterable>:
<body>
where <item> corresponds to the loop variable and is any valid identifier (or lvalue),
<iterable> is an object such as a list that
returns data sequentially, and the body is an arbitrary number of statements that are indented to
the same level.
range(): function used to produce integers.
The general form is range(start, stop,
inc). The integers that are produced start at
start. Each successive term is incremented
by inc. The final value produced is the “last”
one before stop. Both inc and start are
optional and have default values of 1 and 0, respectively. inc may be positive or negative.
Given a list xlist, range(len(xlist))
will produce, in order, all the valid indices for
this list.
The range() function can be used as the iterable in the header of a for-loop. This can be
done either to produce a counted loop where the
loop variable is not truly of interest or to produce the valid indices of a list (in which case
the loop variable is used to access the elements
of the list).
list(): returns the list version of its argument. (This function can be used to obtain
a list containing all the values generated by
the range() function. However, in practice,
list() is not used with range().)
tuples are similar to lists but the elements
of a tuple cannot be changed while the elements of a list can be, i.e., tuples are immutable while lists are mutable.
lists and tuples can be used in simultaneous assignments. They appear on the right side
of the equal sign and the number of lvalues to
the left of the equal sign must equal the number
of elements in the list or tuple.
6.11 Review Questions
1. True or False: The length of a list is given by the length() function.
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.
3. What is the output produced by the following code?
xlist = []
xlist.append(5)
xlist.append(10)
print(xlist)
134 CHAPTER 6. LISTS AND FOR-LOOPS
(a) [5, 10]
(b) []
(c) 5, 10
(d) 5 10
(e) This produces an error.
(f) None of the above.
4. What is the output produced by the following code?
zlist = []
zlist.append([3, 4])
print(zlist)
(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))
(a) [-3, -2, -1, 0, 1, 2, 3]
(b) [-3, -2, -1, 0, 1, 2]
(c) [-2, -1, 0, 1, 2]
(d) [-3, 0, 3]
(e) This produces an error.
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.
8. What is output produced by the following?
xlist = [2, 1, 3]
ylist = xlist.sort()
print(xlist, ylist)
(a) [2, 1, 3] [1, 2, 3]
(b) [3, 2, 1] [3, 2, 1]
(c) [1, 2, 3] [2, 1, 3]
(d) [1, 2, 3] None
(e) This produces an error.
9. To what value is the variable x set by the following code?
def multiply_list(start, stop):
product = 1
for element in range(start, stop):
product = product * element
return product
x = multiply_list(1, 4)
(a) 24
(b) 6
(c) 2
(d) 1
10. Consider the following function:
def f1(x, y):
print([x, y])
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.
12. Consider the following function:
def f3(x, y):
print(x, y)
return [x, y]
True or False: This function returns a list consisting of the two parameters passed to the
function.
13. Consider the following function:
def f4(x, y):
return [x, y]
print(x, y)
True or False: This function prints a list consisting of the two parameters passed to the
function.
14. Consider the following function:
def f5(x, y):
return [x, y]
print([x, y])
True or False: This function prints a list consisting of the two parameters passed to the
function.
15. What output is produced by the following code?
xlist = [3, 2, 1, 0]
for item in xlist:
print(item, end=” “)
(a) 3210
(b) 3 2 1 0
(c) [3, 2, 1, 0]
(d) This produces an error.
(e) None of the above.
16. What output is produced by the following code?
6.11. REVIEW QUESTIONS 137
a = 1
b = 2
xlist = [a, b, a + b]
a = 0
b = 0
print(xlist)
(a) [a, b, a b]+
(b) [1, 2, 3]
(c) [0, 0, 0]
(d) This produces an error.
(e) None of the above.
17. What output is produced by the following code?
xlist = [3, 5, 7]
print(xlist[1] + xlist[3])
(a) 10
(b) 12
(c) 4
(d) This produces an error.
(e) None of the above.
18. What output is produced by the following code?
xlist = [“aa”, “bb”, “cc”]
for i in [2, 1, 0]:
print(xlist[i], end=” “)
(a) aa bb cc
(b) cc bb aa
(c) This produces an error.
(d) None of the above.
19. What does the following code do?
for i in range(1, 10, 2):
print(i)
138 CHAPTER 6. LISTS AND FOR-LOOPS
(a) Prints all odd numbers in the range [1, 9].
(b) Prints all numbers in the range [1, 9].
(c) Prints all even numbers in the range [1, 10].
(d) This produces an error.
20. What is the result of evaluating the expression list(range(5))?
(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):
22. Consider the following program:
def main():
num = eval(input(“Enter a number: “))
for i in range(3):
num = num * 2
print(num)
main()
Suppose the input to this program is 2, what is the output?
(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.
25. What is the output from the following code?
s = [’s’, ’c’, ’o’, ’r’, ’e’]
for i in range(len(s) – 1, -1, -1):
print(s[i], end = ” “)
(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
s = [’s’, ’c’, ’o’, ’r’, ’e’]
sum = 0
for i in range(len(s)):
sum = sum + s[i]
print(sum)
(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
30. Consider the following function:
def foo():
xlist = []
for i in range(4):
x = input(“Enter a number: “)
xlist.append(x)
return xlist
Which of the following best describes what this function does?
(a) It returns a list of four numbers that the user provides.
(b) It returns a list of four strings that the user provides.
(c) It returns a list of three numbers that the user provides.
(d) It produces an error.
ANSWERS: 1) False; 2) False; 3) a; 4) b; 5) b; 6) b; 7) a; 8) d; 9) d (the return statement
is in the body of the loop); 10) False (this is a void function); 11) False (this function returns a
tuple); 12) True; 13) False (print() statement comes after the return statement and thus
will not be executed); 14) False; 15) b; 16) b; 17) d; 18) b; 19) a; 20) a; 21) c; 22) d; 23) d; 24) b;
25) b; 26) e; 27) b; 28) b; 29) c; 30) b.
7.8 Chapter Summary
One for-loop can be nested inside another.
One list can be nested inside another. Elements of the outer list are specified by one
index enclosed in brackets. An element of an interior list is specified by two indices enclosed
in two pairs of brackets. The first index specifies the outer element and the second element
specifies the inner element. For example, if x
corresponds to the list [[1, 2], [’a’,
’b’, ’c’]], then x[1] corresponds to
[’a’, ’b’, ’c’] and x[1][2] corresponds to ’c’.
Nesting can be done to any level. Specification
of an element at each level requires a separate
MORE ON FOR-LOOPS_LIST_ITERABLES
172 CHAPTER 7. MORE ON FOR-LOOPS, LISTS, AND ITERABLES
index.
Simultaneous assignment can be used to assign
values to multiple loop variables in the header
of a for-loop.
lists are mutable, i.e., the elements of a list
can be changed without creating a new list.
When a list is assigned to a variable, the variable becomes a reference (or alias) to the list.
If one list variable is assigned to another, both
variables point to the same underlying list.
When a list is changed, it is changed globally.
Strings can be used as the iterable in a forloop header in which case the loop variable is
assigned the individual characters of the string.
Negative indexing can be used to specify an element of a sequence (e.g., a string, list, or
tuple). The last element of a sequence has an
index of -1. The first element of a sequence s
has an index of -len(s).
Slicing is used to obtain a portion of a sequence.
For a sequence s a slice is specified by
s[<start> : <end>]
or
s[<start> : <end> : <inc>]
The resulting sequence takes elements from s
starting at an index of <start> and going up
to, but not including, <end>. The increment
between successive elements is <inc> which
defaults to 1. The start and end values can be
specified with either positive or negative indexing. <start> defaults to 0. <end> defaults to
the length of the sequence. inc may be negative. When it is negative, the default <start>
is -1 and the default <end> is -len(s) – 1.
Reversal of a sequence can be achieved using [
: : -1], and a list, e.g., xlist, can be
copied using xlist[ : ].
7.9 Review Questions
1. What output isproduced by the following code?
xlist = [1, [1, 2], [1, 2, 3]]
print(xlist[1])
2. What output is produced by the following code?
xlist = [1, [1, 2], [1, 2, 3]]
print(xlist[1][1])
3. What output is produced by the following code?
xlist = [1, [1, 2], [1, 2, 3]]
print(xlist[1] + [1])
4. What output is produced by the following code?
def sum_part(xlist, n):
sum = 0
for x in xlist[n]:
7.9. REVIEW QUESTIONS 173
sum = sum + x
return sum
ylist = [[1, 2], [3, 4], [5, 6], [7, 8]]
x = sum_part(ylist, 2)
print(x)
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]
(d) All of the above.
6. What output is produced by the following code?
for i in range(3):
for j in range(3):
print(i * j, end=””)
(a) 123246369
(b) 0000012302460369
(c) 000012024
(d) None of the above.
7. What output is produced by the following code?
s = “abc”
for i in range(1, len(s) + 1):
sub = “”
for j in range(i):
sub = s[j] + sub
print(sub)
174 CHAPTER 7. MORE ON FOR-LOOPS, LISTS, AND ITERABLES
(a) a
ba
cba
(b) a
ab
abc
(c) a
ab
(d) This code produces an error.
8. What output is produced by the following code?
s = “grasshopper”
for i in range(1, len(s), 2):
print(s[i], end=””)
(a) gasopr
(b) gr
(c) rshpe
(d) rshper
9. What output is produced by the following code?
x = [7]
y = x
x[0] = x[0] + 3
y[0] = y[0] – 5
print(x, y)
10. What output is produced by the following code?
x = [7]
y = x
x = [8]
print(x, y)
11. What output is produced by the following code?
x = [1, 2, 3, 4]
y = x
y[2] = 0
z = x[1 : ]
x[1] = 9
print(x, y, z)
7.9. REVIEW QUESTIONS 175
12. What output is produced by the following code?
s = “row”
for i in range(len(s)):
print(s[ : i])
(a)
r
ro
(b) r
ro
row
(c) ro
row
(d) None of the above.
13. What output is produced by the following code?
s = “stab”
for i in range(len(s)):
print(s[i : 0 : -1])
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
(d) None of the above.
14. What output is produced by the following code?
s = “stab”
for i in range(len(s)):
print(s[i : -5 : -1])
176 CHAPTER 7. MORE ON FOR-LOOPS, LISTS, AND ITERABLES
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
(d) None of the above.
15. What output is produced by the following code?
s = “stab”
for i in range(len(s)):
print(s[0 : i : 1])
(a) s
ts
ats
bats
(b)
t
at
bat
(c)
s
st
sta
(d) None of the above.
ANSWERS: 1) [1, 2]; 2) 2; 3) [1, 2, 1]; 4) 11; 5) d; 6) c; 7) a; 8) c; 9) [5] [5];
10) [8] [7]; 11) [1, 9, 0, 4] [1, 9, 0, 4] [2, 0, 4]; 12) a; 13) b; 14) a; 15)
c.
9.8 Chapter Summary
Strings are immutable, i.e., they cannot be
changed (although an identifier assigned to a
string variable can be assigned to a new string).
Strings can be concatenated using the plus operator. With operator overloading, a string can be
repeated by multiplying it by an integer.
Indexing and slicing of strings is the same as for
lists and tuples (but working with characters rather than elements).
The len() function returns the number of characters in its string argument.
The str() function returns the string representation of its argument.
ASCII provides a mapping of characters to
numeric values. There are a total of 128
ASCII characters, 95 of which are printable (or
graphic) characters.
The ord() function returns the numeric value
of its character argument. The chr() function
returns the character for its numeric argument.
ord() and chr() are inverses.
An escape sequence within a string begins with
the backslash character which alters the usual
meaning of the adjacent character or characters.
For example, ’\n’ is the escape sequence for
the newline character.
Strings have many methods including the following, where “a given string” means the string
on which the method is invoked:
• split(): Returns a list of elements
obtained by splitting the string apart at the
specified substring argument. Default is
to split on whitespace.
• join(): Concatenates the (string) elements of the list argument with a given
string inserted between the elements. The
insertion may be any string including an
empty string.
• capitalize(), title(), lower(),
upper(), swapcase(): Case methods that return a new string with the case
set appropriately.
• count(): Returns the number of times
the substring argument occurs in a given
string.
• find() and index(): Return the index at which the substring argument occurs within a given string. Optional arguments can be used to specify the range of
the search. find() returns -1 if the substring is not found while index() raises
• lstrip(), rstrip(), strip():
Strip whitespace from a given string (from
the left, right, or from both ends, respectively).
STRINGS
9.9. REVIEW QUESTIONS 231
• replace(): Replaces an “old” substring with a “new” substring in a given
string.
• repr (): Returns a string that shows
the “official” representation of a given
string (useful for debugging purposes
when not in an interactive environment).
• format(): Allows fine-grain control
over the appearance of an object within a
string. Used for formatting output.
9.9 Review Questions
1. What is printed by the following Python fragment?
s = “Jane Doe”
print(s[1])
(a) J
(b) e
(c) Jane
(d) a
2. What is printed by the following Python fragment?
s = “Jane Doe”
print(s[-1])
(a) J
(b) e
(c) Jane
(d) a
3. What is printed by the following Python fragment?
s = “Jane Doe”
print(s[1:3])
(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.
5. What is the output of this program fragment?
for x in “Mississippi”.split(“i”):
print(x, end=””)
(a) Msssspp
(b) M ssissippi
(c) Mi ssi ssi ppi
(d) M ss ss pp
6. ASCII is
(a) a standardized encoding of written characters as numeric codes.
(b) an encryption system for keeping information private.
(c) a way of representing numbers using binary.
(d) computer language used in natural language processing.
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.
8. What is output produced by the following?
9.9. REVIEW QUESTIONS 233
1 s = “absense makes the brain shrink”
2 x = s.find(“s”)
3 y = s.find(“s”, x + 1)
4 print(s[x : y])
(a) sens
(b) ens
(c) en
(d) sen
9. One difference between strings and lists in Python is that
(a) strings are sequences, but lists aren’t.
(b) lists can be indexed and sliced, but strings can’t.
(c) lists are mutable (changeable), but strings immutable (unchangeable).
(d) strings can be concatenated, but lists can’t.
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) ascii_sum = ascii_sum + ch
(b) ascii_sum = chr(ch)
(c) ascii_sum = ascii_sum + chr(ch)
(d) ascii_sum = ascii_sum + ord(ch)
234 CHAPTER 9. STRINGS
12. What is the result of evaluating the expression chr(ord(’A’) + 2)?
(a) ’A2’
(b) ’C’
(c) 67
(d) An error.
(e) None of the above.
13. What is the output of the following code?
s0 = “A Toyota”
s1 = “”
for ch in s0:
s1 = ch + s1
print(s1)
(a) A Toyota
(b) atoyoT A
(c) None of the above.
14. What is the output of the following code?
s0 = “A Toyota”
s1 = “”
for ch in s0[ : : -1]:
s1 = ch + s1
print(s1)
(a) A Toyota
(b) atoyoT A
(c) None of the above.
15. What is the output of the following code?
s0 = “A Toyota”
s1 = “”
for ch in s0[-1 : 0 : -1]:
s1 = s1 + ch
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
s1 = “I’d\nrather 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
(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()
(e) All of the above.
(f) None of the above.
21. What output is produced by the following code?
1 s = “Jane Doe”
2 print(s[1 : 3: -1])
(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.
ANSWERS: 1) d; 2) b; 3) c; 4) a; 5) a; 6) a; 7) b; 8) d; 9) c; 10) d; 11) d; 12) b; 13) b; 14)
a; 15) c; 16) d; 17) c; 18) d; 19) d; 20) c; 21) e; 22) [’this’, ’is’, ’a’, ’test’]; 23)
[’thi’, ’ i’, ’ a te’, ’t’]; 24) 6543; 25) b; 26) a; 27) b; 28) d.
14.4 Chapter Summary
Dictionaries consist of key-value pairs. Any object consisting of immutable components can be
used as a key. Values may be any object. Dictionaries themselves are mutable.
Dictionaries are unordered collections of data
(i.e., they are not sequences).
The value associated with a given key can be obtained by giving the dictionary name followed
by the key enclosed in square brackets. For example, for the dictionary d, the value associated
with the key k is given by d[k]. It is an error
to attempt to access a non-existent key this way.
DICTIONARIES
344 CHAPTER 14. DICTIONARIES
The get() method can be used to obtain the
value associated with a key. If the key does not
exist, by default, get() returns None. However, an optional argument can be provided to
specify the return value for a non-existent key.
The keys() method returns the keys of a dictionary. When a dictionary is used as an iterable (e.g., in the header of a for-loop), by default the iteration is over the keys. Thus, if d is
a dictionary, “for k in d:” is equivalent to
“for k in d.keys()”.
The sorted() function can be used to sort
the keys of a dictionary. Thus, “for k in
sorted(d):” cycles through the keys in order. (Similar to the sort() method for lists,
the order can be further controlled by providing
a key function whose output dictates the values
to be used for the sorting. Additionally, setting the optional argument reverse to True
causes sorted() to reverse the order of the
items.)
The values() method returns the values in
the dictionary. Thus, if d is a dictionary,
“for v in d.values():” cycles through
the values of the dictionary.
The items() method returns the key-value
pairs in the dictionary.
14.5 Review Questions
1. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
print(d[’c’])
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
2. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
print(d[2])
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
3. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
print(d.get(2, ’c’))
14.5. REVIEW QUESTIONS 345
(a) c
(b) 2
(c) ’c’ : 2
(d) This code produces an error.
4. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
for x in sorted(d):
print(d[x], end=” “)
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
5. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
for x in sorted(d.values()):
print(x, end=” “)
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
6. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
for x in sorted(d.items()):
print(x, end=” “)
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
7. What is the output produced by the following code?
d = {’a’ : 0, ’b’: 1, ’c’ : 2}
for x in sorted(d.keys()):
print(x, end=” “)
346 CHAPTER 14. DICTIONARIES
(a) a b c
(b) 0 1 2
(c) (’a’, 0) (’b’, 1) (’c’, 2)
(d) This code produces an error.
8. What is the output produced by the following code?
pres = {’george’ : ’washington’, ’thomas’ : ’jefferson’,
print(pres.get(’washington’, ’dc’))
(a) george
(b) washington
(c) dc
(d) This code produces an error.
9. What is the output produced by the following code?
pres = {’george’ : ’washington’, ’thomas’ : ’jefferson’,
for p in sorted(pres):
print(p, end=” “)
(a) george thomas john
(b) george john thomas
(e) None of the above.
ANSWERS: 1) b; 2) d; 3) a; 4) b; 5) b; 6) c; 7) a; 8) c; 9) b;
10.3. CHAPTER SUMMARY 251
10.3 Chapter Summary
Files are opened for reading or writing using the
open() function. The first argument is the file
name and the second is the mode (’r’ for read,
’w’ for write). Returns a file object.
The stream position indicates the next
character to be read from a file. When the file
is first opened, the stream position is zero.
Contents of a file can be obtained using the following file-object methods:
• read(): Returns a string corresponding
to the contents of a file from the current
stream position to the end of the file.
• readline(): Returns, as a string, a single line from a file.
• readlines(): Returns a list of
strings, one for each line of a file, from the
current stream position to the end of the
file (newline characters are not removed).
If the stream position is at the end of a
strings while readlines() returns an empty
list.
A file object can be used as the iterable in a forloop.
The close() method is used to close a file object. It is an error to read from a closed file.
The write() method can be used to write a
string to a file.
A print() statement can also be used to print
to a file (i.e., write a string to a file) using the
optional file argument. A file object must be
provided with this argument.
The writelines() method takes a sequence
of strings as its argument and writes them to the
given file as a continuous string.
FILES

252 CHAPTER 10. READING AND WRITING FILES
10.4 Review Questions
1. Assume the file input.txt is opened successfully in the following. What is the type of
the variable z after the following code is executed:
file = open(“input.txt”, “r”)
(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.
2. What output is produced by the following?
file = open(“foo.txt”, “r”)
print(s[2])
3. What output is produced by the following?
file = open(“foo.txt”, “r”)
4. What output is produced by the following?
file = open(“foo.txt”, “r”)
for line in file:
print(line[0], end=””)
5. What output is produced by the following?
file = open(“foo.txt”, “r”)
xlist = s.split()
print(xlist[1])
10.4. REVIEW QUESTIONS 253
6. What output is produced by the following?
file = open(“foo.txt”)
xlist = s.split(’\n’)
print(xlist[1])
7. What output is produced by the following?
file = open(“foo.txt”)
print(len(xlist), len(ylist))
8. What output is produced by the following?
file = open(“foo.txt”)
file.seek(0)
print(len(ylist), len(ylist))
9. What output is produced by the following?
file = open(“foo.txt”)
print(x, end=”:”)
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()
ANSWERS: 1) a; 2) i; 3) a test.; 4) TaI; 5) is; 6) a test.; 7) 3 0; 8) 3 3; 9)
T:h:i:s: :i:s:; 10) this is a test (terminated with a newline character); 11) The
file will be empty since there is an error that prevents the write() method from being used—
write() takes a single string argument and here is is given two arguments.; 12) thisis a
test (this is not terminated with a newline character); 13) this is a test (terminated with
a newline character).