Python newbie
Python newbie

Reputation: 29

What does the boolean in this context do?

What does the boolean in this context do? What does true represent? This is python idle v3.4.2 The code works, i am just unsure how it functions

ans=True
while ans:
    print("""
    1.Take the quiz
    2.View and sort scores
    3.Exit/Quit
    """)
    ans=input("What would you like to do? ")
    if ans=="1":
      print("\n Taking quiz")
      quiz()

Upvotes: 0

Views: 41

Answers (2)

Jaron Thatcher
Jaron Thatcher

Reputation: 824

In this context, they are using ans as a check to see if they should continue to loop. They originally set it to True so that the loop will execute the first time.

All further executions of the loop will be dependent on what ans is set to afterwards, but it doesn't actually seem like they want it to loop by the way that small snippet of code is written.

Upvotes: 0

mhlester
mhlester

Reputation: 23221

By setting an initial ans to True, it satisfies the while ans loop for the first time. If it were a falsy value, the loop wouldn't ever be entered. (Of course, if the variable didn't exist at all, there would be a NameError)

ans is then updated each time you type an input (presumed "1", "2", or "3"). This loop keeps going until you've typed "1", in which case it takes the quiz.

If you press enter without typing anything, ans becomes an empty string "". The while ans is no longer satisfied and you break out of the loop, either continuing with whatever code is next or terminating the program.

Upvotes: 1

Related Questions