Credit: Lisa Yan
File: running_sum.py
Write a program that reads in integers from the user and then outputs the current sum of the entered values. Here's what the output of the program should look like:
Enter integers, one at a time. I will show you the sum!
Please enter an integer: 3
The current sum is: 3 (1 integers entered)
Please enter an integer: 4
The current sum is: 7 (2 integers entered)
Please enter an integer: 5
The current sum is: 12 (3 integers entered)
Please enter an integer: 10
The current sum is: 22 (4 integers entered)
Please enter an integer: 3
The current sum is: 25 (5 integers entered)
Please enter an integer: 4
The current sum is: 29 (6 integers entered)
Please enter an integer: 1
The current sum is: 30 (7 integers entered)
Please enter an integer:
Remember in Karel, we wrote while loops that executed code until some particular condition is true? In Python, we can extend this idea to write a loop that executes forever (an infinite number of times). The basic structure looks like the below code, which will print "Hello" to the console an infinite number of times—one "Hello" on each line:
while True:
print("Hello")
Because your program will just keep adding up user input until the end of time, your program should use an infinite loop.
Caution: Note that you need to keep track of some information that needs to stay somewhere between loop iterations (like the total sum so far). You can declare these variables before the infinite loop starts.
Remember that you can run your program in Pycharm's Terminal by typing python3 runningsum.py
(if you are on Mac)
or py runningsum.py
(if you are on PC). However, this program runs forever!
To exit a program that runs forever, hit Ctrl-C
on your keyboard while in the Terminal. You should then be able
to run your program via the python3 runningsum.py
or py runningsum.py
again.
Often in console programs it is necessary to print out values to the user in a string. Suppose you have a variable total
that stores the number 55 and you want to output it. In your program, you should write:
print("The sum is: " + str(total))
If you run your program with the above input, the program will output the following to the console:
The sum is: 55
A more general form for printing out variables in code is:
"String message" + str(variable_name) + "more string message"