Python 是否有更干净/更好的方法来运行显示打印号码的代码?

Python 是否有更干净/更好的方法来运行显示打印号码的代码?,python,python-3.x,Python,Python 3.x,代码应该显示每次运行循环时与打印输出相对应的数字。有没有更好/更干净的方法 counter = 1 i = 0 while i < 5: print(f"{counter} Hello World!") counter += 1 i += 1 考虑到counter=i+1,一个选项是只打印print(f“{i+1}Hello World!”),然后去掉counter 我不明白你所说的“更好/更干净的方式”还有什么意思,如果这不是你想要的,请澄清

代码应该显示每次运行循环时与打印输出相对应的数字。有没有更好/更干净的方法

counter = 1
i = 0
while i < 5:
    print(f"{counter} Hello World!")
    counter += 1
    i += 1

考虑到
counter=i+1
,一个选项是只打印
print(f“{i+1}Hello World!”)
,然后去掉
counter

我不明白你所说的“更好/更干净的方式”还有什么意思,如果这不是你想要的,请澄清你的问题。

你应该使用迭代器或
enumerate()
现有迭代器

>适用于范围(1,5+1)内的计数器:
...     打印(“{}你好世界!”。格式(计数器))
...
你好,世界!
2你好,世界!
3你好,世界!
4你好,世界!
5你好,世界!
range()
允许设置起始值,因此从
1开始可以省去对计数器进行进一步计算的麻烦

for i in range(5):
    print(f"{i+1} Hello World!")

您可以使用上面的代码。

为什么要费心维护两个独立但几乎相同的变量
i
计数器
for i in range(5):
    print(f"{i+1} Hello World!")