问题:编写带有参数shampoo_instructions()
的函数num_cycles
。如果num_cycles
小于1,则打印"Too few."
。如果大于4,则打印"Too many."
。否则,打印"N : Lather and rinse."
num_cycles
次,其中N是循环号,后跟"Done."
。
给定程序的示例输出: 1:起泡并冲洗。 2:起泡并冲洗。 完成。
我的代码:
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print ('Too few.')
elif num_cyles > 4:
print ('Too many.')
else:
i = 0
while i<=num_cycles:
i = i + 1
print (i+1,": Lather and rinse")
print ('Done')
shampoo_instructions(2)
我的代码抛出以下错误,我似乎无法弄清楚如何定义num_cycles
。
Traceback (most recent call last): File "main.py", line 14, in
shampoo_instructions(2) File "main.py", line 4, in shampoo_instructions
elif num_cyles > 4: NameError: global name 'num_cyles' is not defined
答案 0 :(得分:2)
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print ('Too few.')
此行:
elif num_cyles > 4:
应该是:
elif num_cycles > 4:
在解决此错误后,错误消失了。因此,其余的语法很好。但是,我进行了一些更改以获取所需的输出:
print ('Too many.')
else:
i = 0
while i<num_cycles:
print (i+1,": Lather and rinse")
i = i + 1
print('Done')
这将产生:
1 : Lather and rinse
2 : Lather and rinse
Done
因此您可能希望使用<
而不是<=
,并且在向i
加1之前两次将其打印。
答案 1 :(得分:0)
存在一些语法错误和不正确的变量。所有内容均已更正,并且代码已通过测试。干杯!
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print ('Too few.')
elif num_cycles > 4:
print ('Too many.')
else:
i = 0
while i < num_cycles:
print (i+1,": Lather and rinse.")
i = i + 1
print('Done.')
shampoo_instructions(2)
答案 2 :(得分:0)
def shampoo_instructions(num_cycles):
if num_cycles <= 1:
print('Too few.')
elif num_cycles > 4:
print('Too many.')
else:
i = 0
while i<num_cycles:
i += 1
print (i,": Lather and rinse.")
print('Done.')
答案 3 :(得分:0)
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print('Too few.')
elif num_cycles > 4:
print('Too many.')
else:
i = 0
while i<num_cycles:
i = i + 1
print (i,': Lather and rinse.')
print('Done.')
shampoo_instructions(2)
答案 4 :(得分:0)
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print('Too few.')
elif num_cycles > 4:
print('Too many.')
else:
i = 0
while i<num_cycles:
print (i+1,": Lather and rinse.")
i = i + 1
print('Done.')
shampoo_instructions(2)