【问题标题】:Strange print output for Python function returnPython函数返回的奇怪打印输出
【发布时间】:2018-04-19 08:21:40
【问题描述】:

我是一个刚刚起步的新手。我一直在玩函数,我不明白为什么我会从下面的代码中得到下面的输出:

为什么它不连续打印函数的返回值和文本,为什么输出看起来像是在函数中循环两次?

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

plus = add(1,1)
minus = subtract(1,1)
times = multiply(1,1)

print plus
print minus
print times

我得到的输出是:

ADDING 1 + 1

SUBTRACTING 1 - 1

MULTIPLYING 1 * 1

2

0

1

【问题讨论】:

  • 那是你程序的执行顺序。首先调用所有函数,然后打印结果。

标签: python return output


【解决方案1】:

您的代码是这样编写的。首先,您执行所有三个功能。然后打印所有三个函数的结果。

plus = add(1,1)          # ADDING 1 + 1
minus = subtract(1,1)    # SUBTRACTING 1 - 1
times = multiply(1,1)    # MULTIPLYING 1 * 1

print plus               # 2
print minus              # 0
print times              # 1

如果您希望结果与计算交错,则将它们交错。

plus = add(1,1)          # ADDING 1 + 1
print plus               # 2
minus = subtract(1,1)    # SUBTRACTING 1 - 1
print minus              # 0
times = multiply(1,1)    # MULTIPLYING 1 * 1
print times              # 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多