Python For循环示例

时间:2020-01-09 10:43:06  来源:igfitidea点击:

如何以及何时在Python编程语言下使用for循环?

for循环是一个Python语句,该语句将一组语句重复指定的次数。
您可以在Python的for循环中使用任何对象(例如字符串,数组,列表,元组,dict等)。

Python for循环语法

基本语法为:

 
for var in list:
   statement-1 
   statement-2 
   statement-N

其中:

  • var:var从第一个元素开始,从列表中读取每个元素。
  • list:list是一个Python列表,即列表或者字符串。

Python中的示例和用法

以下示例说明了python中for语句的用法。
创建一个名为for-loop.py的文件:

#!/usr/bin/python
#
# for-loop.py: Sample for loop to print welcome message 3 times
#
for i in '123':
        print "Welcome",i,"times"

保存并关闭文件。
如下运行:

$ chmod +x for-loop.py
$ ./for-loop.py

或者

$ python for-loop.py

输出示例:

Welcome 1 times
Welcome 2 times
Welcome 3 times

上面的示例可以使用while循环编写,如下所示:

#/usr/bin/python
i=1
while i <= 3:
	print "Hello World,",i," times."
	i += 1

输出示例:

Hello World, 1  times.
Hello World, 2  times.
Hello World, 3  times.

嵌套循环示例

以下代码显示了使用python进行嵌套的经典for循环:

#!/usr/bin/python
# Nested for loop example
 
### Outer for loop ###
for x in xrange(1,5 ):
    ### Inner for loop	 ###
    for y in xrange(1, 5):
        print '%d ' % (x),
    print

输出示例:
嵌套的Python用于循环程序输出

使用range()函数迭代python for循环

代替使用名为123的字符串,请尝试使用range()遍历数字序列:

#!/usr/bin/python
# Python for loop using range()
 
print "*** Generates a list of 3 values starting from 0 ***"
for i in range(3):
        print "Welcome",i,"times."
 
print "*** Generates a list of 3 values starting from 1 ***"
for i in range(1,4):
        print "Welcome",i,"times."

输出示例:

*** Generates a list of 3 values starting from 0 ***
Welcome 0 times.
Welcome 1 times.
Welcome 2 times.
*** Generates a list of 3 values starting from 1 ***
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.

建议您使用xrange()函数来节省内存:

#!/usr/bin/python
# Python for loop using range()
 
print "*** Generates a list of 3 values starting from 0 using xrange() ***"
for i in xrange(3):
        print "Welcome",i,"times."
 
print "*** range() vs xrange() ***"
print "range() creates a list containing numbers all at once."
print "xrange() creates a list containing numbers as needed."

Python for循环列表示例

以下示例说明了使用列表的for语句的用法:

#!/usr/bin/python
# Sample for loop using a List
 
## define a list 
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
 
## Read shuttles list and store the value of each element into s and display on screen
for s in shuttles:
        print s

输出示例:

columbia
endeavour
challenger
discovery
atlantis
enterprise
pathfinder

要打印索引及其值,请尝试enumerate()。
它简化了常用的循环方法。
它为所有可迭代的集合提供了与iteritems()为字典提供紧凑,易读,可靠的索引符号相同的优点:

#!/usr/bin/python
# A list of shuttles 
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
 
## Read shuttles list and enumerate into index and value 
for index, value in enumerate(shuttles):
        print index, value

输出示例:

0 columbia
1 endeavour
2 challenger
3 discovery
4 atlantis
5 enterprise
6 pathfinder

使用for循环的字典数据类型示例

字典由键索引。
您可以通过Python for循环使用键和值对。
以下示例说明了此概念:

#!/usr/bin/python
 
# define a dict data type for our dns server as geoLocation : DNS server name
dnsservers = {"us":"ns1.theitroad.com", "uk":"ns2.theitroad.local", "asia":"ns3.theitroad.org"  }
 
# Python for loop for key,value using dict data type
for location, server in dnsservers.iteritems():
	print server, "dns server is located in" , location

输出示例:

ns2.theitroad.local dns server is located in uk
ns1.theitroad.com dns server is located in us
ns3.theitroad.org dns server is located in asia

下面的示例遍历字典数据类型,并且仅在找到匹配项时才显示结果:

#!/usr/bin/python
## Dict data type
dnsservers = {"us":"ns1.theitroad.com", "uk":"ns2.theitroad.local", "asia":"ns3.theitroad.org"  }
 
## Is location found ? 
found = False 
 
## INPUT: Search for a geo location 
search_ns_location = raw_input("Provide geo location ")
 
## Use for loop to search geo location for ns
for location, server in dnsservers.iteritems():
	if location == search_ns_location:
		print server, "dns server is located in" , search_ns_location
		found = True
 
## Display an error 
if found == False :
	print search_ns_location ,"not a valid geo location."

输出示例:

Provide geo location asia
ns3.theitroad.org dns server is located in asia

Provide geo location nyc
nyc not a valid geo location.

如何用于无限循环?

可以使用while True:语法创建一个无限for循环:

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1

您可以使用sleep()添加延迟,如下所示

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
import time
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1
        # Delay for 2 seconds
        time.sleep(2)

输出示例:
无限循环程序输出

有条件退出有休息

您可以使用for循环中的break语句来提前退出。
语法为:

for condition:
    if condition is true:
        break

提前退出示例:

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
import time
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1
        #### Delay for 2 seconds ####
        time.sleep(2)
        #### Die (early exit) if i is 5 ####
        if i == 5:
             print "Early exit detected...terminating infinity"
             break

输出示例:

Welcome 1 times. To stop press [CTRL+C]
Welcome 2 times. To stop press [CTRL+C]
Welcome 3 times. To stop press [CTRL+C]
Welcome 4 times. To stop press [CTRL+C]
Early exit detected...terminating infinity