Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "while True" mean in Python?

Tags:

python

syntax

def play_game(word_list):     hand = deal_hand(HAND_SIZE) # random init     while True:         cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')         if cmd == 'n':             hand = deal_hand(HAND_SIZE)             play_hand(hand.copy(), word_list)             print         elif cmd == 'r':             play_hand(hand.copy(), word_list)             print         elif cmd == 'e':             break         else:             print "Invalid command." 

While WHAT is True?

I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?

like image 319
Baba Avatar asked Sep 20 '10 19:09

Baba


People also ask

Why do we use while true in Python?

While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.

How do you say while true in Python?

Instead of writing a condition after the while keyword, we just write the truth value directly to indicate that the condition will always be True . The loop runs until CTRL + C is pressed, but Python also has a break statement that we can use directly in our code to stop this type of loop.

What does the while true command do?

The concept behind a while loop is simple: While a condition is true -> Run my commands. The while loop will check the condition every time, and if it returns "true" it will execute the instructions within the loop.

How do you define while true?

While True in PythonIt is a practice followed to indicate that the loop has to run until it breaks. We then write the break statements inside the code block. The while true in python is simple to implement.


1 Answers

while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.

Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.

like image 147
Richard Cook Avatar answered Sep 30 '22 23:09

Richard Cook