以下是代码:
#! /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 totaln'))
partial = int(raw_input('Enter the partialn'))
your_points = int(raw_input('Enter your pointsn'))
his_points = int(raw_input('Enter his pointsn'))
#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()
两个带注释的格式打印不起作用,执行时报告此错误:IndexError: tuple index out of range
。最后一次打印(未发表评论),效果良好。我读过很多Python中格式化字符串的例子,我不明白为什么我的代码不起作用。
我的python版本是2.7.6
str.format()
需要单独的参数,并且您将元组作为单个参数传递。因此,它将元组替换为第一个{}
,然后就没有更多的项留给下一个了。要将元组作为单独的参数传递,请对其进行解压缩:
print '{} {} {}'.format(*goodDifference(total, partial, your_points, his_points))
为什么不直接打印元组中的值?
t = goodDifference(total, partial, your_points, his_points)
print '{', t[0], '} {', t[1], '} {', t[2], '}'