在python中使用For循环使其在语法上正确

时间:2018-09-03 18:27:00

标签: python string-formatting

每个评委的体操运动员得分都在1到10之间;没有更低,没有更高。所有分数均为整数值;一位法官没有十进制分数。将体操运动员可以从一名法官中获得的可能分数存储在元组中。打印出句子:

  

“最低分是____,最高分是   ____。”

使用元组中的值。打印出一系列句子:“法官可以给体操运动员_分。”

我的解决方案:

scores = (1,2,3,4,5,6,7,8,9,10)

for num in scores:
    print('A judge can give a gymnast %d points.' % (num))

输出:

A judge can give a gymnast 1 points.  
A judge can give a gymnast 2 points.
A judge can give a gymnast 3 points.
A judge can give a gymnast 4 points.
A judge can give a gymnast 5 points.
A judge can give a gymnast 6 points.
A judge can give a gymnast 7 points.
A judge can give a gymnast 8 points.
A judge can give a gymnast 9 points.
A judge can give a gymnast 10 points.

如何更改第一行,使其在语法上正确“法官可以给体操运动员1分”?

2 个答案:

答案 0 :(得分:1)

如果数字大于's',则可以使用条件表达式将'point'添加到1。另外请注意,使用range()比手动键入分数更整洁,并且.format%更好(尤其是在使用多种格式时)。

for num in range(1, 11):
    print('A judge can give a gymnast {} point{}.'.format(num, 's' if num > 1 else ''))

给出:

A judge can give a gymnast 1 point.
A judge can give a gymnast 2 points.
A judge can give a gymnast 3 points.
A judge can give a gymnast 4 points.
A judge can give a gymnast 5 points.
A judge can give a gymnast 6 points.
A judge can give a gymnast 7 points.
A judge can give a gymnast 8 points.
A judge can give a gymnast 9 points.
A judge can give a gymnast 10 points.

答案 1 :(得分:1)

您可以在python 3.6中使用f-strings

scores = (1,2,3,4,5,6,7,8,9,10)

for num in scores:
    print(f'A judge can give a gymnast {num} point{"s" if num > 1 else ""}.')

输出:

A judge can give a gymnast 1 point.
A judge can give a gymnast 2 points.
A judge can give a gymnast 3 points.
A judge can give a gymnast 4 points.
A judge can give a gymnast 5 points.
A judge can give a gymnast 6 points.
A judge can give a gymnast 7 points.
A judge can give a gymnast 8 points.
A judge can give a gymnast 9 points.
A judge can give a gymnast 10 points.