Python Forum
not controlling this loop well
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
not controlling this loop well
#1
Hi all,

So I'm trying to understand while loops. I'm stumped why this loop executes 8 times, when I'm trying to have it execute no more than 6 times. Could someone please explain? (Homework question, I've modified the variable names and contents from the original.)

lyrics = ["Today I don't feel like doing anything", "I just wanna lay in my bed", "Don't feel like picking up my phone", "So leave a message at the tone"]

repeat_number = 6

repeat = 0
while repeat < repeat_number:
    for lyric in range(0,(len(lyrics))):
        repeat += 1
        print(repeat, ':')
        print(lyrics[lyric])
Here are the results -- as you can see, the loop continues executing twice more, then though repeat > repeat_number:

1 :
Today I don't feel like doing anything
2 :
I just wanna lay in my bed
3 :
Don't feel like picking up my phone
4 :
So leave a message at the tone
5 :
Today I don't feel like doing anything
6 :
I just wanna lay in my bed
7 :
Don't feel like picking up my phone
8 :
So leave a message at the tone
Reply
#2
Following uses f-string and requires python 3.6 or newer.
number on same line as lyric:
lyrics = ["Today I don't feel like doing anything", "I just wanna lay in my bed", "Don't feel like picking up my phone", "So leave a message at the tone"]

for n, line in enumerate(lyrics):
    print(f'{n}: {line}')
output:
Output:
0: Today I don't feel like doing anything 1: I just wanna lay in my bed 2: Don't feel like picking up my phone 3: So leave a message at the tone
On separate lines:
lyrics = ["Today I don't feel like doing anything", "I just wanna lay in my bed", "Don't feel like picking up my phone", "So leave a message at the tone"]

for n, line in enumerate(lyrics):
    print(f'{n}:\n{line}')
output:
Output:
0: Today I don't feel like doing anything 1: I just wanna lay in my bed 2: Don't feel like picking up my phone 3: So leave a message at the tone
Reply
#3
Hi Larz60+,

Thanks for replying! Unfortunately, I haven't gotten to f-string yet. Also, I really want to understand why the loop is executing 8 times rather than just 6, as I thought my code as written would do. Do you see why it's doing that? If so, could you explain it?

Cheers, Juan
Reply
#4
Quote:I really want to understand why the loop is executing 8 times
Because the for executes completely. It has nothing to do with the while, so if you execute the for only, you will get the same result. Try this

while repeat < repeat_number:
    for lyric in range(0,(len(lyrics))):
        repeat += 1
        print(repeat, ':')
        print(lyrics[lyric])
    print("Done with for")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020