python - 创建我自己的错误消息?但是哪里?

标签 python message calculator

我已经创建了这个计算器,但是现在我想通过创建诸如“请仅输入数字”之类的错误消息来改进它。但是我应该在哪里添加这个呢?

这是我的代码:

def menu():
    print "Welcome to the calculator"
    print "The options are 1) Addition 2)Subtraction 3)Multiplication 4)Division 5)Exit        Calculator"
    return input("Choose your option")

def add(a,b):
    print a+b

def sub(a,b):
    print a-b

def mult(a,b):
    print a*b

def div(a,b):
    print a/b

loop=1
choice=0
while loop==1:
    choice=menu()
    if choice==1:
        add(input("Enter first number"),input("Enter second number"))
    elif choice==2:
         sub(input("Enter first number"),input("Enter second number"))
    elif choice==3:
          mult(input("Enter first number"),input("Enter second number"))
    elif choice==4:
          div(input("Enter first number"),input("Enter second number"))

    elif choice==5:
                loop=0
                exit()

谢谢:-)

最佳答案

基本思想是使用raw_input而不是输入。这给了我们一个来自用户的字符串,我们测试它是否是一个数字。如果这不是一个数字,我们会再次询问。

def myInput(message):

    # loop forever / until we have a valid input
    while True:

        # ask user for input
        user_input = raw_input(message)

        # check if its a number
        try:
            result = float(user_input)

            # Valid input, return the result
            return result

        except ValueError:
            # It couldn't be converted to a number, ask again
            print "Please only enter numbers"

            # Repeat the loop / ask again
            continue

然后在您当前使用 input('some message') 的地方使用 myInput('some message')

关于python - 创建我自己的错误消息?但是哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598271/

相关文章:

android - 如何更改异常消息, "The application ... has stopped unexpectedly. Please try again later.”

javascript - 创建 javascript/html 表单计算器 - 简单的方法吗?

c - GMP 计算器卡在幂数上

python - numpy 中的变量赋值不起作用?

python - 从帧字节获取帧值

python - 如何使用opencv python将YUV_420_888转换为BGR?

c++ - Win32 工具栏下拉按钮消息处理

Java:Joptionpane 消息对话框未打开

java - 为什么此代码不能进行加法运算?

python - 在 PostgreSQL 上使用 SQLAlchemy 创建全文搜索索引