python3调用函数函数_Python3.3:调用其他函数的函数

My question was why the text "First one ended..." and "Second one ended..." appear when the first two functions are run separately, but not when the function combined() runs.

看起来您是在交互式提示符下运行代码(空闲或命令行)。在交互提示下,当您运行函数并且不将其返回值分配给任何对象时,返回值将打印到屏幕上。如果将其返回值指定给变量,或者函数不是顶级函数,则返回值不会打印到屏幕上。例如:>>> def foo():

return 3

>>> def bar():

foo()

>>> foo() # not assigned to anything -> prints return value to output

3

>>> bar() # not top-level -> doesn't print return value to output

>>> x = foo() # assigned to x -> doesn't print return value to output

这是交互式提示的一个奇怪之处。如果将powers_of_9()行添加到文件末尾,然后运行它,则不会得到相同的结果。执行此操作时,结果如下所示:

^{pr2}$

如您所见,powers_of_9的返回值没有被打印出来。在

无论如何,您使用return语句的方式是不正确的。只有当您想从函数中提取一些信息以在其他地方使用时,才应该使用return。例如,像这个愚蠢的例子:def add(x, y):

return x+y

def print_two_plus_three():

result = add(2, 3)

print(result)

当您只想显示一些信息时,print是您应该使用的。在

另外,我想对您的代码提供一些注释。为了获得您想要的结果,您的代码应该如下所示:def powers_of_x(x):

print('Powers function with', x, 'entered:')

for n in range(-3, 4, 1):

print('power of', n, '=', x**n)

print('First one ended (using variables with defined range)')

def powers_of_9():

print('Powers function for 9 is:')

powers_of_x(9)

print('Second one ended (no passed variable here)')

def combined():

x = int(input('Enter value to start: '))

print('First, run powers_of_x function for entered value of:', x)

powers_of_x(x)

print('Second, run powers_of_9 function for powers of 9:')

powers_of_9()

print('All now finished')当您写print('abc', 'def', 'ghi')时,打印的字符串是abc def ghi。也就是说,要打印的每个参数都用空格隔开。您可以通过编写例如print('abc', 'def', 'ghi', sep='X')来改变这种行为,其中sep关键字参数指定应该使用什么字符串来分隔参数。正如您所猜测的,这将打印abcXdefXghi。在

正如我所评论的,用圆括号括起return值被认为是不好的样式(当然,除非返回的是元组)。在

函数名和参数之间的空格也被认为是错误的。i、 e.使用print('foo'),而不是print ('foo')。在

最好在input()的参数末尾加一个空格,这样输入的值就与输入提示符分开了。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值