Python 04 Exercises
Python 04 Exercises
Python 04 Exercises
Practical Programming
in Python
Inspired by ’Practical Programming’ by Paul Gries, Jennifer Campbell, Jason Montojo
• Strings are created by placing pairs of single or double quotes around the text. Multiline
strings can be created using matching pairs of triple quotes.
• Special characters like newline and tab are represented using escape sequences that be-
gin with a backslash.
Escape Sequences
• Values can be printed using built-in function print, and input can be provided by the
user using built-in function input.
Lecture 4: Exercises
When writing code, only use Python concepts that have been introduced
in the lectures already.
Exercise 1:
What value does each of the following expressions evaluate to? Verify your answers by typing
the expressions into the Python shell.
a. 'Computer' + 'Science'
b. 'Darwin\'s'
c. 'H2O' * 3
d. 'CO2' * 0
Exercise 2:
Express each of the following phrases as Python strings using the appropriate type of quotation
marks (single, double, or triple) and, if necessary, escape sequences. There is more than one
correct answer for each of these phrases.
d. hydrogen sulfide
e. left\right
Exercise 3:
Rewrite the following string using single or double quotes instead of triple quotes:
"""A
B
C"""
Exercise 4:
Use built-in function len to find the length of the empty string.
Exercise 5:
Given variables x and y, which refer to values 3 and 12.5, respectively, use function print to
print the following messages. When numbers appear in the messages, variables x and y should
be used.
a. The rabbit is 3.
c. 12.5 is average.
d. 12.5 * 3
e. 12.5 * 3 is 37.5
Exercise 6:
Consider this code:
Exercise 7:
Use input to prompt the user for a number, store the number entered as a float in a variable
named num, and then print the contents of num.
Exercise 8:
Complete the examples in the docstring and then write the body of the following function:
Examples:
>>> repeat('yes', 4)
'yesyesyesyes'
>>> repeat('no', 0)
>>> repeat('yesnomaybe', 2)
"""
Exercise 9:
Complete the examples in the docstring and then write the body of the following function:
Examples:
"""