獲得更多資料歡迎進入我的網站或者 csdn或者博客園
本節主要介紹python,if條件語句,以及用法。下面附有之前的文章;
語句快介紹
語句快並非一種語句,是通過縮進形成的語句集合;
可以使用的縮進符:TAb建(相當於四個空格),4個空格,8個空格,可以成倍增加形成嵌套語句快;
一般來說使用四個空格是最規范的。
功能:語句快是在條件為真時執行(if)或執行多次(循環)的一組語句;
#偽代碼
this is a line
this is a condition:
this is a block
.....
there wo escaped the inner block
條件和條件語句
布爾型介紹
假(false):會被看做假的值:
FALSE ,None ,0 ,‘ ’ (沒有空格) ,“ ” (沒有空格) ,() ,[] ,{}
真(true):其他的都會被判定為真:
測試如下:
#假
>>> bool(False)
False
>>> bool(None)
False
>>> bool('')
False
>>> bool("")
False
>>> bool()
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
>>>
#真
>>> bool(True)
True
>>> bool('ddd')
True
>>> bool(1)
True
>>> bool([1])
True
>>> bool((1))
True
>>> bool({1})
True
>>>
條件執行和if語句
if語句
if語句可以實現條件執行,如果條件判定為真,則后面的語句塊執行,如果條件為假,語句塊就不會被執行。
#如果用戶輸入:0-9 就打印True
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 6
if 0<x<9:
print(True)
True
else語句
else子句(之所以叫子句,是因為它不是獨立的語句,而只能作為if語句的一部分)當條件不滿足時執行;
#如果用戶輸入:0-9 就打印True,不在之類輸出 False
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 11
>>> if 0<x<9:
... print(True)
... else:
... print(False)
...
False
elif語句
如果需要檢查多個條件,就可以使用elif,它是“else if”的簡寫,也是if和else子句的聯合使用——也就是具有條件的else子句。
#如果用戶輸入在0-9:就打印in 0-9 ,否則如果輸出大於9:就打印 >9,否則打印:<0
>>> x=int(input("Please enter an integer in 0-9 "))
Please enter an integer in 0-9 -1
>>> if 0<x<9:
... print("in 0-9")
... elif x>9:
... print(">9")
... else:
... print("<0")
...
<0
>>>
嵌套if語句
if語句里可以嵌套使用if語句:
x=int(input("Please enter an integer in 0-9 "))
if x>=0:
if x>9:
print("x>9")
elif x==0:
print("x==0")
else:
print('x<0')
Please enter an integer in 0-9 0
x==0
更復雜的條件:
條件運算符一覽:
#比較運算符
x==y x等於y
x<y x小於y
x>y x大於y
x>=y x大於等於y
x<=y x小於等於y
x!=y x不等於y
a<x<b x大於a小於b
#同一性運算符
x is y x和y是同一個對象
x is not y x和y是不同的對象
#成員資格運算符
x in y x是y容器的成員
x not in y x不是y容器的成員
同一性運算符說明:
看以來和一樣實際是時不同的,只有兩個綁定在相同的對象時才是真(當然當為數值變量時是和相同的):
#a與b不時指向同一對象
>>> a=[1,2]
>>> b=[1,2]
>>> a is b
False
#a與b指向同一對象
>>> a=b=[1,2]
>>> a is b
True
in成員資格運算符說明
#成員在序列中返回真
>>> a=[1,2,3]
>>> b=1
>>> c=4
>>> b in a
True
>>> c in a
False
>>>
邏輯運算符:
and :x and y 返回的結果是決定表達式結果的值。如果 x 為真,則 y 決定結果,返回 y ;如果 x 為假,x 決定了結果為假,返回 x。
or :x or y 跟 and 一樣都是返回決定表達式結果的值。
not : 返回表達式結果的“相反的值”。如果表達式結果為真,則返回false;如果表達式結果為假,則返回true。
>>> a=1
>>> b=2
>>> a and b
2
>>> a=1
>>> b=0
>>> a and b
0
>>> a or b
1
>>> not b
True
>>>
斷言簡介
if語句有個非常有用的近親,其工作方式多少有點像下面這樣(偽代碼):
if not condition:
crash program
這樣做是因為與其讓程序在晚些時候崩潰,不如在錯誤條件出現時直接讓它崩潰。一般來說,你可以要求某些條件必須為真。語句中使用的關鍵字為assert。
如果需要確保程序中的某個條件一定為真才能讓程序正常工作的話,assert語句就有用了,可以在程序中置入檢查點:
條件后可以添加字符串(用逗號把條件和字符串隔開),用來解釋斷言:
>>> age=-1
>>> assert 0<age<150,"The age must be realistic"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: The age must be realistic
>>>
>>> age=10
>>> assert 0<age<150,"The age must be realistic"
>>>
相關鏈接:
python3入門之類
python3入門之函數
python3入門之循環
python3之if語句
python3入門之賦值語句介紹
python3入門之print,import,input介紹
python3入門之set
python3入門之字典
python3入門之字符串
python3入門之列表和元組
python3入門之軟件安裝
python3爬蟲之入門和正則表達式