繁体   English   中英

具有功能的Python打印格式

[英]Python printing format with functions

我目前正在学习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

正在打印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

无论如何,我相信您在这里写的只是一个例子。 如果计算内容不是出于调试目的,则不应从计算结果的函数中打印任何内容。 如果是用于调试,则整个消息应包含在函数主体中,而不应这样分割。

每当您调用函数时,它的主体都会立即执行。 因此,当您调用add = ink(1, 59) ,将执行包含print语句的ink函数的主体。 因此它打印出"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循环的信息):

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

您必须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

暂无
暂无

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

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