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



体操运动员可以从每个评委那里获得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 分"?

你可以使用 python 3.6 中的 f 字符串:

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.

您可以使用条件表达式仅在数字大于1时将's'添加到'point'。另请注意,使用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.

最新更新