Exercises for Lesson 3

Back to Lesson 3

Exercise 1: Operations on ints and floats

For this exercise, predict the output and then type each of the following commands in IDLE. We’ll discuss the results shortly.

1a: basic operations

>>> print(7 + 3.0)

>>> print(7.0 - 3.0)

>>> print(7 * 3)

>>> print(7 ** 3)

>>> print(7 / 3)

>>> print(7.0 / 3)

>>> print(7 // 3)

>>> print(7 % 3)

1b: type conversions

>>> int(2.718)

>>> round(2.718)

>>> float(2.718)

>>> float(round(2.718))

>>> float("2.718")

>>> int("2.718")

>>> float("2,718")

Exercise 2: The price of pizza

Write a program that calculates the cost per square inch of a circular pizza, given its diameter and price. The formula for area is .

(Hint: you should use the math library!)

Back to Lesson 3

Exercise 3: Practice with binary

What number (in base 10) does each of the following binary numbers represent? (Note that I’ve added a space in between the groups of four to help with readability.)

a)   0110 0010

b)   1001 0010

c)   1111 1111

d)   0000 1111

e)   0101 0101

Exercise 4: Summing by accumulation

Write a program to find the sum of the first natural numbers, where the value of is provided by the user. (Hint: you should use the accumulator pattern.)

Exercise 5: Approximating pi

Write a program that approximates the value of pi by summing the terms of this series: 41 - 43 + 45 - 47 + 49 - 411 + … . The program should prompt the user for , the number of terms to sum, and then output the sum of the first terms of this series. Have your program subtract the approximation from the value of math.pi to see how accurate it is.

Back to Lesson 3