简体   繁体   中英

Python - Returning Multiple Lines of Code without Tuple

I'm writing a python function and I want it to print out a shapes. I am limited to using print five times. The shapes prints out if I use:

def shape():
     print line1
     print line2
     print line3
     print line4
     print line5

And then print the shapes out multiple times by multiplying the function. However, this uses up all my allotted print statement and I need to also create another function that prints the same shapes, but indented to the right evert other line.

So I would like this function to return the whole shapes, so that I can use print statement later on. However, of course, if I use return instead of print, I only have line 1 returned and then the function stops. Is there any way to get around this? Using a tuple doesn't help me since I want the shape intact.

EDIT: I am not allowed to use "/n" or any extra quotations marks when writing my answer. I am given pre set strings that I can use.

presuming lines are in a list or tuple etc.. use join on wherever the container the lines are coming from.

def shape():
     return "\n".join(line1,line2,line3,line4,line5)

Or just return all lines and use join on the function:

def shape():
     return lines

print("\n".join(shape()))

For five lines return lines[:5] .

You can use join on any iterable:

def shape():
      return "\n".join(line1,line2,line3,line4,line5)

without using \\n just iterate over the function using a single print:

def shape():
     return lines

for line in shape():
  print(line) 

You can return multiple variables from a function:

def shape():
     return line1, line2, line3, line4, line5

and read them in the same way:

line1, line2, line3, line4, line5 = shape()

which means that if you want, you can create a "pretty print" function that reads the variables returned from shape() and adds tabs/newlines/whatever-you-want to each line - without messing your data:

def pretty_print_lines():
    for line in shape():
        print line

Restricting this answer to the specs in the question: You can use a format string in the function and add an indent argument.

def shape(indent = 0):
    indent = ' ' * indent
    print '{}'.format('ab')
    print '{}{}'.format(indent, 'cd')
    print '{}'.format('ef')
    print '{}{}'.format(indent, 'gh')
    print '{}'.format('jk')

def indent5():
    shape(5)

Usage:

>>> shape()
ab
cd
ef
gh
jk
>>> indent5()
ab
     cd
ef
     gh
jk
>>>

There are a lot of variations you can add to that like a second argument to specify indenting the even or odd lines- which would require a bit more code in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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