noob2014
noob2014

Reputation: 89

concatenating functions in python?

Below is my code to create a square. So far so good, but I would like to make another square to the right of it. I tried concatenating my function "my_square()" to "my_square()" but that didn't work. What is the simplest way to accomplish this? I'm using python 2.7

def lines():
    print "|           |           |"

def bottom_top():
    print "+-----------+-----------+"


def my_square():
   bottom_top()
   lines()
   lines()
   lines()
   lines()
   bottom_top()

my_square()

Second try: I changed "bottom_top" and "lines" from functions to strings to test it out. When i ran the program I get the two squares but also an exception. Shouldn't this work if now i'm using strings?

bottom_top = "+-----------+-----------+"
lines = "|           |           |"

def my_square():
   print bottom_top
   print lines
   print lines
   print lines
   print lines
   print bottom_top

def two_squares():
my_square() + '' + my_square()

two_squares()

Upvotes: 0

Views: 6835

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

You can't concatenate functions, no. You are using print, which writes directly to your terminal. You'd have to produce strings instead, which you can concatenate, then print separately:

def lines():
    return "|           |           |"

def bottom_top():
    return "+-----------+-----------+"

def my_square():
   print bottom_top()
   for i in range(4):
       print lines()
   print bottom_top()

def two_squares():
   print bottom_top() + ' ' + bottom_top()
   for i in range(4):
       print lines() + ' ' + lines()
   print bottom_top() + ' ' + bottom_top()

Upvotes: 2

Related Questions