带函数的Python打印格式

2024-05-16 02:12:42 发布

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

我目前正在学习Python并编写了这个基本函数。然而,输出是在几行,并没有显示答案后,“这里是一些数学:”。怎么了?你知道吗

谢谢

def ink(a, b):
    print "Here is some math:"
    return a + b        
add = ink(1, 59)    
fad = ink(2, 9)    
bad = ink(4, 2)     
print add    
print fad    
print bad

输出:

Here is some math:
Here is some math:
Here is some math:
60
11
6

编辑: 为什么不打印

输出:

Here is some math:
60
Here is some math:
11
Here is some math:
6

Tags: 函数答案add编辑returnhereisdef
3条回答

您必须return要打印的内容:

def ink(a, b):
    return "Here is some math: {}".format(a + b)
add = ink(1, 59)
fad = ink(2, 9)
bad = ink(4, 2) 

print add
print fad
print bad

输出:

Here is some math: 60
Here is some math: 11
Here is some math: 6

无论何时调用函数,函数体都会立即执行。 因此,当调用add = ink(1, 59)时,执行ink函数体,其中包含print语句。 因此它打印出"Here is some math:"。你知道吗

函数体到达return语句后,函数的执行将结束,return语句将值返回到调用函数的位置。 所以当你这么做的时候:

add = ink(1, 59)

resultink(1, 59)返回,然后存储到add,但是result尚未打印。你知道吗

然后对其他变量重复相同的操作(fadbad),这就是为什么在看到任何数字之前要打印"Here is some math:"三次。 只有在以后,才可以使用以下方法打印实际结果:

print add
print fad
print bad

您应该做的是让函数只计算结果:

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

通常,您需要在函数之外(或在主函数中)进行打印和输入:

add = ink(1, 59)
fad = ink(2, 9)
bad = ink(4, 2)

print "Here's some math:", add
print "Here's some math:", fad
print "Here's some math:", bad

尽管重复的代码通常被认为是不好的,所以您可以在这里使用for循环(如果您不知道for循环是如何工作的,您应该更多地了解它们):

for result in (add, fad, bad):
    print "Here's some math:", result

函数ink在被调用时正在打印Here is some math:,其返回值在

add = ink(1, 59)

结果值打印在

print add

为了达到你想要的,你必须要做的

print ink(1, 59)

编辑:如果是为了调试,那就更好了:

def ink(a, b):
    result = a + b
    print "Here is some math:"
    print result
    return result

不管怎样,我相信你在这里写的只是一个例子。如果不是出于调试的目的,则不应打印计算某些内容的函数中的任何内容。如果是为了调试,那么整个消息应该包含在函数体中,而不是像那样拆分。你知道吗

相关问题 更多 >