python - "while True"在 Python 中是什么意思?

标签 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."

什么是真的?

我认为说“虽然是真的”是简写,但这是为了什么?当变量“手”被赋值时?如果变量 'hand' 没有被赋值怎么办?

最佳答案

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

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

关于python - "while True"在 Python 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754620/

相关文章:

syntax - C#中函数修饰符的顺序

perl - 散列[关联数组?]上的Perl语法错误

sql - SQL-带大小写的分组依据

python - 无法捆绑 OpenCV 和 PyQt5

python - 帮助 Python while 循环行为

python - 加载音频文件并查找频率

css - ul,ul li 从 less 到 CSS

python - GAE 上的 XMPP 机器人状态消息

python - cv2中的可变fps(每秒帧数)

php - 奇怪的行为: json_encode() producing invalid json dependent on input