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
globalwould be a slippery slope even if it probably looks like a quick fixsand then checks == 'F'to break out of the loop before convertingsto anint. Usingtry ... exceptto break out of the loop is also fine IMO.y = int(input())and in the next statementif isinstance(y,int): res +=y. If the first statement failed to convert the input to an int, an exception would have been thrown and you never would have fallen through to the second. So isn't that test for y being an int superfluous?