python - 当输入是特定字符串时如何中断 while 循环?

标签 python

当其中之一是字符串“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)

注意:

    不需要
  • 导入号码。 (我什至不知道它的存在!)
  • 您可以使用 True,而不是 2 > 1
  • 您无需检查 isinstance(..., int),因为 int() 会强制执行此操作。
  • 此操作将一直运行,直到到达任何非整数字符串为止。
<小时/>

如果您只想专门检查“F”,则更容易一些:

result = 0

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

print(result)

请注意,如果不使用 try,如果输入非整数、非“F” 字符串,程序将会崩溃。

关于python - 当输入是特定字符串时如何中断 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107690/

相关文章:

python - with语句,自动删除对象

python - 如何删除 Pandas 数据框的最后一行数据

Python/Tkinter - 将文本框的背景变成图像?

python - Python 中的循环和 if 语句

python - 向正在运行的 python 进程发送消息

python - 错误: "Required Parameter is Missing" - While Getting Anonymous Table in BigQuery

python - 如何将多个稀疏矩阵和密集矩阵组合在一起

恢复模式下 osx 上的 Python 位置

Python:递归函数中的变量绑定(bind)

python - Tkinter StringVar() 连接