Python:判断输入的是否是数字

参考链接:

https://www.cnblogs.com/zxmbky/p/9160822.html


代码:
#!/usr/bin/python3

num1 = input("first num :").strip()
num2 = input("second num: ").strip()

if not  num1.replace(".",'').isdigit():
    exit("fist num not num !")

if not  num2.replace(".",'').isdigit():
    exit("second num not num !")

sum = float(num1) + float(num2)
print("sum :", sum)

执行情况:
adams@adams:~$ python test.py  
first num :12345.43456
second num: 1212..1212^[[D^[[D^[[D
second num not num !
adams@adams:~$ python test.py 
first num :1212.1212
second num: 343434.3434
sum : 344646.4646
adams@adams:~$ python test.py  
first num :qw
second num: 1212
fist num not num !
adams@adams:~$ python test.py 
first num :1212121.455656
second num: sd
second num not num !
adams@adams:~$ 

其中
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。


Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值