Python中循環及判斷語句


循環判斷條件是編程語言中一個很重要的部分,python也不例外,循環判斷條件一般結合continue,return,break關鍵字來判斷,這些關鍵字用法與java中基本一致

一、if判斷語句

判斷條件返回的結果為布爾值,在python中,布爾值為True/False,首字母必須大寫,否則將出現如下異常

>>> ls=false
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined
View Code

python中,值不為空時,判斷條件為True,如

>>> str='flag'
>>> if str:
...     print("not empty")
... else:
...     print("empty")
... 
not empty
>>> str=''
>>> if str:
...     print("not empty")
... else:
...     print("empty")
... 
empty
View Code

單個判斷條件

>>> tup=('dog','cat','water','bj')
>>> for val in tup:
...      if len(val) < 3:
...          print("the length of " + val + " is less than 3")
...      elif len(val) == 3:
...          print("the length of " + val + " is 3")
...      else:
...          print ("the length of " + val + " is more than 3")
... 
the length of dog is 3
the length of cat is 3
the length of water is more than 3
the length of bj is less than 3

多個判斷條件可以使用and或者or

>>> name="xiao"
>>> if name != "" and len(name) > 3:
...     print ("long name")
... else:
...     print ("short name")
... 
long name
>>> weight=100
>>> if weight > 150 or weight < 60:
...     print ("no normal weight")
... else:
...     print ("normal weight")
... 
normal weight

 判斷某個值是否在列表中存在

>>> ls=['car','cat','dog']
>>> if 'car' in ls:
...     print("yes, it is car")
... else:
...     print("no car")
... 
yes, it is car

while循環

>>> i=5
>>> while(i>1):
...     i-=1
...     print(i)
... 
4
3
2
1

for循環

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM