-1

The code is supposed to show what number corresponds to the print output every time the loop is ran. Is there a better/cleaner way to do this?

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

output:

1 Hello World!
2 Hello World!
3 Hello World!
4 Hello World!
5 Hello World!

3 Answers3

1

Given that counter = i + 1, one option would be to just do print(f"{i+1} Hello World!") and get rid of counter.

I don't see what else you could mean by "better/cleaner way", if this isn't what you had in mind please clarify your question.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
0

You should use a range() iterator or enumerate() an existing one!

>>> for counter in range(1, 5+1):
...     print("{} Hello World!".format(counter))
...
1 Hello World!
2 Hello World!
3 Hello World!
4 Hello World!
5 Hello World!

range() allows setting the start value, so beginning it at 1 saves you from doing further math on your counter.

ti7
  • 16,375
  • 6
  • 40
  • 68
0
for i in range(5):
    print(f"{i+1} Hello World!")

You can use the above code.

Sam Dani
  • 114
  • 1
  • 6