简体   繁体   中英

General learning question about while loops

So for the basic code below. I thought the spam = spam + 1 would be adding 1 to the local variable spam, but it appears to add it to the global ( or else why would you start with the global variable spam = 0) . I thought local variables only exist within the function( starting after the colon.) It seems like this should not work considering local/global scopes?

  spam = 0
    while spam < 5:
        print('Hello, world.')
        spam = spam + 1

The while loop doesn't create a new scope. Scopes are only established by function and class definitions. The while loop is not a function definition.

So the spam = 0 and spam = spam + 1 statements are in the same scope, since there's no function definition around either of them.

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