【问题标题】:How to restart count midway through a string of input?如何在输入字符串中途重新开始计数?
【发布时间】:2019-10-10 13:52:47
【问题描述】:

我正在尝试编写一个函数,它接收任意长度的正整数或负整数字符串,并将每个数字加到总数中,只要值不低于零。 (对于任何无效或空输入,它都会返回 0。)

我在编写一个循环时遇到问题,该循环在计数变为负数时将其重置为零并从停止的位置继续添加。

例如
输入:1, 2, -4, 1, 1
输出:2

这是我的代码:

def sum_earnings():
values = input("Enter a string of pos &/or neg numbers separated by commas (e.g. 1,-3,0,-4): ").split(',')
earnings = 0

try:
    for i in values:
        earnings += int(i)
        while earnings >= 0:
            earnings += int(i)
        else:
            earnings = 0
            continue
    print(earnings)

except ValueError:
    print(0)

return

【问题讨论】:

  • 你的缩进是错误的。
  • 谢谢,我刚刚注意到这一点,并对其进行了一些修改以纠正不必要的代码。
  • 我不清楚你想做什么 - 如果总 ever 低于零,它会产生 0 吗?在这种情况下,你为什么需要重新拿起它?另外,是的,你的缩进是错误的:)
  • 啊,我现在看到你添加了一个具体的例子:)

标签: python loops for-loop if-statement while-loop


【解决方案1】:

似乎过于复杂。请尝试以下操作:

earnings = 0
for i in values:
    try:
        earnings = max(0, earnings + int(i))  # resets to 0 for negative intermediate sum
    except ValueError:
        earnings = 0
        break  # this will end the loop for invalid input
print(earnings)

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多