strange while statement behaviour?

后端 未结 2 1238
有刺的猬
有刺的猬 2021-01-26 08:18

I cannot figure out why the following statements dont work.

randomKey = random.choice(list(topic.keys()))
randomValue = random.choice(topic[randomKey])

current          


        
2条回答
  •  情歌与酒
    2021-01-26 08:50

    It is part of the Python grammar. From the documentation:

    This [a while statement] repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

    So in the first case, it must be that the while condition never evaluates to false, while in the second it eventually does. Note that explicitly breaking out of the loop will not execute the else clause.

提交回复
热议问题