当其中之一是字符串“ F”时,我需要停止添加用户输入。所以基本上,如果我的输入是int,则:+ =结果,如果相同的输入变量是字符串,则需要停止并将它们加在一起。
我的代码实际上可以正常工作,并且具有相同的输入和输出练习要求,但是我对解决它的方式感到非常不满意。
这是我的代码:
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()
通过检查我的变量是否为int,它实际上以一种愚蠢的方式打破了while循环。(我需要通过按F使其停止)是否有更简洁的方法来获得相同的输出?
我期望的实际输入输出示例:
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
您可以写得短一些:
result = 0
while True:
line = input()
try:
result += int(line)
except ValueError:
break
print(result)
注意:
import numbers
不需要。(我什至不知道它的存在!)2 > 1
,您可以使用True
。isinstance(..., int)
因为这可以int()
强制执行。如果你想专门检查“F”只是,这是一个容易一点:
result = 0
while True:
line = input()
if line == "F":
break
result += int(line)
print(result)
请注意,如果不使用try
,则输入非整数,非"F"
字符串会导致程序崩溃。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句