Python 的 for 循环可通过 range() 函数指定遍历范围。语法:for i in range(start, stop, step)。参数:start 为起始值(包含),stop 为终止值(不包含),step 为递增值(默认为 1)。示例:遍历 0 到 10(不含 10):for i in range(10); 遍历 5 到 15(不含 15),步长为 2:for i in range(5, 15, 2); 遍历 10 到 0(不含 0),步长为 -1:for i in range(

Python for 循环指定范围
Python 的 for 循环可以指定遍历一个范围内的元素。要指定循环从哪到哪,可以使用 range() 函数。
语法:
<code class="python">for i in range(start, stop, step):
# 循环体</code>参数:
立即学习“Python免费学习笔记(深入)”;
start:循环的起始值(包含)stop:循环的终止值(不包含)step:循环每次递增的值(默认为 1)示例:
遍历 0 到 10(不包含 10)的范围:
<code class="python">for i in range(10):
print(i)</code>输出:
<code>0 1 2 3 4 5 6 7 8 9</code>
以递增值为 2 遍历 5 到 15(不包含 15):
<code class="python">for i in range(5, 15, 2):
print(i)</code>输出:
<code>5 7 9 11 13</code>
以递减值为 -1 遍历 10 到 0(不包含 0):
<code class="python">for i in range(10, 0, -1):
print(i)</code>输出:
<code>10 9 8 7 6 5 4 3 2 1</code>
以上就是python for 循环怎么指定从哪到哪的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号