简体   繁体   中英

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). 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.

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.

(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.)

is there a way to make the 'def loopme()' ask what it is supposed to say?

Of course!

>>> def asker():
...     print(input('What do you want to say? '))
... 

>>> loop(asker)
What do you want to say? Hello World!
Hello World!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM