[英]How to break a while loop when input is a particular string?
当其中一个是字符串“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
。 (我什至不知道它的存在!)True
而不是2 > 1
。isinstance(..., int)
因为int()
强制执行。如果您只想专门检查 "F" ,它会更容易一些:
result = 0
while True:
line = input()
if line == "F":
break
result += int(line)
print(result)
请注意,如果不使用try
,如果输入非整数、非"F"
字符串,程序会崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.