简体   繁体   English

不明白“ while not”循环的工作原理

[英]Don't understand how a “while not” loop works

I am currently trying to learn python. 我目前正在尝试学习python。 I was going through Al Sweigart's Automate the Boring stuff with Python . 我正在研究Al Sweigart的《使用Python自动化无聊的东西》 In his example of while loops, he uses a not condition with his while loop (as shown in the code below). 在他的实例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')

This code works fine. 此代码可以正常工作。 I am confused about how this works though. 我对此感到困惑。 We set name to '' (blank value) and then in the while loop we have while not name !='' . 我们将name设置为'' (空白值),然后在while循环中,我们拥有while not name !='' Why does this not work with while name != '' ? 为什么这对while name != ''不起作用?

The while loop will only loop as long as the condition after it remains true. while循环仅在条件成立后才会循环。 Putting a not before the condition inverts it. 在条件反转之前放置一个not not True == False , not False == True not True == Falsenot False == True

while not name != '' will loop as long as (not (name != '')) is True. 只要(not (name != ''))为True while not name != ''就会循环。

The not operator will invert your condition so the while loop condition is logically equivalent to saying, while name is equal to the empty string ''. not运算符会反转您的条件,因此while循环条件在逻辑上等效于说,而name等于空字符串”。 This is because you have the statement, name != '' , and then you use the not operator on it which inverts it. 这是因为您拥有语句name != ''语句,然后对它使用了not运算符来对其进行反转。 This is so the while loop will continue to request the user for an input name that does not equal ''. 这样,while循环将继续请求用户输入不等于“”的输入名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM