In Python, how does a for loop with `range` work?

前端 未结 6 1290
醉梦人生
醉梦人生 2021-01-03 19:20
for number in range(1,101): 
    print number

Can someone please explain to me why the above code prints 1-100? I understand that the range functio

6条回答
  •  情书的邮戳
    2021-01-03 19:39

    As JG said, number is your variable (much like i in your C code). A for loop in python is really like a foreach loop in C# (I think Visual C++ has it too). Basically, it iterates over a container. So you can use that syntax with lists too:

    fib = [0,1,1,2,3,5,8]
    for number in fib:
        print number
    

    A range object acts sort of like a container, containing all the numbers between a and b.

提交回复
热议问题