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 VS Code.

1a: basic operations

print(7 + 3.0)

print(7.0 - 3.0)

print(7 * 3)

print(7 ** 3)

print(7 / 3)  # regular division

print(7.0 / 3)

print(7 // 3) # integer division

print(7 % 3)  # modulo

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")

Back to Lesson 3

Exercise 2: Playing with range()

2a: generating a sequence of numbers

What inputs to range() would give each of the following sequences?

a) 0, 1, 2, 3, 4, 5, 7, 8

b) 12, 13, 14

c) 0, 4, 8, 12

d) -3, -1, 1, 3, 5, 7

e) 5, 4, 3, 2, 1

f) 1, 3, 5, 7, 9, 11

2b: generating an alternating sequence

Using range() and a for loop, write a program to print out the values 1, -1, 1, -1, 1, .... The program should prompt the user for n (how many numbers to print) and then print each number.

Here is an example interaction:

What is n? 5
Results:
1
-1
1
-1
1

2c: putting it all together

Write a program to print out the following sequence: 1, -3, 5, -7, 9, -11, … . The program should prompt the user for n (how many numbers to print) and then print each number.

Here is an example interaction:

What is n? 3
Results:
1
-3
5

Hint: Think carefully about how the values you get from range() relate to the values you need to print.

Back to Lesson 3

Exercise 3: Summing by accumulation

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

Here is an example interaction:

What is n? 10
The sum of 1 to 10 is: 55

Exercise 4: Approximating pi

Write a program that approximates the value of pi by summing the terms of this series: 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + … . The program should prompt the user for n (the number of terms to sum) and then output the sum of the first n terms of this series. Have your program subtract the approximation from the value of math.pi to see how accurate it is.

Here is an example interaction:

What is n? 3
The sum of the first 3 terms of 4/1 - 4/3 + 4/5 + ... is: 3.466666666666667

And another:

What is n? 10000000
The sum of the first 10000000 terms of 4/1 - 4/3 + 4/5 + ... is: 3.1415925535897915

To compare to math.pi:

import math
print(math.pi) # prints 3.141592653589793

Back to Lesson 3