【问题标题】:Why there is an issu [duplicate]为什么会有问题 [重复]
【发布时间】:2022-02-23 00:17:19
【问题描述】:

我正在尝试创建一个简单的 while 循环,但有一个问题:

import random

weekDays = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday"]

n = 0
while n < len(weekDays):
    diceRoll = random.randint(4, 6)
    print("On {} perform {} reps per set".format(weekDays[n]))
    n = n + 1

我不明白的问题:

print("在 {} 每组执行 {} 次".format(weekDays[n])) IndexError: 位置 args 元组的替换索引 1 超出范围

如果您有任何建议,我们将不胜感激。

【问题讨论】:

标签: python


【解决方案1】:

您的 format 调用缺少参数 (diceRoll)。如果您使用 f 字符串而不是 format,则更容易跟踪您正在格式化的值,因为它们直接进入字符串:

import random

weekDays = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday"]
for day in weekDays:
    diceRoll = random.randint(4, 6)
    print(f"On {day} perform {diceRoll} reps per set")

【讨论】:

    【解决方案2】:

    print("On {} perform {} reps per set".format(weekDays[n])) 中需要两个参数。

    您可以将其更改为print("On {} perform reps per set".format(weekDays[n]))。它会起作用的。

    【讨论】:

      猜你喜欢
      • 2014-07-15
      • 2018-03-29
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2020-12-24
      相关资源
      最近更新 更多