简体   繁体   中英

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

I am currently trying to learn python. I was going through Al Sweigart's Automate the Boring stuff with Python . In his example of while loops, he uses a not condition with his while loop (as shown in the code below).

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 !='' . Why does this not work with while name != '' ?

The while loop will only loop as long as the condition after it remains true. Putting a not before the condition inverts it. not True == False , not False == True

while not name != '' will loop as long as (not (name != '')) is True.

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 ''. This is because you have the statement, name != '' , and then you use the not operator on it which inverts it. This is so the while loop will continue to request the user for an input name that does not equal ''.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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