0

我目前正在尝试学习python。我正在阅读 Al Sweigart 的Automate the Boring stuff with Python。在他的while循环示例中,他在循环中使用了not条件while(如下面的代码所示)。

name = ''
while not name != '':
    print('Enter your name:')
    name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests !=0:
    print('Be sure to have enough room for all your guests.')
print('Done')

这段代码工作正常。不过,我对这是如何工作的感到困惑。我们将 name 设置为''(空白值),然后在while循环中我们有while not name !=''. 为什么这不起作用while name != ''

4

2 回答 2

0

while 循环只会在它之后的条件保持为真时循环。在条件之前放置 anot会反转它。not True == False,not False == True

while not name != ''只要为(not (name != ''))真,就会循环。

于 2019-07-17T22:35:10.447 回答
0

not 运算符将反转您的条件,因此 while 循环条件在逻辑上等同于说,while name 等于空字符串 ''。这是因为你有语句, name != '',然后你not在它上面使用运算符来反转它。这样 while 循环将继续向用户请求不等于 '' 的输入名称。

于 2019-07-17T22:58:42.407 回答