Python 程序:检查字符是否为数字

用一个实例编写一个 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/n/127313.html

(0)
RB2TERB2TE
上一篇 2024-10-03
下一篇 2024-10-03

相关推荐

发表回复

登录后才能评论