1. 程式人生 > >python中的分支和迴圈:for 迴圈,while迴圈,三元操作符,斷言,assert關鍵字,rang()函式總結

python中的分支和迴圈:for 迴圈,while迴圈,三元操作符,斷言,assert關鍵字,rang()函式總結

1.python中的條件語句

例:score=int(input('請輸入一個分數'))       
if 100>=score>=90:                                   
    print('A')                                                       
elif 90>score>=80:
    print('B')                                                                
elif 80>score>=60:                                               
    print('C')                                                  
elif 60>score>=0:                                             
    print('D')                                                                
else:                                                                     
    print('輸入錯誤')                                              
中直接使用elif不需要else if了      

三元操作符:small=x if x<y else y語法:x if 條件 else y

二元操作符:

x,y=4,5

if x<y:

  small=x

else:

   small=y

意思與上面三元操符意思相等                     

2.python中的斷言

assert這個關鍵字即為斷言,當關鍵字後面的條件為假時,程式自動崩潰並丟擲AssertionError的異常。

>>> assert 3==4
Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    assert 3==4
AssertionError

作用:可以用assert關鍵字在程式中置入檢查點,當需要確保程式中的某個條件一定為真才能讓程式正常工作的話,assert就有用

 

3

while迴圈

while 條件:

    迴圈體(條件為真)

for迴圈

語法:for  目標  in  表示式:

                 迴圈體

其中len(str)可以算出str的字元數量

 

4        rang()

語法:rang([start,]   stop   [,step=1])

      這個BIF有三個引數,其中用中括號括起來的是可選的,step=1表示第三個引數的預設值為1,意思是以1為單位步進

       該BIF表示生成一個從start引數值開始到stop引數的值結束的數字序列,其中,當括號內只有stop時,預設初始值是0