对于我在范围内(开始,停止,步骤)Python 3 [英] for i in range(start,stop,step) Python 3

查看:39
本文介绍了对于我在范围内(开始,停止,步骤)Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出一系列数字,我正在使用for i in range(start,stop,step)".

I want to list a range of numbers and I'm using the "for i in range(start,stop,step)".

def range():
    P=36
    for i in range(P+1,0,-1):
        P=P-4
        print(P)

我想将数字列出到 0,但它一直到 -112.

I want to list the numbers down to 0 but it goes all the way to -112.

我发现如果我这样做:

def test():
    P=36
    for i in range(P+1,28, -1):
        P=P-4
        print(P)

它现在会停在 0.有人可以解释为什么它会这样做并且实际上并没有在 0 处停止吗?对不起,我是新手,我非常困惑.我也希望列出的结果能够在之后被引用,比如将结果串在一起形成一条带多边形的线但不能简单地写

It would now stop at 0. Could someone please explain why it does this and doesn't actually STOP at 0? Sorry, I'm new to this and I'm super confused. I would also like the results listed to be able to be referred to afterwards, like stringing the results together to form a line with a polygon but can't simply write

list(P)

代替print(P)

推荐答案

要创建一个从 36 到 0 以 4 为单位倒计时的列表,您只需直接使用内置的 range 函数即可:

To create a list from 36 to 0 counting down in steps of 4, you simply use the built-in range function directly:

l = list(range(36,-1,-4)) 
# result: [36, 32, 28, 24, 20, 16, 12, 8, 4, 0]

停止值是 -1,因为循环从开始值(包含)运行到停止值(不包含).如果我们使用 0 作为停止值,那么最后一个列表项将是 4.

The stop value is -1 because the loop runs from the start value (inclusive) to the stop value (exclusive). If we used 0 as stop value, the last list item would be 4.

或者如果您更喜欢 for 循环,例如因为你想打印里面的变量:

Or if you prefer a for loop, e.g. because you want to print the variable inside it:

for P in range(36,-1,-4):
    print(P)

这篇关于对于我在范围内(开始,停止,步骤)Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆