if語句在java平時的代碼中應用很多,在python中也一樣,功能也相似,但細節的地方稍微有些差別。下面是一個例子:
age =
if age < :
print("too young")
elif age > :
print("for free")
elif age < or age > :
print("half")
elif age >= and age <=:
print("full")
python中的and代替了Java中的邏輯與&,or代替了java中的邏輯或 | ,在python中沒有短路與&&和短路或 ||的概念,elif代替java中的else if其他地方都基本類似。最後else語句塊運用是一緻的,在if和elif中不符合條件的内容,都會在else中起作用。
age =
if age > :
print("not")
else:
print("yes")
== 和!=的用法也是一樣的,字元串的比較是,後面的值需要加上引号。
age =
if age == :
print("right")
elif age != :
print("wrong")
清單的判斷中,判斷清單是否為空的方式不是很一樣。判斷一個元素是否在清單中使用in或者是not in來進行判斷。
tuple = (,)
if tuple:
print(tuple)
if in tuple:
print("200 in the tuple")
if not in tuple:
print("300 not in the tuple")
else:
print("empty")
判斷清單是否為空,python是這樣處理的,當一個清單的元素大于等于一個,就傳回True,否則就傳回False。