Exercises for Lesson 2
Exercise 1: Operations on numbers and strings
For this exercise, predict the output and then type each of the following commands in VS Code. We’ll discuss the results shortly.
1a: Operators on numbers
print(4)
print(4 + 3)
print(4.0 - 3.0)
print(4 * 3)
print(4 ** 3)
print(4 / 3)
1b: Operators on strings
print("4" + "3")
print("4" - "3")
print("4" - 3)
print("4" * "3")
print("4" * 3)
print("4" / "3")
1c: Combining strings and expressions
print("4 + 3 =", 4 + 3)
print("Three 4s:", 3 * "4")
Exercise 2: sep
keyword parameter of print
The Python print
function supports other keyword parameters besides end
. One of these other keyword parameters is sep
. What do you think the sep
pararmeter does? Hint: sep
is short for separator. Try it out using the following print statement:
print("3", "1", "4", "1", "5", sep=<change me>) # change <change me> to something else
Exercise 3: Predicting loop outputs
Predict the output from the following code fragments:
3a: Regular loop sequences
a) for i in range(5):
print(i * i)
b) for i in range(5):
print(i, 2**i)
c) for d in [3,1,4,1,5]:
print(d, end=" ")
d) for i in range(4):
print("Hello")
3b: Bounds testing range
e) for i in range(0):
print("Hola")
f) for i in range(3, 4):
print("你好")
g) for i in range(3, 3):
print("안녕하세요")
h) for i in range(3, 2):
print("🐉")