第七章 循环

知识点:

(1)for 循环:遍历可迭代对象的循环。可用 enumerate 函数访问可迭代对象的索引和元素。

x = ['a','B','c','D']
for i,char in enumerate(x):
    char = x[i]
    char = char.upper()
    x[i] = char
print(x)

(2)while 循环:只要表达式为真就一直执行的循环。语法:while 表达式:执行代码。

#优先执行循环语句,循环完毕之后再执行下一段代码
x = 10
while x>0:
    print(x)
    x -=1
print("happy new year!")

(3)break语句,continue语句。break用于终止循环,continue用于终止当前迭代,进入下一个迭代。

for i in range(100):
    if i>10:
        break
    print(i)


i = 1
while i<=5:
    if i==3:
        i +=1
        continue
    print(i)
    i +=1

(4)嵌套循环:外循环每遍历一次,内循环就遍历一次其可迭代对象的所有元素。

for i in range(1,3):
    print(i)
    for letter in ['a','b','c']:
        print(letter)

 课后习题:

一、打印一下列表["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]中的每一个元素。

x = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]
for i in range(len(x)):
    print(x[i])

二、打印第一题的每个元素及索引。

x = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]
z = dict()

for i,show in enumerate(x):
    z[i] = show
    while z[i] == "The Vampire Diaries":
        print(z)
        break

三、编写一个包含死循环和数字列表的程序(可选择输入q退出)。每次循环时,请用户猜一个在列表中的数字,然后告知其猜测是否正确。

n =[1,2,3,4]
while True:
    x = input("guess a number:")
    if x=="q":
        break
    x = int(x)
    if x in n:
        print("yes")
    else:
        print("no")
原文地址:https://www.cnblogs.com/yijierui/p/12831223.html