Nick Honings
Nick Honings

Reputation: 31

How can i print a multi line code with built in variables?

Hey I keep getting this Syntax Error with this code in the last line of the print statement. Did I miss something obvious or am i just doing it wrong. Radar() is supposed to get distances in steps of 18 degrees, which it does. Visual_radar() is then supposed to display them in a half circle. if there's any more information you need let me know.

def radar():
    measures = {}
    angle = 18
    servo(0)
    for x in range(9):
        servo(angle)
        dist = distance()
        measures[angle] = dist
        angle += 18

    for number in measures:
        if number < min_distance:
            print('Too close!', number)
            can_move_forward = False

def visual_radar():

    print """
                     %f              %f    
           %f                                %f

       %f                                       %f

    """ %(measures[90]), %(measures[108]),%(measures[72]),measures[126]),%(measures[54]))

radar()
visual_radar()

Upvotes: 0

Views: 47

Answers (2)

nsaura
nsaura

Reputation: 331

As said by Verv earlier, your error comes from multiple % after the last " inside your print function.

I suggest you to try the pair "{} .format" in your print or when you construct a string variable, a path and so.

It is according to me a generalization of the % because you don't have to know precisely what is the type of your variable.

To give you a simple example of how to use it :

a = [i**2 for i in xrange(4)]
print ("{}".format(a)) # ints
>>> [0, 1, 4, 9]

a.append("s") # string
a.append(2.4) # float
print "{}, {}".format(a[-1], a[-2])
>>> 's', 2.4

Here again you only have to write .format once and near the last " and to match the number of {} with the number of elements you put in the .format()

I hope this will be useful

Upvotes: 1

Verv
Verv

Reputation: 2473

The multiple % are what's causing your syntax error. You also seem to have an extra parenthesis in there. You might as well just get rid of superfluous parenthesis while you're at it.

Try this:

print("""
                     %f              %f    
           %f                                %f

       %f                                       %f

    """ % (measures[90], measures[108], measures[72] ,measures[126], measures[54]))

Looks like you haven't fully understood how the formatting operator works, you might wanna read through this

Also note that you'll get another error after that. You have 6 format strings but only 5 format arguments. It should look like this:

TypeError: not enough arguments for format string

Upvotes: 1

Related Questions