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/  歡迎轉載 ~
相關文章
相關標籤/搜索