python如何判断用户输入的是不是数字_如何检查输入是否是Python中的数字?

I have a Python script which converts a decimal number into a binary one and this obviously uses their input.

I would like to have the script validate that the input is a number and not anything else which will stop the script.

I have tried an if/else statement but I don't really know how to go about it. I have tried if decimal.isint(): and if decimal.isalpha(): but they just throw up errors when I enter a string.

print("Welcome to the Decimal to Binary converter!")

while True:

print("Type a decimal number you wish to convert:")

decimal = int(input())

if decimal.isint():

binary = bin(decimal)[2:]

print(binary)

else:

print("Please enter a number.")

Without the if/else statement, the code works just fine and does its job.

解决方案

If the int() call succeeded, decimal is already a number. You can only call .isdigit() (the correct name) on a string:

decimal = input()

if decimal.isdigit():

decimal = int(decimal)

The alternative is to use exception handling; if a ValueError is thrown, the input was not a number:

while True:

print("Type a decimal number you wish to convert:")

try:

decimal = int(input())

except ValueError:

print("Please enter a number.")

continue

binary = bin(decimal)[2:]

Instead of using the bin() function and removing the starting 0b, you could also use the format() function, using the 'b' format, to format an integer as a binary string, without the leading text:

>>> format(10, 'b')

'1010'

The format() function makes it easy to add leading zeros:

>>> format(10, '08b')

'00001010'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值