我无法弄清楚如何在代码中停止循环:
def shampoo_instructions(num_cycles):
for num_cycles in range(1,num_cycles+1):
if num_cycles < 1:
print 'Too few.'
elif num_cycles > 4:
print 'Too many.'
else:
print num_cycles, ': Lather and rinse.'
else:
print 'Done.'
shampoo_instructions(2)
我的输出是:
1:泡沫和冲洗。
2:泡沫和冲洗。
完成。
当shampoo_instructions(6)
时,我怎么能这样做呢?它只打印“太多了。”
答案 0 :(得分:1)
将范围检查移到实际循环之外,例如:
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+1):
print num_cycles, 'lather and rinse.'
print 'Done'