print "HEllo !!"
print "Today, I will calculate something for you !!"#introduces itself
inp = True
def start():
print "type 1 for ADDITION"
print "type 2 for SUBTRACTION"
print "type 3 for MULTIPLICATION" #asks for the kind of calculation
print "type 4 for DIVISION"
press=int(raw_input())
if press >= 5 :
print "Choose a NUMBER which is less than 5 and you will get the answer!!"
print "-------------------------------"
if press == 1:
print "Enter your first number"
num1 = input()
print "enter your second number" #adds
num2 = input()
result = num1 + num2
print " Your answer is "+ str(result)
print "-------------------------------"
if press == 2 :
print "Enter your first number"
num1 = input()
print "enter your second number" #subtracts
num2 = input()
result = num1 - num2
print " Your answer is "+ str(result)
print "-------------------------------"
if press == 3:
print "Enter your first number"
num1 = input()
print "enter your second number"
num2 = input() #multiplies
result = num1 * num2
print " Your answer is "+ str(result)
print "-------------------------------"
if press == 4:
print "Enter your first number"
num1 = input() #divides
print "enter your second number"
num2 = input()
result = num1/num2
print " Your answer is "+ str(result)
print "-------------------------------"
while inp :
start()
所以我使用基本命令创建了这个计算器,唯一的问题是当有人输入一个字母时,它要求1到4的数字,它会显示python错误。相反,我希望能够打印一个自定义的错误,例如"只允许数字"或类似的东西,而不是python显示的常规错误。我可以做什么改变,以便它接收数字和字母,但是当有人输入一封信时会显示一个定制的错误? 附: :我要求var"按"而不是" num1"或" num2"
答案 0 :(得分:3)
你可以这样做:
num1 = None
while num1 is None:
try:
num1 = int(num1)
except ValueError:
print "ERROR: Invalid Input"
这会尝试将输入转换为整数。如果没有这样做,那么"中的代码除了"部分将运行。
答案 1 :(得分:0)
您可以使用str.isdigit()
检查字符串是否只包含数字,如果是这种情况则返回true,如果字符串包含任何非数字字符,则返回false。