1 # 判斷輸入的字符串是否為數字 2 x = input("請輸入:") 3 # 是否有一個小數點 4 if x.count(".") == 1: 5 left, right = x.split(".") 6 # 小數點左右是否為純數字 7 if left.isdigit() and right.isdigit(): 8 print("正小數") 9 # 小數點左側是否由負號開頭且只有一個負號,右側是否為純數字 10 elif left.startswith('-') and left.count('-') == 1 and right.isdigit(): 11 left_right = left.split('-')[-1] 12 # 小數點和負號的中間部分是否為純數字 13 if left_right.isdigit(): 14 print("負小數") 15 else: 16 print("非數字") 17 # 是否沒有小數點 18 elif x.count(".") == 0: 19 # 是否為純數字 20 if x.isdigit(): 21 print("正整數") 22 # 是否為負號開頭且只有一個負號 23 elif x.startswith("-") and x.count("-") == 1: 24 x_right = x.split("-")[-1] 25 # 負號的右側部分是否為純數字 26 if x_right.isdigit(): 27 print("負整數") 28 else: 29 print("非數字") 30 else: 31 print("非數字") 32 else: 33 print("非數字")