【问题标题】:how to overcome indexout of bound at line no 8 of my code for the amount = int(values[1])如何在我的代码的第 8 行克服数量 = int(values[1]) 的索引越界
【发布时间】:2018-07-20 16:05:00
【问题描述】:

编写一个程序,根据控制台输入的交易日志计算银行账户的净金额。事务日志格式如下:

D 100
W 200

D 表示存款,W 表示取款。 假设以下输入提供给程序: D 300 D 300 W 200 100 那么,输出应该是: 500 enter code here

tot = 0
n = int(input())
i = 0
while(i < n):
    x = input()
    values = x.split(" ")
    operation = values[0]
    amount = int(values[1])
    if operation == "D":
        tot += amount
    elif operation == "W":
        tot -= amount
    else:
        pass
    i += 1
print("total=", tot)

【问题讨论】:

  • 公平地说,即使是作业,错误在帖子标题中,我们尝试了代码 OP,并且我们期望输入/输出。
  • OP - 你一定得到了错误的输入。尝试通过在第 8 行上方放置 print(repr(x)) 语句来进行调试。它打印出什么?除非您给我们答案,否则我们无法为您提供帮助 -- idownvotedbecau.se/nodebugging
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。该程序需要手动输入。请将问题输入硬编码到您发布的代码中。

标签: python


【解决方案1】:

我的第一个建议是尝试调试您的代码。

什么是n?是你所期望的吗?

什么是x? 是你所期望的吗?

values = x.split(" " ) 是否在做你认为应该做的事情?

我的猜测是输入格式错误,但如果没有额外的信息,很难准确地说出哪里出了问题。

【讨论】:

    【解决方案2】:

    在这里使用 sys.stdin 而不是 input()... 这使得循环输入行更容易,而不是读取 input() 两次。更简洁,更容易理解和调试。

    import sys
    
    total = 0
    for line in sys.stdin:
        parts = line.split(' ')
        if parts[0] == 'D':
            total += int(parts[1])
        elif parts[0] == 'W':
            total -= int(parts[1])
        else:
            continue
    
    print('Total = ' + str(total))
    

    【讨论】:

    • 我认为你应该解释为什么你选择做出你所做的改变。
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2019-01-01
    • 2020-05-15
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多