我是Python新手,在编写循环模块时遇到了一个问题,我无法找到一种方法将命令放入循环模式中。 (它被忽略然后脚本继续)。我希望你们能解决我的问题。提前致谢:D!
def loop(loopme):
start = 'y'
while True:
start != 'y'
restart = input('restart? (y/n) ')
if restart == 'y':
start = 'y'
elif restart == 'n':
break
else:
print('invalid input')
continue
loopme #it works with print('hi')
if start == 'y':
start = 'n'
答案 0 :(得分:1)
假设您想在最后loopme
语句之前执行if
,您可以将任何函数作为参数传递给loop
,然后调用它。
演示:
>>> def loop(loopme):
... # some code
... loopme()
... # some more code
...
>>> def loopme(): print('hi there, i am loopme!')
...
>>> loop(loopme)
hi there, i am loopme!
请注意,您必须通过添加loopme
显式调用()
,只是声明函数名称不会有用。
(另请注意,无需调用loop
的参数loopme
,您可以将其命名为some_function
,然后在some_function()
中调用loop
的身体。)
有没有办法让'def loopme()'询问它应该说什么?
当然!
>>> def asker():
... print(input('What do you want to say? '))
...
>>> loop(asker)
What do you want to say? Hello World!
Hello World!