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:The alternative is to use exception handling; if a
ValueError
is thrown, the input was not a number:Instead of using the
bin()
function and removing the starting0b
, you could also use theformat()
function, using the'b'
format, to format an integer as a binary string, without the leading text:The
format()
function makes it easy to add leading zeros: