index = 2 for index in range(10): print(index)
output:
0
1
2
3
4
5
6
7
8
9
由此程式碼可知for loop 的 index 與全域中的 index 不同,若要使index起始為全域起始,可如此
index = 2 for index in range(index, 10): print(index)
output:
2
3
4
5
6
7
8
9
以下嘗試把同名local與global變數放在一起
index = 2 for index in range(10): print("local:") print(index) global index print("global:") print(index)
ouput結果產生錯誤,兩者皆表示為local變數,並顯示"SyntaxWarning: name 'index' is assigned to before global declaration"錯誤訊息
意思為index該變數在global宣告前已經賦值
再嘗試把 global index放入for loop中
index = 2 for index in range(10): global index print("global:") print(index)
產生與上段程式碼相同錯誤訊息
global index index = 2 for index in range(10): global index print("global:") print(index)
產生與上段程式碼相同錯誤訊息
for index in range(10): print("for index") print(index) if index >= 0: print("if index") index = index +1 print(index)
output:
for index
0
if index
1
for index
1
if index
2
for index
2
if index
3
for index
3
if index
4
for index
4
if index
5
for index
5
if index
6
for index
6
if index
7
for index
7
if index
8
for index
8
if index
9
for index
9
if index
10
Process finished with exit code 0
由上述程式碼可知for 的index與if中的index並不共用, 就像
index_if = 0 for index in range(10): print("for index") print(index) if index >= 0: print("if index") index_if = index_if +1 print(index_if)
此程式碼與上段程式碼相同結果
Python has no block scoping, only functions and classes introduce a new scope.
Because you have no function here, there is no need to use a global
statement, cows
and bulls
are already globals.
算了,用while好了
index = 2 # python 默認 index 為全域變數 while index < 10: index = index + 1 # 模仿for loop 行為 print(index) index = index + 1 # 動態改變index
參考:https://stackoverflow.com/questions/15725458/how-do-you-create-a-for-loop-with-a-dynamic-range
#此篇文為探討如何把for loop 中的 index 放在 for loop 中其他if等共用,喔,沒有成功,決定用whie代替for loop了