繁体   English   中英

如何编辑基于输入分别显示结果的代码,并避免重复

[英]how can I edit my code that has shown results separately base on inputs and avoid duplicating

def aplusb(a, b):
    return a+b
    # write your code here

q=0
max=int(raw_input())
while q<max :
    a,b = map(int, raw_input().split())
    q=q+1
# q=aplusb(a,b)*q

for q in range(max):
    q = aplusb(a, b)
    print q


if __name__ == "__main__":
    q = int(raw_input())
    for i in range(q):
        inps = [int(_) for _ in raw_input().split()]
        print aplusb(inps[0], inps[1])

当我输入两个不同的数字序列,例如(2,1)(3,6)我期望的结果是这样的(3) \\N (9)但是它们现在显示(9) /n (9) 我该如何解决?

if __name__ ...之前的代码读取第一个while循环中的所有输入,但随后仅对第二个while循环的每次迭代使用最后ab

您可以在阅读每对结果时将其打印出来,或者必须保存所有输入,以便第二个循环可以返回该结果。

问题是您的代码在打印ab的值之前会更改它们的值。

我认为您不希望输入与输出交错。 因此,您必须将输入或结果临时存储在列表中。 此方法存储输入,因为它更接近原始代码。

def aplusb(a, b):
    return a+b

inps = []
max=int(raw_input())

for q in range(max):
    inps.append(map(int, raw_input().split()))

# At this point, using your sample data, inps looks like [[2,1], [3,6]]

for a, b in inps:
    q = aplusb(a, b)
    print q

附带说明一下,如果您刚开始使用Python,则实际上不应该自学Python2。请考虑安装并使用Python 3。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM