[英]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) .
我认为 spam = spam + 1 会将 1 添加到局部变量 spam,但它似乎将其添加到全局变量(否则为什么要从全局变量 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. while
循环不会创建新的作用域。 Scopes are only established by function and class definitions.作用域仅由函数和类定义建立。 The
while
loop is not a function definition. while
循环不是函数定义。
So the spam = 0
and spam = spam + 1
statements are in the same scope, since there's no function definition around either of them.所以
spam = 0
和spam = spam + 1
语句在同一范围内,因为它们中的任何一个都没有函数定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.