Python-条件语句和循环语句

 

·条件语句

笔记:post

  If  布尔值:优化

    print(‘hello,world!’)spa

当表达式为布尔表达式时,Flase   None  0   ””    ()    []    {} 都视为code

 

@ if-else 语句


 当if语句成立,运行if语句后缩进的代码,若是if语句不成立,则运行else语句后缩进的代码。orm

name = input("What is your name?")
if name.endswith('jimmy'):  #当输入为Jimmy时,表达式为真,否者为假。
    print('hello,{}'.format(name))
else:                       #当输入为其余时,if语句为假,才会运行else语句。
    print('None')

当输入为jimmy时,条件语句成立:blog

What is your name?jimmy
hello,jimmy

当输入为其余值时,条件语句不成立:input

What is your name?tom
None

 

@ elif 语句


建立一个成绩等级查询系统,当用户输入成绩时,能够看到成绩对应等级:博客

score = int(input("请输入你的成绩:"))
if score >= 90: 
    print('优秀')
if score >= 80:
    print('良好')
if score >= 70:
    print('通常')
if score >= 60:
    print('及格')
if score < 60:
    print('不及格')
打印结果: 请输入你的成绩:80
良好
通常
及格

运行过程当中发现:if语句逐条判断,当输入成绩80时,知足前中间3个if语句,程序打印了3个输出结果,显然不知足要求。it

接着来修改程序,把if语句替换成elif后:io

score = int(input("请输入你的成绩:"))
if score >= 90: 
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('通常')
elif score >= 60:
    print('及格')
elif score < 60:
    print('不及格')
打印结果: 请输入你的成绩:80
良好

再次输入成绩80,第一条语句判断不成立,接着往下执行,只要有一个elif成立时,就再也不判断后面的elif语句。

 

@ assert 断言


正常的分数值在0-100之间,以上程序当输入大于100或者小于0时程序还能照常运行,下面使用断言法来限定分数的范围:

score = int(input("请输入你的成绩:"))
assert score <= 100 and score >= 0,'请输入0-100之间的成绩'
if score >= 90: 
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('通常')
elif score >= 60:
    print('及格')
elif score < 60:
    print('不及格')
打印结果:
请输入你的成绩:-1
Traceback (most recent call last):
  File "test1.py", line 3, in <module>
    assert score <= 100 and score >= 0,'请输入0-100之间的成绩'
AssertionError: 请输入0-100之间的成绩
请输入你的成绩:101

Traceback (most recent call last):
  File "test1.py", line 3, in <module>
    assert score <= 100 and score >= 0,'请输入0-100之间的成绩'
AssertionError: 请输入0-100之间的成绩

请输入你的成绩:80
良好

 

·循环语句

 
 笔记:
   while 布尔值:
    表达式

@ while循环语句:


 要让以上的查询系统知足屡次查询的条件,须要继续优化代码,使用while语句:

while True:
    score = int(input("请输入你的成绩:"))
    assert score <= 100 and score >= 0,'请输入0-100之间的成绩'
    if score >= 90: 
        print('优秀')
    elif score >= 80:
        print('良好')
    elif score >= 70:
        print('通常')
    elif score >= 60:
        print('及格')
    elif score < 60:
        print('不及格')

这样就能够实现屡次查询成绩啦,当输入小于0或者大于100的值时,assert断言将起做用。

 

end~

 
****** 几米花的Python ****** 博客主页:https://www.cnblogs.com/jimmy-share/  欢迎转载 ~