Python——流程控制语句

if语句

条件进行判断,满足,则执行里面 的内容;不满足,则执行if循环下面的语句

基本语法: 

if 判断条件:
    满足后执行语句

1 如果:女人的年龄>30岁,那么:叫阿姨

age_of_girl=31
if age_of_girl > 30:
    print('阿姨好')

2 如果:女人的年龄>30岁,那么:叫阿姨,否则:叫小姐

age_of_girl=18
if age_of_girl > 30:
    print('阿姨好')
else:
    print('小姐好')

 3 如果:女人的年龄>=18并且<22岁并且身高>170并且体重<100并且是漂亮的,那么:表白,否则:叫阿姨

复制代码
age_of_girl=18
height=171
weight=99
is_pretty=True
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    print('表白...')else:
    print('阿姨好')
复制代码

 4 关于表白的综合过程

age_of_girl=18
height=171
weight=99
is_pretty=True

success=False

if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    if success:
        print('表白成功,在一起')
    else:
        print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
    print('阿姨好')
View Code

5 关于成绩的判断

score=input('>>: ')
score=int(score)

if score >= 90:
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('普通')
else:
    print('很差')
View Code

while语句

条件判断语句,如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件,就这样一直到不满足为止; 如果条件为假,那么循环体不执行,循环终止,执行while下面的语句

while 条件:    
    # 循环体

例如:

#打印0-10之间的奇数
count=0
while count <= 10:
    if count%2 == 1:
        print('loop',count)
    count+=1
View Code

死循环

import time
num=0
while True:
    print('count',num)
    time.sleep(1)
    num+=1
View Code

嵌套循环

tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False
View Code

break和continue

#break用于退出本层循环
while True:
    print "123"
    break
    print "456"

#continue用于退出本次循环,继续下一次循环
while True:
    print "123"
    continue
    print "456"
View Code

for语句

基本语法:

for i in 可迭代对象:
        循环体

什么是可迭代对象这里先不解释,后面会介绍,这里可以认为可以for循环的就是可迭代对象。

在for循环中,同样可以使用break和continue

for运行的例子:

for i in range(1,10):  # 创建从1开始,9结束,步长为1的可迭代对象
    for j in range(1,i+1):  # 创建从1开始,i结束,步长为1的可迭代对象
        print('%s*%s=%s' %(i,j,i*j),end=' ')
    print()
View Code

在for循环中可以用enumerate来记录循环次数,循环次数是从0开始的。

比如:

for index, i in enumerate(range(100, 110)):
    print(index, i)

 

posted @ 2018-05-17 10:16  苦行僧95  阅读(309)  评论(0编辑  收藏  举报