Keep in mind that I am still very new to python coding as I am only just into chapter 5 of my python coding class. Keeping that in mind, I am attempting to create a sum calculator using a “while loop” to continue until the user enters a negative number instead of a positive number.
In case I am not entirely clear in my description of my question I will post the exact homework problem here:
Chapter 5, page 200, #8
Sum of Numbers
Write a program with a while loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.
Now for the code that I have written so far:
def main():
number = float(input('Please enter in a positive number: '))
while number > 0:
positiveNumber()
while number < 0:
calculateTotal()
printTotal()
def positiveNumber():
number = float(input('If you are finished please enter a negative number.' + \ 'Otherwise, enter another positive number: '))
while number > 0:
positiveNumber()
while number < 0:
calculateTotal()
printTotal()
def calculateTotal():
total = 0 + number
def printTotal():
print('The sum of your numbers is: ', total)
main()
- In line 11, I have the “+ \” sign there because I wanted to make an enter space there in order to have a cleaner looking text, but that does not seem to work.
I apologize if this question seems “nooby” but I need help making a cleaner/working sum calculator. I would greatly appreciate it if someone can take a look at this code and hopefully help me improve it. Thank you!
Final Edit:
Thank you all for the informative answers! I learned alot (for a “newbie” =]). I used Talon876’s answer for my calculator. Thanks again everyone!
If you want a single string to be printed on multiple lines, put a
\nin the string.For example,
would output
It looks like you’re mixing a while loop with recursion (calling a method from within itself). I would suggest using a single while loop and an input variable to check for the breaking condition (the input is < 0)
It would look something like this:
This will loop until the user inputs a negative number, or 0. If you want to accept 0 as a positive number, change the while condition to
number > -1