BYU logo Computer Science

Toggling a boolean variable

There are a variety of situations in which it is useful to toggle a boolean variable. For example, maybe you need to alternate between whether a light is green or red:

s_green = True
for _ in range(10):
    if is_green:
        print("green!")
    else:
        print("red!")
    is_green = not is_green

The statement if is_green: checks whether the variable is True. Then the statement:

is_green = not is_green

turns the variable from True to False, or from False to True, depending on its current value.

Example

Here is an example where toggling a boolean variable is helpful. This code runs a game with two players. Each player takes a turn choosing an integer. The game ends when the sum of all numbers exceeds 100. The person with the highest individual sum wins.

# a simple method to get a response and convert it to an integer
def get_response(prompt):
    response = int(input(prompt))

def play_easy_game():
    is_first = True
    total = 0
    sum_a = 0
    sum_b = 0
    while total < 100:
        if is_first:
            # Player 1's turn -- get response and add to total and their sum
            response = get_response('Player 1: ')
            total += response
            sum_a += response
        else:
            # Player 2's turn -- get response and add to total and their sum
            response = get_response('Player 2: ')
            total += response
            sum_b += response

        # alternate turns
        is_first = not is_first

    if sum_a > sum_b:
        print('Player 1 wins!')
    else:
        print('Player 2 wins!')

play_easy_game()