我有一个Python脚本,可以将十进制数转换为二进制数,这显然需要使用它们的输入。
我希望脚本能验证输入是否为数字,而不是其他任何会停止脚本的东西。
我尝试了if/else语句,但我真的不知道该怎么做。我尝试了if decimal.isint():
和if decimal.isalpha():
,但当我输入字符串时,它们只会抛出错误。
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.")
如果没有if / else语句,代码可以正常工作并完成其工作。
isdigit
,事实上,这会导致错误。 - elssarraw_input()
。 - Martijn Pieters