Results 1 to 5 of 5

Thread: Python - toggle boolean

  1. #1
    Join Date
    Jun 2010
    Location
    /home/TX
    Beans
    225
    Distro
    Ubuntu 12.04 Precise Pangolin

    Python - toggle boolean

    is there an easy way to toggle a boolean in python, like
    Code:
    bool1 = !bool1
    ?

    Thanks in advance.
    "The secret to creativity is knowing how to hide your sources." -Albert Einstein

    Ubuntu User #32977; Linux User #528876

  2. #2
    Join Date
    May 2009
    Beans
    525

    Re: Python - toggle boolean

    Code:
    Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) 
    [GCC 4.0.1 (Apple Inc. build 5488)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> b = True
    >>> print not b
    False
    >>> b = not b
    >>> print b
    False
    literally:

    Code:
    bool = not bool

  3. #3
    Join Date
    Apr 2009
    Location
    Germany
    Beans
    2,134
    Distro
    Ubuntu Development Release

    Re: Python - toggle boolean

    bool1 = not bool1

  4. #4
    Join Date
    Jun 2010
    Location
    /home/TX
    Beans
    225
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Python - toggle boolean

    thanks for the fast responses! works like a charm!
    "The secret to creativity is knowing how to hide your sources." -Albert Einstein

    Ubuntu User #32977; Linux User #528876

  5. #5
    Join Date
    Sep 2007
    Beans
    3

    Re: Python - toggle boolean

    Discovered this today, but am still posting it in case someone searching on the web will be looking for it.

    Alternative solution to toggling the boolean:

    Code:
    b ^= True
    example:

    Code:
    Python 2.7 (r27:82500, Aug 07 2010, 16:54:59) [GCC] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> b = True
    >>> b ^= True; b
    False
    >>> b ^= True; b
    True
    >>> b ^= True; b
    False

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •