用一個實例編寫一個 Python 程序來檢查字符是不是數字。
這個 python 程序允許用戶輸入任何字符。接下來,我們使用 If Else 語句來檢查用戶給定的字符是否是數字。這裡, If 語句檢查字符是否大於等於 0,小於等於 9。如果為真,則為數字。否則,它不是一個數字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ch >= '0' and ch <= '9'):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
Python 字符是數字還是不輸出
Please Enter Your Own Character : 1
The Given Character 1 is a Digit
>>>
Please Enter Your Own Character : i
The Given Character i is Not a Digit
在本 Python 示例中,我們使用 ASCII 值來檢查字符是否為數字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ord(ch) >= 48 and ord(ch) <= 57):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
Please Enter Your Own Character : 7
The Given Character 7 is a Digit
>>>
Please Enter Your Own Character : @
The Given Character @ is Not a Digit
在本例 python 代碼中,我們使用 If Else 語句中的 isdigit 字符串函數來檢查給定字符是否為數字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ch.isdigit()):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
原創文章,作者:RB2TE,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127313.html