Python Programming – John Zelle: Chapter 3 ex. 13

Write a program to sum a series of numbers entered by the user.

The program should first prompt the user how many numbers are to be summed.

It should then input each of the numbers and print a total sum.

Chapter 3 Exercise 13

Python

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #Chapter 3 Exercise 13 # Write a program to sum a series of numbers entered by the user. # The program should first prompt the user how many numbers are to be summed. # It should then input each of the numbers and print a total sum. def main(): print("This program adds series of numbers entered by the user") num = eval(input("How many numbers do you want to sum? ")) x = 0 s = 0 while x < num: x += 1 s += eval(input("Enter a number: ")) print("The total value of your", num, "numbers is ", s) main() |

Run =

This program adds series of numbers entered by the user

How many numbers do you want to sum? 6

Enter a number: 2

Enter a number: 45

Enter a number: 3

Enter a number: 77

Enter a number: 2

Enter a number: 3

The total value of your 6 numbers is 132

**************************

While the code above works it will fail if a user enters a letter instead of a number.

I edited the code to force valid numbers

Chapter 3 Exercise 13b

Python

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #Chapter 3 Exercise 13b # Write a program to sum a series of numbers entered by the user. # The program should first prompt the user how many numbers are to be summed. # It should then input each of the numbers and print a total sum. def main(): print("This program adds series of numbers entered by the user") num = eval(input("How many numbers do you want to sum? ")) x = 0 s = 0 while x < num: try: s += int(input('Enter a number: ')) except ValueError: print ("Invalid input.") else: x += 1 print("The total value of your", num, "numbers is ", s) main() |

while was not introduced at this point in the book, it has to be done with a for loop actually.

eg.

def main():

n = eval(input(“Please enter a number so we can calculate the sum of the cubes for all the natural number up to given number: “))

result = 0

for i in range(n):

t =(i+1)**3

result += t

print(result)

print(“The sum of all cubes is: “, result)

main()

while was not introduced at this point in the book, it has to be done with a for loop actually.

eg.

def main():

n = eval(input(“Please enter some numbers. how many numbers do you want to enter? “))

x = 0

sum = 0

for i in range(n):

num = eval(input(“Please enter a number: “))

sum += num

print(“The sum of the amount of numbers is: “, sum)

main()