Exercises for Lesson 3
Exercise 1: 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 2: Playing with range
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.
Exercise 3: 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
Exercise 4: Operations on int
s and float
s
For this exercise, predict the output and then type each of the following commands in VS Code.
4a: 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
4b: type conversions
int(2.718)
round(2.718)
float(2.718)
float(round(2.718))
float("2.718")
int("2.718")
float("2,718")