如何在Python中返回多个值? [英] How to return multiple values in Python?
问题描述
my_function(c,r)
x = 4
y = 5
a = my_function(x,y)
print(a)
输出:
*这里没有空格*
*模式印出*
以下是my_function函数的代码:
def my_function(c,r):
if(c> 0 and r> 0):
print(**) c)
为范围内的(r - 2):
if(c == 1):
print(*)
elif(c> ; 1):
print(*+*(c - 2)+*)
if(r> 1):
print( ** c)
如果我按原样调用函数,它将打印所有内容。但我不希望它打印。我尝试用return来替换所有的打印文件,但是它只打印第一行(这并不意外,因为return只是在第一行终止了函数)。 class =h2_lin>解决方法
收集值返回到一个列表中,在函数结尾处构建一个字符串以返回:
def my_function(c,r):
lines = []
如果c和r:
lines.append(** c)
对于我在范围(r - 2):
如果c == 1:
lines.append(*)
else:
lines.append(*+ *(c - 2)+*)
if r> 1:
lines.append(** c)
return'\\\
'.join(lines)
这包括相同的换行符, print()
函数会在每行之间写入。
演示:
>>> print(my_function(4,5))
****
* *
* *
* *
****
So I'm wondering if this is possible. So, what I need to happen is to make my function return a string. Now the tricky part is that my function prints out a fancy pattern and I'm not sure how I can return my pattern as a string? I don't want it to actually print anything before I use the function in something like:
my_function(c,r)
x = 4
y = 5
a = my_function(x,y)
print(a)
Output:
*nothing here blank space*
*pattern printed*
Here is my code for the function my_function:
def my_function(c, r):
if(c > 0 and r > 0):
print("*" * c)
for i in range(r - 2):
if(c == 1):
print("*")
elif(c > 1):
print("*" + " " * (c - 2) + "*")
if(r > 1):
print("*" * c)
If I call the function as is, it will print everything. But I don't want it to print. I tried replacing all the print by return but it prints only the first line(which was not unexpected, since return will just terminate the function at line 1).
Gather the values to return into one list, build a string at the end of your function to return:
def my_function(c, r):
lines = []
if c and r:
lines.append("*" * c)
for i in range(r - 2):
if c == 1:
lines.append("*")
else:
lines.append("*" + " " * (c - 2) + "*")
if r > 1:
lines.append("*" * c)
return '\n'.join(lines)
This includes the same newlines the print()
function would write between each line.
Demo:
>>> print(my_function(4, 5))
****
* *
* *
* *
****
这篇关于如何在Python中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!