对于amount=int(值[1]),如何克服代码第8行的indexout-of-bound

2024-09-30 00:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

D 100
W 200

D表示存款,W表示取款。 假设向程序提供了以下输入: D 300型 D 300型 宽200 D 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)

Tags: 程序inputhere格式code事务金额amount
2条回答

我的第一个建议是尝试调试代码。你知道吗

什么是n?这是你所期望的吗?你知道吗

什么是x?这是你所期望的吗?你知道吗

values = x.split(" " )在做你认为应该做的事情吗?你知道吗

我猜是输入格式不正确,但如果没有额外的信息,很难说到底出了什么问题。你知道吗

使用系统标准而不是这里的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))

相关问题 更多 >

    热门问题