Exercises for Lesson 2

Back to Lesson 2

Exercise 1: Operations on numbers and strings

For this exercise, predict the output and then type each of the following commands in IDLE. 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("3 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>)

Exercise 3: swapping without simultaneous assignment

Using simultaneous assignment in Python makes swapping the values of two variables easy:

x, y = y, x

How would you do this without simultaneous assignment, i.e., if you can only assign one variable a value in a given statement? (Hint: it will take more than one line of code.)

Back to Lesson 2

Exercise 4: Predicting loop outputs

Predict the output from the following code fragments:

a)  for i in range(5):
        print(i * i)

b)  for d in [3,1,4,1,5]:
        print(d, end=" ")

c)  for i in range(4):
        print("Hello")

d)  for i in range(5):
        print(i, 2**i)

e)  for i in range(0):
        print("Hello")

Back to Lesson 2

Exercise 5: Repetition via looping

The following program converts temperatures in Celsius to temperatures in Fahrenheit. (It’s from Zelle section 2.2.)

# File: convert.py
# A program to convert Celsius temps to Fahrenheit.

def main():
    celsius = int(input("What is the Celsius temperature? "))
    fahrenheit = 9/5 * celsius + 32
    print("The temperature is", fahrenheit, "degrees Fahrenheit.")

main()

5a: A few repetitions

Modify the convert.py program with a loop so that it executes 5 times before quitting. Each time through the loop, the program should get another temperature from the user and print the converted value.

5b: A table of values

Modify the original convert.py program so that it uses a loop to compute and print a table of Celsius temperatures and the Farenheit equivalents every 10 degrees from 0°C to 100°C (it no longer needs user input). Make sure to think carefully about what sequence you want to loop over.

Here is some example output:

Celsius | Fahrenheit
0.0 | 32.0
10.0 | 50.0
20.0 | 68.0
30.0 | 86.0
40.0 | 104.0
50.0 | 122.0
60.0 | 140.0
70.0 | 158.0
80.0 | 176.0
90.0 | 194.0
100.0 | 212.0

Back to Lesson 2