Python toggle boolean with functionPassing values in PythonCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionHow to make a chain of function decorators?Does Python have a string 'contains' substring method?

Was it really unprofessional of me to leave without asking for a raise first?

Symbol for "not absolutely continuous" in Latex

Does the app detect walking (and unlock Portmanteaus) if screen lock is on?

Should I share with a new service provider a bill from its competitor?

Who voices the character "Finger" in The Fifth Element?

Matrix decomposition

Using Raspberry Pi to flash its own SD card

How to securely dispose of a smartphone?

How can my story take place on Earth without referring to our existing cities and countries?

Wrong corporate name on employment agreement

What exactly did Ant-Man see that made him say that their plan worked?

How is this practical and very old scene shot?

What game is this character in the Pixels movie from?

What was the impact of Fischer vs. Spassky 1972 on the relationship between the USA and the Soviet Union?

Sharing referee/AE report online to point out a grievous error in refereeing

How can I specify a local port when establishing SSH connections?

How to Prove a System Is Invertible?

Balanced parentheses using STL C++

Donkey as Democratic Party symbolic animal

How exactly is a normal force exerted, at the molecular level?

What's the easiest way for a whole party to be able to communicate with a creature that doesn't know Common?

Can I travel from Germany to England alone as an unaccompanied minor?

How do I tell the reader that my character is autistic in Fantasy?

Does any Greek word have a geminate consonant after a long vowel?



Python toggle boolean with function


Passing values in PythonCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonUsing global variables in a functionHow to make a chain of function decorators?Does Python have a string 'contains' substring method?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to toggle a boolean with the help of a seperate function.
If my research is correct, there are no pointers in Python (I'm starting to learn it right now) so I'm unsure how to fix this issue.



For key presses i am using the library 'keyboard' which uses callbacks for hotkeys. Thus i have to somehow pass the toggle as a callback and need a method for toggling it. (If you have a different approach wihich could solve this its also appreciated)



Doing it inside the while loop like the shutdown call doesn't work. because the keyboard library doesn't have a simple method to check for key press or key release so it would be called repeatedly until the key is released.



import keyboard

# Global Variables
running = False

# ------------
# FUNCTIONS
# ------------

def shutdown():
print("Tool shutting down!")
quit()

def toggle(b):
b = not b

def init():
running = False
keyboard.add_hotkey('alt+1', toggle, args=[running])

# ------------
# MAIN PROGRAM
# ------------

init()

while True:
if keyboard.is_pressed('alt+q'):
shutdown()


The Variable should be consistent at least in the main program itself (It can be also consistent globally, which was my latest approach that didn't work out) and be toggled once i use my set hotkey.










share|improve this question






















  • Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

    – meowgoesthedog
    Mar 25 at 13:27


















0















I'm trying to toggle a boolean with the help of a seperate function.
If my research is correct, there are no pointers in Python (I'm starting to learn it right now) so I'm unsure how to fix this issue.



For key presses i am using the library 'keyboard' which uses callbacks for hotkeys. Thus i have to somehow pass the toggle as a callback and need a method for toggling it. (If you have a different approach wihich could solve this its also appreciated)



Doing it inside the while loop like the shutdown call doesn't work. because the keyboard library doesn't have a simple method to check for key press or key release so it would be called repeatedly until the key is released.



import keyboard

# Global Variables
running = False

# ------------
# FUNCTIONS
# ------------

def shutdown():
print("Tool shutting down!")
quit()

def toggle(b):
b = not b

def init():
running = False
keyboard.add_hotkey('alt+1', toggle, args=[running])

# ------------
# MAIN PROGRAM
# ------------

init()

while True:
if keyboard.is_pressed('alt+q'):
shutdown()


The Variable should be consistent at least in the main program itself (It can be also consistent globally, which was my latest approach that didn't work out) and be toggled once i use my set hotkey.










share|improve this question






















  • Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

    – meowgoesthedog
    Mar 25 at 13:27














0












0








0








I'm trying to toggle a boolean with the help of a seperate function.
If my research is correct, there are no pointers in Python (I'm starting to learn it right now) so I'm unsure how to fix this issue.



For key presses i am using the library 'keyboard' which uses callbacks for hotkeys. Thus i have to somehow pass the toggle as a callback and need a method for toggling it. (If you have a different approach wihich could solve this its also appreciated)



Doing it inside the while loop like the shutdown call doesn't work. because the keyboard library doesn't have a simple method to check for key press or key release so it would be called repeatedly until the key is released.



import keyboard

# Global Variables
running = False

# ------------
# FUNCTIONS
# ------------

def shutdown():
print("Tool shutting down!")
quit()

def toggle(b):
b = not b

def init():
running = False
keyboard.add_hotkey('alt+1', toggle, args=[running])

# ------------
# MAIN PROGRAM
# ------------

init()

while True:
if keyboard.is_pressed('alt+q'):
shutdown()


The Variable should be consistent at least in the main program itself (It can be also consistent globally, which was my latest approach that didn't work out) and be toggled once i use my set hotkey.










share|improve this question














I'm trying to toggle a boolean with the help of a seperate function.
If my research is correct, there are no pointers in Python (I'm starting to learn it right now) so I'm unsure how to fix this issue.



For key presses i am using the library 'keyboard' which uses callbacks for hotkeys. Thus i have to somehow pass the toggle as a callback and need a method for toggling it. (If you have a different approach wihich could solve this its also appreciated)



Doing it inside the while loop like the shutdown call doesn't work. because the keyboard library doesn't have a simple method to check for key press or key release so it would be called repeatedly until the key is released.



import keyboard

# Global Variables
running = False

# ------------
# FUNCTIONS
# ------------

def shutdown():
print("Tool shutting down!")
quit()

def toggle(b):
b = not b

def init():
running = False
keyboard.add_hotkey('alt+1', toggle, args=[running])

# ------------
# MAIN PROGRAM
# ------------

init()

while True:
if keyboard.is_pressed('alt+q'):
shutdown()


The Variable should be consistent at least in the main program itself (It can be also consistent globally, which was my latest approach that didn't work out) and be toggled once i use my set hotkey.







python reference toggle






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 13:20









DJSchaffnerDJSchaffner

381 silver badge6 bronze badges




381 silver badge6 bronze badges












  • Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

    – meowgoesthedog
    Mar 25 at 13:27


















  • Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

    – meowgoesthedog
    Mar 25 at 13:27

















Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

– meowgoesthedog
Mar 25 at 13:27






Why not just running = not running instead of b = not b? Also, see this post for why your code doesn't work.

– meowgoesthedog
Mar 25 at 13:27













1 Answer
1






active

oldest

votes


















1














Its just a problem with the scope of variables



Check this



var1 = False

def changeVar(va):
va = not va

changeVar(var1)

print(var1)

def changeVar2():
global var1
var1 = not var1
changeVar2()
print(var1)


And in your code you need to define toggle as following :



def toggle(b):
global running
running = not running





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55338761%2fpython-toggle-boolean-with-function%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Its just a problem with the scope of variables



    Check this



    var1 = False

    def changeVar(va):
    va = not va

    changeVar(var1)

    print(var1)

    def changeVar2():
    global var1
    var1 = not var1
    changeVar2()
    print(var1)


    And in your code you need to define toggle as following :



    def toggle(b):
    global running
    running = not running





    share|improve this answer



























      1














      Its just a problem with the scope of variables



      Check this



      var1 = False

      def changeVar(va):
      va = not va

      changeVar(var1)

      print(var1)

      def changeVar2():
      global var1
      var1 = not var1
      changeVar2()
      print(var1)


      And in your code you need to define toggle as following :



      def toggle(b):
      global running
      running = not running





      share|improve this answer

























        1












        1








        1







        Its just a problem with the scope of variables



        Check this



        var1 = False

        def changeVar(va):
        va = not va

        changeVar(var1)

        print(var1)

        def changeVar2():
        global var1
        var1 = not var1
        changeVar2()
        print(var1)


        And in your code you need to define toggle as following :



        def toggle(b):
        global running
        running = not running





        share|improve this answer













        Its just a problem with the scope of variables



        Check this



        var1 = False

        def changeVar(va):
        va = not va

        changeVar(var1)

        print(var1)

        def changeVar2():
        global var1
        var1 = not var1
        changeVar2()
        print(var1)


        And in your code you need to define toggle as following :



        def toggle(b):
        global running
        running = not running






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 13:46









        anilkunchalaeceanilkunchalaece

        1718 bronze badges




        1718 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55338761%2fpython-toggle-boolean-with-function%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해