[英]How do I assign a command to a variable
I am new to Python and when writing a loop module i bumped into the problem that I can't to find a way to put a command in the 'loopme' (it just gets ignored and then the script goes on). 我是Python的新手,在编写循环模块时遇到了一个问题,我找不到在'loopme'中放置命令的方法(它会被忽略,然后脚本继续执行)。 I hope you guys can help me with my problem.
我希望你们能帮助我解决我的问题。 Thanks in advance :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'
Assuming you want to execute loopme
before the last if
statement, you can pass any function to loop
as a parameter and then call it. 假设您要在最后一个
if
语句之前执行loopme
,则可以将任何函数作为参数传递给loop
,然后调用它。
Demo: 演示:
>>> def loop(loopme):
... # some code
... loopme()
... # some more code
...
>>> def loopme(): print('hi there, i am loopme!')
...
>>> loop(loopme)
hi there, i am loopme!
Note that you must explicitly call loopme
by adding the ()
, just stating the function name will do nothing useful. 请注意,您必须通过添加
()
来显式调用loopme
,仅声明函数名称将无济于事。
(Also note that it is not necessary to call loop
's argument loopme
, you could have named it some_function
and then call some_function()
in loop
's body.) (还要注意,不必调用
loop
的参数loopme
,您可以将其命名为some_function
,然后在loop
的主体中调用some_function()
。)
is there a way to make the 'def loopme()' ask what it is supposed to say?
有没有办法让'def loopme()'问它应该说什么?
Of course! 当然!
>>> def asker():
... print(input('What do you want to say? '))
...
>>> loop(asker)
What do you want to say? Hello World!
Hello World!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.