首页 > 技术文章 > (五)流程控制if...else

morron 2018-04-16 22:18 原文

既然我们编程的目的是为了控制计算机能够像人脑一样工作,那么人脑能做什么,就需要程序中有相应的机制去模拟。人脑无非是数学运算和逻辑运算,对于数学运算在上一节我们已经说过了。对于逻辑运算,即人根据外部条件的变化而做出不同的反映。

以下是三种形式

形式一
if 条件1:
    代码1
    代码2
    代码3
形式二
if 条件1:
    代码1
    代码2
    代码3
    。。。
else:
    代码1
    代码2
    代码3
    。。。
形式三
if 条件1:
    代码1
    代码2
    代码3
    。。。
elif 条件2
    代码1
    代码2
    代码3
elif 条件3
    代码1
    代码2
    代码3
    。。。
形式四
if 条件1
    代码1
    代码2
    代码3
    if 条件2
        代码1
        代码2
        代码3
    else: 
        代码1
        代码2
        代码3
else:
    代码1
    代码2
    代码3
1 如果:女人的年龄>30岁,那么:叫阿姨
注意缩进
age_of=4
int(age_of),
if age_of>30:
    print('hello aunt')

else: print('hello miss')
age_of=int(input('input age')) #强制转换为整型
print(type(age_of))
if age_of > 30:
    print('hello aunt')

else: print('hello miss')
if 嵌套
score=int(input('pls input your score'))
if score>=90 :
    print('youxiu')
elif score>80:
    print('lianghao')
elif score>70:
        print('putong')

else: print('hencha')

  if 条件1:

    缩进的代码块

  elif 条件2:

    缩进的代码块

  elif 条件3:

    缩进的代码块

  ......

  else:  

    缩进的代码块
    
    
    

 today=input('>>>:')
if today in ['saturaday','sunday']:
    print('lang')
elif today in ['Monday','Tuesday','Wednessday','Thursday','Friday']:
    print('on duty')
else:
    print('''必须输入其中一种:  
    Monday
    Tuesday
    Wednessday
    Thursday
    Friday
    )

猜成绩

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

推荐阅读