学习python课程第四天

一.流程控制之 if  else:

既然我们编程的目的是为了控制计算机能够像人脑一样工作,那么人脑能做什么,就需要程序中有相应的机制去模拟。

人脑无非是数学运算和逻辑运算,对于数学运算在上一节我们已经说过了。对于逻辑运算,即人根据外部条件的变化而做出不同的反映,比如:

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.if 套 if
在表白的基础上继续:
如果表白成功,那么:在一起
否则:打印。。。

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('阿姨好')

5.如果:成绩>=90,那么:优秀

       如果成绩>=80且<90,那么:良好

       如果成绩>=70且<80,那么:普通

       其他情况:很差

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

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



二.流程控制之while:
 1 为何要用循环
程序员对于重复使用一段代码是不耻的, 而且如果以后修改程序会很麻烦.
while条件循环, 语法如下:
while 条件:    
     循环体
 
     如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
     如果条件为假,那么循环体不执行,循环终止.
打印0-10
count=0
while count <= 10:
    print(count)
    count+=1
打印0-10之间的偶数
count=0
while count <= 10:
    if count%2 == 0:
        print(count)
    count+=1
打印0-10之间的奇数
count=0
while count <= 10:
    if count%2 == 1:
        print(count)
    count+=1
2.死循环:
import time
num=0
while True:
    print('count',num)
    time.sleep(1)
    num+=1 
4 循环嵌套与tag
tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False
5.break 与 continue
break可以把while的代码块循环强制停止,
continue可以把while代码块循环的本次停止.

三.流程控制之for循环:

1 迭代式循环:for,语法如下

  for i in range(10):

    缩进的代码块

2.循环嵌套:

for i in range(1,10):
    for j in range(1,i+1):
        print('%s*%s=%s' %(i,j,i*j),end=' ')
    print()

猜你喜欢

转载自www.cnblogs.com/lvyipin1/p/9649156.html