Felix Dumitrascu
Felix Dumitrascu

Reputation: 125

How to break a while loop when input is a particular string?

I need to stop adding up user inputs when one of them is the string "F". So basically If my input is a int then : += result, if the same input variable is a string then I need to stop and add them together.

My code actually works and has the same inputs and outputs the exercise demands but I'm very unhappy with the way I resolve it.

This is my code:

import numbers
cat = int(input())


def norm(cat):
    res = 0
    for n in range(cat):
      x = int(input())
      res += x

    print(res)

def lon():
    res = 0
    while 2 > 1:
     try :
         y = int(input())
         if isinstance(y,int):
           res +=y
     except:
        print(res)
        break




if cat >= 0 :
    norm(cat)
else:
    lon()

It's actually breaking the while loop in a stupid way by checking if my variable is an int. (I need to make it stop by simply pressing F) Is there any cleaner and shorter way to obtain the same outputs?

Example of the actual inputs-outputs I expect :

in:       out:16    (1 + 3 + 5 + 7)
4
1
3
5
7

in:       out:37     (1 + 3 + 5 + 7 + 21)
-1
1
3
5
7
21
F

Upvotes: 1

Views: 3330

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

You could have written it a bit shorter:

result = 0

while True:
    line = input()
    try:
        result += int(line)
    except ValueError:
        break

print(result)

Notice:

  • import numbers isn't needed. (I didn't even know that existed!)
  • Instead of 2 > 1, you can use True.
  • You don't need to check isinstance(..., int) since int() enforces that.
  • This runs until any non-integer string is reached.

If you want to specifically check for "F" only, it's a bit easier:

result = 0

while True:
    line = input()
    if line == "F":
        break
    result += int(line)

print(result)

Note that without using try, you'll crash the program if you input a non-integer, non-"F" string.

Upvotes: 2

Related Questions