AR89
AR89

Reputation: 3638

Python, print with format a tuple, not working

Here is the code:

#! /usr/bin/python

def goodDifference(total, partial, your_points, his_points):

    while (total - partial >= your_points - his_points):
        partial = partial+1
        your_points = your_points+1

        return (partial, your_points, his_points)

def main():
     total = int(raw_input('Enter the total\n'))
     partial = int(raw_input('Enter the partial\n'))
     your_points = int(raw_input('Enter your points\n'))
     his_points = int(raw_input('Enter his points\n'))
     #print 'Partial {}, yours points to insert {}, points of the other player {}'.format(goodDifference(total, partial, your_points, his_points))
     #print '{} {} {}'.format(goodDifference(total, partial, your_points, his_points))
     print goodDifference(total, partial, your_points, his_points)

if __name__ == "__main__":
     main()

The two commented print-with-format don't work, when executing it reports this error: IndexError: tuple index out of range. The last print (not commented), works fine. I've read many examples of format strings in Python and I can't understand why my code is not working.

My python version is 2.7.6

Upvotes: 0

Views: 479

Answers (2)

kindall
kindall

Reputation: 184455

str.format() requires individual arguments, and you are passing a tuple as a single argument. Thus, it substitutes the tuple into the first {} and then there are no more items left for the next one. To pass the tuple as individual arguments, unpack it:

print '{} {} {}'.format(*goodDifference(total, partial, your_points, his_points))

Upvotes: 4

Jay
Jay

Reputation: 2686

Why don't you just printout the values in the tuple?

t = goodDifference(total, partial, your_points, his_points)
print '{', t[0], '} {', t[1], '} {', t[2], '}'

Upvotes: 2

Related Questions