1. 程式人生 > 實用技巧 >Python全棧課程004

Python全棧課程004

程式結構

  • 順序
  • 選擇
  • 迴圈

選擇(分支)語句

  • if語句
  • if 表示式:
    語句1
    語句2
    else:
    語句
a = input("請輸入數字:") #字串
a = int(a)
if a < 10:
    print("Python全棧課程")
else:
    print("Linux從入門到放棄")
請輸入數字:100
Linux從入門到放棄
#輸入成績,100-90分為優秀,89-80分為良好,79-60分為及格,60分以下為不及格
score = input("input your score:")
score = int(score)
if score <= 100 and score >= 90:
    print("優秀")
else:
    if score <= 89 and score >= 80:
        print("良好")
    else:
        if score <= 79 and score >=60:
            print("及格")
        else:
            print("不及格")       
input your score:99
優秀
score = input("input your score:")
score = int(score)
if score <= 100 and score >= 90:
    print("優秀")
elif score <= 89 and score >= 80:
    print("良好")
elif score <= 79 and score >=60:
    print("及格")
else:
    print("不及格")
input your score:99
優秀

pass關鍵字

  • 佔位符
a = 1
if a < 2:
  File "<ipython-input-12-504e793a112e>", line 2
    if a < 2:
             ^
SyntaxError: unexpected EOF while parsing
a = 1
if a < 2:
    pass
a = 1
if a < 2:
    pass #跳過此語句,而不是終止
    print("pass")
pass

迴圈

  • for迴圈
  • while迴圈
list = [1,2,3,4]
for i in list:
    print(i)
1
2
3
4
list = [1,2,3,4]
for i in list:
    print("**********************")
    if i % 2 == 0:
        print("Python全棧課程")
    else:
        print("Linux從入門到放棄")
    print("**********************")
**********************
Linux從入門到放棄
**********************
**********************
Python全棧課程
**********************
**********************
Linux從入門到放棄
**********************
**********************
Python全棧課程
**********************
print(1)
print(2)#print()自動換行
1
2
print(1, end = "") #end的預設值為\n(換行)
print(2, end = "")
12
for i in range(1,101,2):#range:從1開始到100結束,步長為2
    print(i, end = " ")
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 
list = [1,2,3,4]
for i in list:
    print(i)
else:
    print("python全棧課程")
    print("Linux從入門到放棄")
1
2
3
4
python全棧課程
Linux從入門到放棄