我对python很陌生,并且尝试制作我自己的简单计算器脚本。目标是存储数学运算符的输入,得到第一个值和第二个值,然后将所选的运算符应用到值中。它工作得很好,只是它在程序结束后抛出了“无效的数学运算符”错误。我希望它在用户输入错误操作符后立即显示错误(即: not +,-,*或/)。代码似乎没有那么有效,因为我仍然在学习如何优化和找到好的替代方案,而不是垃圾邮件,如果,elif。
# primitive calculator script
error = "Invalid mathematical operation." # global error variable
ops = ["+", "-", "*", "/"]
lark = input("Enter a mathematical operation (+, -, / or *): ")
if lark != ops:
print("Error. Line 8")
quit()
exart = input("Enter the first value: ")
blip = input("Enter the second value: ")
if lark == "+":
print("Sum of these numbers is:", int(blip)+int(exart))
elif lark == "-":
print("Subtraction of these numbers is:", int(blip)-int(exart))
elif lark == "*":
print("Product of these numbers is:", int(blip)*int(exart))
elif lark == "/":
print("Division of these numbers is: ", int(blip)/int(exart))
发布于 2022-06-15 00:43:59
error = "Invalid mathematical operation." # global error variable
ops = ["+", "-", "*", "/"]
lark = input("Enter a mathematical operation (+, -, / or *): ")
if lark not in ops:
print("Error. Line 8")
quit()
exart = input("Enter the first value: ")
blip = input("Enter the second value: ")
if lark == "+":
print("Sum of these numbers is:", int(blip)+int(exart))
elif lark == "-":
print("Subtraction of these numbers is:", int(blip)-int(exart))
elif lark == "*":
print("Product of these numbers is:", int(blip)*int(exart))
elif lark == "/":
print("Division of these numbers is: ", int(blip)/int(exart))
这符合你的期望吗?
如果是这样的话,你应该把你的"!=“改为”不在“后面如果百灵鸟
https://stackoverflow.com/questions/72628118
复制