Python Forum

Full Version: While loop that needs to count up
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The code works as it should with one exception, I can't seem to figure it out.

User-inputs a number and then I need the program to print 1 : text then 2 : text until the number that was entered is reach. So input of 2 would result in 1 : text then newline 2 : text

This is the code I have now for it.
def shampoo_instructions(num_cycles):
    if num_cycles < 1:
        print('Too few')
    elif num_cycles > 4:
        print('Too many')
    else:
        i = num_cycles
        while i <+ 4:
            print(i,': Lather and rinse.')
            i += 1
        print('Done.')
shampoo_instructions(2) 
OUTPUT
2 : Lather and rinse.
3 : Lather and rinse.
Done.
 
The i variable should start at 1, and the while condition should be i <= num_cycles. Think about it, if you want to do something num_cycles times, then count each time you do it from 1 to num_cycles.

Is it part of the exercise to do it with a while loop? Because this begs for a 'for' loop. Also, i is a bad variable name. Try to avoid single letter variable names and use more descriptive ones.
Thank you. I wasn't sure how to do a for statement. Could you give me an example for future reference?

This is the finished code block and it works as it should.
def shampoo_instructions(num_cycles):
    if num_cycles < 1:
        print('Too few')
    elif num_cycles > 4:
        print('Too many')
    else:
        cycles = 0
        while cycles < num_cycles:
            print(cycles + 1,': Lather and rinse.')
            cycles += 1
        print('Done.')
shampoo_instructions(4)
The equivalent for loop, replacing lines 7 through 10, would be

for cycles in range(num_cycles):
    print(cycles + 1, ': Lather and rinse.')
This is why I said it begs for a 'for' loop. For loops are specifically made for counting things, so they can do it in fewer lines.
Thank you