0

I want the program to end if I type "stop".
However, an error occurs when str(intNum)=='stop'. What should I do?

The error:

"ValueError: invalid literal for int() with base 10: 'stop'"

intSum = 0

while 1:
    intNum = int(input("Please enter an integer.(If you want to end it, : stop) : ")) 
    intSum = intSum + intNum
    if str(intNum)=='stop':
     break
print("SUM=",intSum)
D_00
  • 1,440
  • 2
  • 13
  • 32

3 Answers3

1

Easiest way is to take the input as string and use if else loop:

intSum = 0
while 1:
    userInput = input("Please enter an integer.(If you want to end it, : stop) : ")
    if userInput == 'stop':
        break
    else:
        intNum = int(userInput)
        intSum = intSum + intNum
print("SUM=", intSum)

# OUTPUT:
# Please enter an integer.(If you want to end it, : stop) : 6
# Please enter an integer.(If you want to end it, : stop) : 3
# Please enter an integer.(If you want to end it, : stop) : stop
# SUM= 9
Neeraj
  • 975
  • 4
  • 10
0

if you type stop, you cannot change it to an integer. I think that is where the problem is.

Hasano
  • 31
  • 1
  • 4
0
intSum = 0

while 1:
    intNum = input("Please enter an integer.(If you want to end it, : stop) : ") 
    if intNum=='stop':
        break
    if intNum.isdigit():
        intSum = intSum + int(intNum)
    else:
        print("Invalid Input")

print("SUM=",intSum)
Akshay Jain
  • 790
  • 1
  • 7
  • 21
  • You cannot convert string 'stop' to int in line 5: intSum = intSum + int(intNum). It will still throw a ValueError – Neeraj Apr 12 '21 at 03:57
  • 1
    I've changes the code and now it will display the `Invalid Input` if the input is wrong – Akshay Jain Apr 12 '21 at 04:02