if條件判斷
if 條件判斷: 邏輯操作...... ......
判斷字符串是否為空
if a.strip(): #表示字符串不為空 pass
判斷是否為字典
d = dict(a=1) if isinstance(d,dict): print("{0} is a dict".format(d))
例子:
age = input("Please input your age: ") if age.strip(): if age.strip().isdigit(): # str.isdigit() 檢查字符串是否只由數字組成 if int(age) >= 18: print("你是一個成年人!") else: print("你還是一個小屁孩!") else: print("你輸入的不是數字!") else: print("你輸入的年齡不符合要求")
if 條件判斷: 邏輯操作...... ...... elif 條件判斷: 邏輯操作...... ...... else: 邏輯操作......
例子:
number = input("Please input a number: ") if int(number) > 0: print("{0} 是正數".format(number)) elif int(number) < 0: print("{0} 是負數".format(number)) else: print("輸入的數字是{0}".format(number))
while循環
while 條件判斷: 邏輯操作...... ......
例子:
a = 100 while a >= 1: print(a) a -= 1
while中使用break和continue
while 1: 這個比while True效率高,因為1更接近與機器編碼格式
break 滿足某個條件時,立即結束當前循環
continue 跳過當前循環的剩余語句,繼續進行下一輪循環
例子:
while 1: age = input("Please input your age: ") if age.strip(): if age.strip().isdigit(): if int(age) >= 18: print("你是一個成年人!") break # 遇到break就會終止,break之后的語句就都不會執行了 else: print("你還是一個小屁孩!") break else: print("你輸入的不是數字!") else: print("你輸入的年齡不符合要求,請重新輸入") continue # 遇到continue會跳出本次循環,進入下一次循環
九九乘法表
分析: 1 1x1=1 2 1x2=2 2x2=4 3 1x3=3 2x3=6 3x3=9 a x b = a*b a最小是1,最大為行號 b等於行號 代碼如下: for b in range(1, 10): for a in range(1, b+1): print("{0}x{1}={2}".format(a,b,a*b),end=" ") # python3中的空格 end="" if a == b: print() # 相當於換行 還有一種一行寫法: print('\n'.join(' '.join("{0}x{1}={2}".format(x, y, x*y) for x in xrange(1, y+1) )for y in xrange(1, 10)))
練習1:
輸入一行字符,分別統計出其中的英文字母、空格、數字和其他字符個數。
''' str.isdigit() 檢查字符串是否只由數字組成 str.isalpha() 檢查字符串是否只由字母組成 str.isspace() 檢查字符串是否只由空格組成 ''' something = input("請隨便輸入一些內容: ") while len(something) > 0: digit, letters, space, other = 0, 0, 0, 0 for i in something: if i.isdigit(): digit += 1 elif i.isalpha(): letters += 1 elif i.isspace(): space += 1 else: other += 1 print("數字有:{0}個\n英文字母有:{1}個\n空格有:{2}個\n其他字符有:{3}個".format(digit,letters,space,other)) break
練習2:
輸入一個數,求它的階乘。
num = int(input("請輸入一個數字: ")) factorial = 1 if num < 0: print("負數沒有階乘") elif num == 0: print("0 的階乘為 1") else: for i in range(1, num + 1): factorial = factorial * i print("{0} 的階乘為:{1}".format(num, factorial))
