6.7.3: Function With Loop: Shampoo.
I am having trouble figuring out how to stop the loop in my code:
def shampoo_instructions(num_cycles): for num_cycles in range(1,num_cycles+1): if num_cycles < 1: impress 'Likewise few.' elif num_cycles > four: print 'Too many.' else: print num_cycles, ': Lather and rinse.' else: print 'Done.' shampoo_instructions(two)
My output would exist:
1 : Lather and rinse.
2 : Lather and rinse.
Washed.
How can i make information technology and so when shampoo_instructions(6)
it just prints "Too many."
?
Jon Clements♦
135k 32 gold badges 240 silver badges 273 statuary badges
asked October 9, 2014 at 0:22
NinjaKlownNinjaKlown
61 1 gold badge two silver badges 8 bronze badges
2
ii Answers 2
Move your range check to exist exterior your actual looping, eg:
def shampoo_instructions(num_cycles): if num_cycles < 1: print 'Too few.' elif num_cyles > 4: print 'Too many.' else: for num_cycles in range(1,num_cycles+ane): print num_cycles, 'lather and rinse.' print 'Washed'
answered Oct 9, 2014 at 0:27
Jon Clements♦ Jon Clements
135k 32 gold badges 240 silverish badges 273 bronze badges
3
-
probably better not to use
num_cycles
in the loopOct 9, 2014 at 0:36
-
@Padraic in this instance, existence immutable and of express scope, it doesn't really affair, but it's a adept bespeak... if the original
num_cycles
value needs to exist retained then yes, the OP should definitely renamenum_cycles
in the for loop - skillful spot :)October 9, 2014 at 0:38
-
Only spotted it because I got strange behaviour using interruption in the loop ;)
Oct 9, 2014 at 0:41
found some help from reddit.
def shampoo_instructions(num_cycles): if num_cycles <= 0: print("Also few.") elif num_cycles >= 5: print("As well many.") else: for num_cycles in range (1, num_cycles + 1): impress(num_cycles,":", "Soap and rinse.") print("Washed.")
answered Jun v at 22:02
one
-
Your reply could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can ostend that your answer is correct. You tin can observe more data on how to write good answers in the assistance center.
Jun five at 23:14
6.7.3: Function With Loop: Shampoo.,
Source: https://stackoverflow.com/questions/26268460/shampoo-cycle-loop
Posted by: crewsmistne.blogspot.com
You're doing your range checking within your
range
- put it outside therange
, then you know it'due south safe to utilise yourrange
...Oct 9, 2014 at 0:24
Q. How did the programmer die in the shower? A. He read the shampoo bottle instructions: Lather. Rinse. Repeat.
October 9, 2014 at 0:29