首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在生产过程中显示错误代码而不是在程序结束时给出错误代码?

如何在生产过程中显示错误代码而不是在程序结束时给出错误代码?
EN

Stack Overflow用户
提问于 2022-06-15 08:26:44
回答 1查看 24关注 0票数 0

我对python很陌生,并且尝试制作我自己的简单计算器脚本。目标是存储数学运算符的输入,得到第一个值和第二个值,然后将所选的运算符应用到值中。它工作得很好,只是它在程序结束后抛出了“无效的数学运算符”错误。我希望它在用户输入错误操作符后立即显示错误(即: not +,-,*或/)。代码似乎没有那么有效,因为我仍然在学习如何优化和找到好的替代方案,而不是垃圾邮件,如果,elif。

代码语言:javascript
运行
复制
# 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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-15 08:43:59

代码语言:javascript
运行
复制
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))

这符合你的期望吗?

如果是这样的话,你应该把你的"!=“改为”不在“后面如果百灵鸟

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72628118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档