# 循环：Python的循环语句详细指南

2021年3月20日14:34:55 发表评论 799 次浏览

## for循环

For循环用于顺序遍历。例如：遍历列表, 字符串或数组等。在Python中, 没有C样式的循环, 即for(i = 0; i <n; i ++)。有一个" for in"循环, 与其他语言中的每个循环类似。让我们学习如何将in循环用于顺序遍历。

for var in iterable:
# statements

# Python program to illustrate
# Iterating over a list
print ( "List Iteration" )
l = [ "geeks" , "for" , "geeks" ]
for i in l:
print (i)

# Iterating over a tuple (immutable)
print ( "\nTuple Iteration" )
t = ( "geeks" , "for" , "geeks" )
for i in t:
print (i)

# Iterating over a String
print ( "\nString Iteration" )
s = "Geeks"
for i in s :
print (i)

# Iterating over dictionary
print ( "\nDictionary Iteration" )
d = dict ()
d[ 'xyz' ] = 123
d[ 'abc' ] = 345
for i in d :
print ( "% s % d" % (i, d[i]))

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz 123
abc 345

for循环的工作：

## 循环控制语句

# Prints all letters except 'e' and 's'
for letter in 'lsbin' :
if letter = = 'e' or letter = = 's' :
continue
print ( 'Current Letter :' , letter)
var = 10

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

for letter in 'lsbin' :

# break the loop as soon it sees 'e'
# or 's'
if letter = = 'e' or letter = = 's' :
break

print ( 'Current Letter :' , letter)

Current Letter : e

# An empty loop
for letter in 'lsbin' :
pass
print ( 'Last Letter :' , letter)

Last Letter : s

## range()函数

range()是Python的内置函数。当用户需要执行特定次数的操作时使用它。 Python(3.x)中的range()只是一个名为的函数的重命名版本

xrange()

• 开始：整数, 从该整数开始返回整数序列

• 停：整数, 在该整数之前要返回整数序列。
整数范围在停止处结束– 1。

• 步骤如下：整数值, 确定序列中每个整数之间的增量

# Python Program to
# show range() basics

# printing a number
for i in range ( 10 ):
print (i, end = " " )
print ()

# using range for iteration
l = [ 10 , 20 , 30 , 40 ]
for i in range ( len (l)):
print (l[i], end = " " )
print ()

# performing sum of first 10 numbers
sum = 0
for i in range ( 1 , 10 ):
sum = sum + i
print ( "Sum of first 10 numbers :" , sum )

0 1 2 3 4 5 6 7 8 9
10 20 30 40
Sum of first 10 numbers : 45

.

## else循环

# Python program to demonstrate
# for-else loop

for i in range ( 1 , 4 ):
print (i)
else : # Executed because no break in for
print ( "No Break\n" )

for i in range ( 1 , 4 ):
print (i)
break
else : # Not executed as there is a break
print ( "No Break" )

1
2
3
No Break

1

.