9.循环(Loop)

#1.for循环 :在可迭代的序列被穷尽时而终止

# 语法:

'''

#item 是可容纳“每一个元素”的变量名称,不能和关键字重名

#in 后面的元素是“可迭代的(uterable)”,比如列表

for item in iterable: #于...其中的每一个元素,做...事情

        do something

'''

'''

Demo 1:循环输出

for every_letter in 'Hello World':

    print(every_letter)


Demo2 循环输出

for i in range(0,11):

    print(str(i)+ '+ 1 =',i+1)     #需要进行类型转换,且需要逗号进行分割

'''

'''

Demo 3 将循环与选择结合进行应用:

song_list = ['Holy Driver','Thunderstruck','Rebel Rebel']

    for song in song_list:

        if song == song_list[0]:

            print(song,'-DIO')

        elif song == song_list[1]:

            print(song,'-AC/DC')

        else:

            print(song,'- David Bowie')

#将所需要的元素从列表中取出来,并输出相应的对应值

'''

'''

#嵌套循环(Nested Loop)

#举例:99乘法表Demo 4

for i in range (1,10):

    for j in range(1,10):

        res =('{} X {} = {}').format(i,j,i*j)

        print(res)

'''

#2. while循环 :在条件成立时,会一直执行下去(只要...条件成立,就一直做...)

# 语法:

# while condition:

#    do something

# while(True): #这种条件永远成立的循环,称为死循环(infinite Loop)

'''

Demo 5 在while循环中制造某种可以让循环停下来的条件

count = 0 #目的:计数器

while True:

    print('Repeat this line')

    count = count + 1 #重新赋值,每次在新的基础上+1

    if count == 5:

        break #上面条件成立,则停下来,跳出循环

'''

Demo 6: 改变使循环成立的条件

若输入密码3次则禁止输入密码


pwd_list = ['123456','654321']

def password_change(pwd_list=pwd_list):

    total = 3  # 计数器    

    while total > 0: #增加while循环

        pwd = input('input pwd:')

        if pwd in pwd_list:    

            print('login success!')

            return pwd_list #需要返回,不然还会接下来连着运行

        elif pwd not in pwd_list:

            print('password is wrong,plrase input again(you have only {} chances):'.format(total-1))

            total = total - 1 #密码输入错误,次数减少1,直至为0

        else:

            print('Your account has been suspended')

            return pwd_list

#在while代码块中又存在着第二层逻辑判断,是一个while-else嵌套逻辑

password_change()

#3.练习题


1.题目一

'''

#练习题#Demo 7 :设置一个函数,创建10个文本,并以数字连续命名for i in range(0,11):

path = (str(i)+'.txt' )

file = open(path,'w')

'''


2.题目二

'''

#Demo 8:计算复利

def invest(amount,rate,time):

    while int(time) > 0:

        amount = (amount*rate)+amount

        print('year '+ str(time)+':'+str(amount))

        time = time - 1

#input 应该放在函数调用部分

time = int(input("input year:"))

rate = int(input("input rate%:"))

rate = rate/100

amount = int(input("input peincipal amount:"))

invest(amount,rate,time) #一一对应

'''


2.题目三

'''

#Demo 9 打印1~100以内偶数

for i in range(1,101):

    if(i%2 == 0):

    print(i)

'''

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容