【问题标题】:how can I edit my code that has shown results separately base on inputs and avoid duplicating如何编辑根据输入分别显示结果的代码并避免重复
【发布时间】:2019-01-01 12:08:05
【问题描述】:
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)!我该如何解决?

【问题讨论】:

  • 你能澄清一下你的代码应该做什么吗?
  • 取一个数字作为您的系列的计数(例如,如果您输入 3,则意味着您要放置 3 个系列的数字,因为每个系列包含两个数字,它们之间有空格),然后添加(3 系列) 他们并向您展示结果(三个结果)

标签: python function output add


【解决方案1】:

问题是您的代码在打印出任何计算结果之前更改了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,您真的不应该自学 Python 2。请考虑安装和使用 Python 3。

【讨论】:

  • 非常感谢,它有效!绝对 python 3 更好
【解决方案2】:

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

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

【讨论】:

  • 因为我使用了输入所以我不知道可以输入多少系列的数字所以我不知道需要多少打印功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 2019-08-20
相关资源
最近更新 更多