我正在尝试编写一个计算器,使用运算符 try 和 except。我的目标是让用户只输入 int (用于操作数)和 str (用于运算符)变量,如果其中一个等于“=”,它会给出结果。不幸的是,我的代码无法正常工作:它接受不正确的变量并仅在输入其他变量后才给出警告字符串。对不起我的英语不好,这不是我的母语
我的密码是:
result = None
operand = None
operator = None
wait_for_number = True
while True:
try:
operand1 = int(input("Enter 1st operand: "))
except ValueError:
print("Enter only numbers please")
continue
try:
operator = str(input("Enter operator (+ - * /): "))
except IndentationError:
print("Please enter only (+ - * /) :")
continue
try:
operand2 = int(input("Enter 2st operand: "))
except ValueError:
print("Enter only numbers please")
continue
if wait_for_number == True:
try:
if operator == "+":
result = operand1 + operand2
if operator == "-":
result = operand1 - operand2
if operator == "*":
result = operand1 * operand2
if operator == "/":
result = operand1 / operand2
elif operator == "=":
break
except ZeroDivisionError:
break
if operand1 == "=" or operand2 == "=" or operator == "=":
print(result)
我的目标是得到这样的结果:
>>> 3
>>> +
>>> 3
>>> 2
2 is not '+' or '-' or '/' or '*'. Try again
>>> -
>>> -
'-' is not a number. Try again.
>>> 5
>>> *
>>> 3
>>> =
Result: 3.0
我尝试使用休息时间,添加
operand1 = None / operand2 = None / operator = None
。我预计它会让用户只输入需要的变量,但它没有帮助。
我该怎么办?你能告诉我我的代码有什么问题吗?
希望这对您有进一步的帮助:
# read first operand until correct value is entered
operand1 = None
while operand1 == None:
try:
operand1 = int(input("Enter 1st operand: "))
except Exception as ex:
continue
# read operator until correct value is entered
operator = None
while operator == None:
try:
operator = str(input("Enter 1st operand: "))
if operator not in ['+', '-', '*', '/']:
raise ValueError('')
except Exception as ex:
continue
# read second operand until its a number
operand2 = None
while operand2 == None:
try:
operand2 = int(input("Enter 2st operand: "))
except Exception as ex:
continue
# make calculation
if operator == "+":
result = operand1 + operand2
elif operator == "-":
result = operand1 - operand2
elif operator == "*":
result = operand1 * operand2
elif operator == "/":
result = operand1 / operand2
print(result)
您想尝试捕获每个值并循环直到每个值正确。你也可以像你一样把它作为一个整体来做,但是每次你犯错的时候,比如为操作数 2 输入“a”,你的程序会再次期待整个公式。
您可以在
continue
要求新值的地方打印消息,指定它必须是数字或运算符。
祝你好运!