Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculator python3
#3
First of all we have to take a look at the Error you are recieving. It is not a Syntax Error, a Syntax Error would mean, that you wrote code that can not be understood by the computer. What you get is a Value Error, which means, that the computer is trying to do operations where it expected a completely differend Value Type.
The problem you are having is that you directly convert the input to int. But since you want to also pass in words like "stop" this conversion will fail and result in a Value Error. I would suggest you change your code to something like this:
n = 0
total = 0 
while not (n == 'stop' or n == 'Stop'):
    n = input('Number? ')
    if not (n == 'stop' or n == 'Stop'):
       total = total + int(n)
       n = int(input('Number?'))
print(total)
Even when you save "Stop" inside of n, the comparison you used for the while-loop ( n >= 0 ) will result in an ValueError, when you send in the "stop" signal.

Though a bit more clean approach would be:
n = 0
total = 0 
while not n in ['stop', 'Stop']:
    n = input('Number? ')
    try:
       total = total + int(n)
    except ValueError:
       continue
print(total)
Here you accept that this error can occure but catch it through the try-except part. And since you only want to print the result when you are finished, you can do this after the while loop.

Also just keep one thing in mind. Using only a string in a condition will result to True if the string is not empty ( "" ) or False if it is empty. So the part where you said:
n == 'stop' or 'Stop'
will always resolve to True, since 'Stop' is always True.

@perfringo actually it is not only the comparison of the while-loop causing the error, but the conversion to int.

also sorry, for kind of double post
Reply


Messages In This Thread
Calculator python3 - by Magicamtt455 - Jan-27-2020, 01:23 AM
RE: Calculator python3 - by perfringo - Jan-27-2020, 08:46 AM
RE: Calculator python3 - by ThiefOfTime - Jan-27-2020, 08:53 AM
RE: Calculator python3 - by perfringo - Jan-27-2020, 10:06 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,980 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020