python之循环

1.while

1 # while
2 #当while循环开始后,先判断条件是否满足,如果满足就执行循环体内的语句,
3 # 执行完毕后再回来判断条件是否满足,如此无限重复;直到条件不满足时,执行while循环后边的语句。
4 name = ""
5 while not name:
6     name = input("Enter your name:")
7 print("hello ,your name is ",name)

  输出结果:

Enter your name:
Enter your name:zyt
hello ,your name is  zyt

2.for循环

  示例一:遍历列表

1 # for循环
2 for looper in [1,2,3,4]:
3     print(looper)

  输出结果:

1
2
3
4

  示例二:遍历字典

1 # 遍历字典
2 d = {"num1":1,"num2":2,"num3":3}
3 for key in d :
4     print(key,"=",d[key])

  输出结果:

num1 = 1
num2 = 2
num3 = 3

  示例三:range()函数

1 # range()内建函数,range(上限、下限、步长),无上限时,默认从0开始
2 for number in range(1,5):
3     print(number)
4 print("——range()无上限时,默认从0开始——")
5 for number in range(5):
6     print(number)

  输出函数:

1
2
3
4
——range()无上限时,默认从0开始——
0
1
2
3
4

3.并行迭代,考虑两个列表元素有的长度是否一致,不一致时使用zip

 1 #并行迭代
 2 names = ["anne","beth","alice","bela"]
 3 ages = [1,2,3,4]
 4 for i in range(len(names)):
 5     print(names[i]," is ",ages[i])
 6 # 并行迭代,考虑两个列表元素有的长度是否一致,不一致时使用zip
 7 print("---------------zip--------------------")
 8 names1 = ["anne","beth","alice","bela","bob"]
 9 ages1 = [1,2,3,4]
10 for names1,ages1 in zip(names1,ages1):
11     print(names1," is ",ages1)

  运行结果:

anne  is  1
beth  is  2
alice  is  3
bela  is  4
---------------zip--------------------
anne  is  1
beth  is  2
alice  is  3
bela  is  4

 4.按索引迭代

1 # 按索引迭代
2 names = ["anne","beth","alice","bela","bob"]
3 index = 0
4 for name in names:
5     if "ob" in name:
6         names[index] = "tom"
7     index +=1
8 print(names)

  输出结果:

['anne', 'beth', 'alice', 'bela', 'tom']

5.continue与break

  continue:跳出本次循环,进入下一次循环

  break:跳出本次循环,终止循环
 1 # contine 与break
 2 # continue:跳出本次循环,进入下一次循环
 3 # break:跳出本次循环,终止循环
 4 for i in range(1,5):
 5     if i==3:
 6         continue
 7     print(i)
 8 print("---------break-----------")
 9 for i in range(1,5):
10     if i==3:
11         break
12     print(i)

  输出结果:

1
2
4
---------break-----------
1
2

 



posted @ 2018-01-16 14:54  一个tester的独白  阅读(445)  评论(0编辑  收藏  举报