码迷,mamicode.com
首页 > 其他好文 > 详细

三、流程控制

时间:2017-12-05 11:56:38      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:tin   爱情   迭代   any   嵌套循环   成功   margin   if...else   bsp   

3.1 判断 if

第一种:

age=28

 if age > 18:

     print(‘表白‘)

第二种if...else...

if age > 18 and age < 22:

    print(‘表白‘)

else:

      print(‘阿姨好‘)

第三种 #if多分支:

score=input(‘>>: ‘)

score=int(score)

if score >= 90:

    print(‘优秀‘)

elif score >= 80:

    print(‘良好‘)

elif score >= 60:

    print(‘合格‘)

else:

print(‘滚犊子‘)

 

if嵌套

 age=19

 is_pretty=True

 success=True

 if age > 18 and age < 22 and is_pretty:

     if success:

         print(‘表白成功,在一起‘)

     else:

         print(‘去他妈的爱情‘)

 else:

     print(‘阿姨好‘)

3.2 条件循环 while

3.2.1 格式一:while:条件循环

while 条件:

循环体

count=0

while count <= 10:

    print(count)

count+=1

 

嵌套循环

count=1

 while True:

     if count > 3:

         print(‘too many tries‘)

         break

 

     name=input(‘name>>: ‘)

     password=input(‘password>>: ‘)

     if name == ‘egon‘ and password == ‘123‘:

         print(‘login successfull‘)

         break

     else:

         print(‘user or password err‘)

         count+=1

 

例2:登陆,只允许登陆三次,使用tag

 count = 1

 tag=True

 while tag:

     if count > 3:

         print(‘too many tries‘)

         break

     name = input(‘name>>: ‘)

     password = input(‘password>>: ‘)

     if name == ‘egon‘ and password == ‘123‘:

         print(‘login successfull‘)

         while tag:

             cmd=input(‘cmd>>: ‘) #q

             if cmd == ‘q‘:

                 tag=False

                 continue

             print(‘run %s‘ %cmd)

     else:

         print(‘user or password err‘)

         count += 1

3.2.2 格式二:while+else

count=0

while count <= 5:

    if count == 3:

        break

    print(count)

    count+=1

else:

print(‘当while循环在运行过程中没有被break打断,则执行我‘)

3.3 for迭代式循环

3.3.1 格式一:

for i in range(1,10,2):
print(i)

例1:

l1=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]

for i in range(len(l1)):
print(i,l1[i])

3.3.2 格式二:for+else:

for i in range(5):

if i == 3:break

print(i)

else:

print(‘当循环在运行过程中没有被break打断,则执行我‘)

3.4 break和continue关键字

while+break

count=0

while True:

     if count == 5:

         break   #跳出本层循环

     print(count)

     count+=1

while+continue

#1,2,3,4,5,7

 

count=1

 while count <= 7:

     if count == 6:

         count += 1

         continue  #跳出本次循环

     print(count)

     count+=1

三、流程控制

标签:tin   爱情   迭代   any   嵌套循环   成功   margin   if...else   bsp   

原文地址:http://www.cnblogs.com/snailgirl/p/7985747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!