Python计算器除零/平方根负整数导致程序崩溃

3 投票
5 回答
2476 浏览
提问于 2025-04-16 21:23

好的,我在做一个项目,每当我尝试让程序进行除以零或者对负数开平方时,程序就会直接关闭。我试过在代码里插入一些东西,想让它显示一个提示信息,然后再让用户输入值,但我插入的每一段代码都导致程序在启动时立刻关闭。

这是没有任何修复代码的计算器。

import math

def convertString(str):
    try:
        returnValue = int(str)
    except ValueError:
        returnValue = float(str)
    return returnValue

def addition(a, B):
    return convertString(a) + convertString(B)

def subtraction(a, B):
    return convertString(a) - convertString(B)

def multiplication(a, B):
    return convertString(a) * convertString(B)

def division(a, B):
    return convertString(a) / convertString(B)

def sqrt(a):
    return math.sqrt(convertString(a))

keepProgramRunning = True

print "Welcome to [Removed]'s 2011 4-H Project! This is a simple calculator coded in  Python, which is a high-level programming language. Java, C, C++, and Perl are  other high-level programming languages that you may have heard of."

while keepProgramRunning:
    print ""
    print "Please choose what you would like to do:"
    print ""
    print "1) Addition"
    print "2) Subtraction"
    print "3) Multiplication"
    print "4) Division"
    print "5) Square Root"
    print "6) Quit Program"

    choice = raw_input()    

    if choice == "1":
        numberA = raw_input("Enter your first addend: ")
        numberB = raw_input("Enter your second addend: ")
        print "The sum of those numbers is:"
        print addition(numberA, numberB)
    elif choice == "2":
        numberA = raw_input("Enter your first term: ")
        numberB = raw_input("Enter your second term: ")
        print "The difference of those numbers is:"
        print subtraction(numberA, numberB)
    elif choice == "3":
        numberA = raw_input("Enter your first factor: ")
        numberB = raw_input("Enter your second factor: ")
        print "The product of those numbers is:"
        print multiplication(numberA, numberB)
    elif choice == "4":
        numberA = raw_input("Enter your dividend: ")
        numberB = raw_input("Enter your divisor: ")
        print "The quotient of those numbers is:"
        print division(numberA, numberB)
    elif choice == "5":
        numberA = raw_input("Enter the number you wish to find the square root of: ")
        print "Your result is:"
        print sqrt(numberA)
    elif choice == "6":
        print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
        keepProgramRunning = False
    else:
        print "Please choose a valid option."
        print "\n"

我不太确定该插入什么以及插在哪里才能解决程序崩溃的问题,但我觉得问题可能出在我插入的位置。

我尝试插入类似这样的代码:

except ValueError:
            print "You cannot divide by zero. Please choose another divisor."
            numberB = raw_input("Enter your divisor: ")

这样可以吗?我该把它插在哪里?如果不行,那什么可以用,应该放在哪里呢?

我尝试把它放在

numberB = raw_input("Enter your divisor: ")

之后,这样那部分代码就会变成

elif choice == "4":
    numberA = raw_input("Enter your dividend: ")
    numberB = raw_input("Enter your divisor: ")
        except ValueError:
            print "You cannot divide by zero. Please choose another divisor."
            numberB = raw_input("Enter your divisor: ")
    print "The quotient of those numbers is:"
    print division(numberA, numberB)

但是正如我所说的,程序在我这样做后会立刻关闭。另外,我知道如果用户再次输入0,程序还是会崩溃。有没有办法让程序返回到它刚才的位置?

还有,关于程序关闭的问题,程序应该显示的提示信息在程序关闭后根本看不清楚,或者命令是同时执行的。无论如何,信息都无法被读取。有没有办法让提示信息在一个单独的对话框中显示,这样程序在关闭这个对话框后再关闭?或者至少有办法让它在关闭前延迟一下吗?

如果我用词不当,请纠正我。我对这些还不是很熟悉。

另外,任何对程序的(建设性)反馈我都非常欢迎。

5 个回答

1

你应该使用异常处理,就像你在 convertString 函数中已经做的那样。

try:
    result = division(numberA, numberB)
    print "The quotient of those numbers is:"
    print result
except ZeroDivisionError:
    print "You cannot divide by zero. Please choose another divisor."
2

这是没有异常处理的答案。基本上,你在一个无限循环的开头检查输入是否有问题,但当你发现输入都是正确的,就跳出这个循环。

对于你的平方根:

elif choice == "5":
    while True:
        numberA = raw_input("Enter the number you wish to find the square root of: ")
        if float(numberA) >= 0:
            break
        print "Cannot take the square root of a negative number."
    print "Your result is:", sqrt(numberA)

对于除法:

elif choice == "4":
    numberA = raw_input("Enter your dividend: ")
    while True:
        numberB = raw_input("Enter your divisor: ")
        if numberB != "0":
            break
        print "You cannot divide by zero. Please choose another divisor."
    print "The quotient of those numbers is:", division(numberA, numberB)

为了让你的程序在关闭之前停顿一下:

elif choice == "6":
    print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
    raw_input('')
    keepProgramRunning = False

祝好运!

3

问题在于你试图在异常被抛出之前去捕捉它。相反,你可以试试这样做:

elif choice == "4":
    numberA = raw_input("Enter your dividend: ")
    numberB = raw_input("Enter your divisor: ")
    while float(numberB) == 0:
        print "You cannot divide by zero. Please choose another divisor."
        numberB = raw_input("Enter your divisor: ")
    print "The quotient of those numbers is:"
    print division(numberA, numberB)

撰写回答