# 1. 輸入 print("****** abc *******",end="") print("****** 123 *******") # == > ****** abc ************* 123 ******* 備註: end=""不換行 # 2. 運算符 a = input("Please input the first number:") b = input("Please input the second number:") print("The result %s + %s = %d"%(a,b,(int(a)+int(b)))) # == > The result 10 + 23 = 33 # 3. list arrayList = ["abc","123",[123,"345"],[["se","df"]]] a1 = arrayList[0] a2 = arrayList[2][0] a3 = arrayList[3][0][0] print("a1=%s\na2=%d\na3=%s"%(a1,a2,a3)) # == > a1=abc a2=123 a3=se # 4. 計算體重 a4 = 1.75 a5 = 80.5 BMI = a4 / a5**a5 if BMI > 32 : print("嚴重肥胖") elif BMI > 28: print("太重") elif BMI < 18.5: print("太輕") else : print("正常") # == > 太輕 # 5. 循環遍歷 names = ["a","b","c"] for name in names: print("name=%s"%name) # == > name=a name=b name=c sum = 0 for x in [1,23,3,3,3,3,3,0,5,5,5,5]: sum += x print("sum=%d"%sum) # == > sum=59 # 6. 計算1-100整數的和 listArray = list(range(101)) sum6 = 0 for s6 in listArray: sum6 += s6 print("0~100的整數和:%d",sum6) # == > 0~100的整數和:%d 5050 # 7. while循環計算 sum7 = 0 a7 = 0 while a7 < 101: sum7 = sum7 + a7 a7 += 1 print("while循環:%d",sum7) # == > while循環:%d 5050 # 練習請利用循環依次對list中的每一個名字打印出Hello, xxx!: L = ["Python","Objective-C","Swift"] for L1 in L: print("Hello,%s"%L1) # == > Hello,Python Hello,Objective-C Hello,Swift # 8.字典 dictionary = {"WebApp":"Python","iOS":"Objective-C","Android":"java"} dict8 = dictionary["WebApp"] # 拿到字典中key爲WebApp對應的Value print("拿到字典中key爲WebApp對應的value:%s"%dict8) # == > 拿到字典中key爲WebApp對應的value:Python bool = "iOS" in dictionary # 判斷key是否在字典中 print("判斷key是否在字典中不存在%d"%bool) # == > 判斷key是否在字典中不存在1 a8 = dictionary.get("PHP",-1) # 字典中的key不存在的話輸出-1 print("字典中的key是否存在不存在輸出本身設定的值:%d"%a8) # == > 字典中的key是否存在不存在輸出本身設定的值:-1 s8 = dictionary.pop("iOS") print("用pop刪除key對應的value爲%s"%s8) # == > 用pop刪除key對應的value爲Objective-C # 9.set:set和dict相似,也是一組key的集合,但不存儲value。因爲key不能重複,因此,在set中,沒有重複的key s = set(["1","2","3"]) print("打印一個set",s) # == > 打印一個set {'2', '1', '3'} s = set(["1","2","3","3","2","1"]) print("set能夠去重",s) # == > set能夠去重 {'2', '1', '3'} # add(key)方法能夠添加元素到set中,能夠重複添加,但不會有效果 s.add(4) print("輸出添加元素後的set",s) # == > 輸出添加元素後的set {'2', 4, '1', '3'} # 經過remove(key)方法能夠刪除元素: s.remove(4) print("輸出移除後的代碼",s) # == > 輸出移除後的代碼 {'2', '1', '3'} s1 = set([1,2,3]) s2 = set([2,3,4]) s3 = s1 & s2 print("交集結果",s3) # == > 交集結果 {2, 3} s4 = s1 | s2 print("並集結果",s4) # == > 並集結果 {1, 2, 3, 4} # 10.排序 sortArray = ["3","2","1"] sortArray.sort() print("排序後的數組:",sortArray) # == > 排序後的數組: ['1', '2', '3'] # 練習: 九九乘法表 m = 1 while m <= 9: n = 1 while n <= m: print("%d*%d=%-2d "%(n,m,m*n),end="") n += 1 print("") m += 1 #1*1=1 #1*2=2 2*2=4 #1*3=3 2*3=6 3*3=9 #1*4=4 2*4=8 3*4=12 4*4=16 #1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 #1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 #1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 #1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 #1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81