Home > database >  Can I change the value of a boolean when my while loop hits a certain condition to activate a second
Can I change the value of a boolean when my while loop hits a certain condition to activate a second

Time:01-17

I almost feel bad for asking a question already, given that I barely started my Python adventure. However I can't seem to figure out the issue.

My code, me playing around with while, conditions, self assignment, etc., looks like this atm:

age = 14
drivers_license = False

while age <= 17 and drivers_license == drivers_license:
    print(f"You are {age} years old, so you are still too young to drive!")
    age  = 1
    if age == 18:
        print(f"Now that you are {age}, you can get your drivers license!")
        drivers_license = True
    elif age >= 18 and drivers_license == True:
        print("You are allowed to drive now!")

''' As you can see, I am trying to change drivers_license from False to True after the age reaches 18 and enable the last print. I don't get errors but when I run the code I don't get the "You are allowed to drive now!" printed to the console. '''

CodePudding user response:

You can write your code like this to find your solution!

age = 14
drivers_license = False

while age <= 18:
    if age == 18:
        print(f"Now that you are {age}, you can get your drivers license!")
        drivers_license = True
    else:
        print(f"You are {age} years old, so you are still too young to drive!")
    if drivers_license == True:
        print("You are allowed to drive now!")
    age  = 1

CodePudding user response:

age = 14

while age <= 17:
    print(f"You are {age} years old, so you are still too young to drive!")
    age  = 1
    if age == 18:
        print(f"Now that you are 18, you can get your drivers license!")
        print("You are allowed to drive now!")
        break #ends the while loop

Anything else is useless.


Notice this:

if drivers_license == drivers_license: #Always True

and this...

if drivers_license == True: # is equivalent to...
if drivers_license:

...and this:

if drivers_license == False: # is equivalent to...
if not drivers_license:
  •  Tags:  
  • Related