简体   繁体   English

Python-变量如何影响循环

[英]Python - how does the variable affect the loop

I am wondering why there is a different result when I change from arr[n] in version 1 to n in version 2: 我想知道为什么从版本1的arr [n]更改为版本2的n时为什么会有不同的结果:

Version 1 版本1

def summer_69(arr):
    list_sum2 = 0
    n = 0
    for arr[n] in range(arr[n] == 6, (arr[n]== 9) + 1):
            list_sum2 += arr[n]
    print(list_sum2)

summer_69([1, 3, 5])
summer_69([4, 5, 6, 7, 8, 9])

Result for Version 1 版本1的结果

0
0

Version 2 版本2

def summer_69(arr):
    list_sum2 = 0
    n = 0
    for n in range(arr[n] == 6, (arr[n]== 9) + 1):
            list_sum2 += arr[n]
    print(list_sum2)

summer_69([1, 3, 5])
summer_69([4, 5, 6, 7, 8, 9])

Result for Version 2 第2版​​的结果

1
4

that's not how range works. 范围不是这样的。

in this line: 在这一行:

for n in range(arr[n] == 6, (arr[n]== 9) + 1):

arr[n] == 6 and (arr[n]== 9) + 1 are returning truth values because == is a comparison operator so n here at best takes values 0 or 1. arr[n] == 6(arr[n]== 9) + 1返回的是真值,因为==是一个比较运算符,因此n最多为0或1。

you want 你要

for n in range(6, 10):

so that the value of n iterates from 6 to 9, range() being inclusive to the left and exclusive to the right 因此n的值从6迭代到9, range()在左边是包含的,在右边是排斥的

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

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