"while True" 是什么意思?在 Python 中是什么意思? [英] What does "while True" mean in Python?

查看:226
本文介绍了"while True" 是什么意思?在 Python 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 true' 是简写,但为了什么?当变量hand"被赋值时?如果变量 'hand' 没有被赋值怎么办?

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?

推荐答案

while True 表示永远循环.while 语句接受一个表达式并在表达式计算为(布尔值)true"时执行循环体.True 始终评估为布尔值true",因此无限期地执行循环体.这是一个你最终会习惯的成语!您可能会遇到的大多数语言都有相同的习语.

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.

请注意,大多数语言通常都有一些机制可以提前跳出循环.对于 Python,它是您问题中示例的 cmd == 'e' 案例中的 break 语句.

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.

这篇关于"while True" 是什么意思?在 Python 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆