Python Forum
While loop that needs to count up
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop that needs to count up
#1
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.
 
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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)
Reply
#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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to implement loop count zukochew 3 2,602 Jul-25-2018, 06:23 PM
Last Post: ichabod801
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,065 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

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