3

申し分なく、私はプロジェクトのためにこれを行っていますが、ゼロまたは平方根で除算しようとすると、プログラムが終了する負の数になります。コードに挿入してメッセージを表示し、再度値の入力を求めるプロンプトを表示できるものを見つけようとしましたが、挿入しようとしたものはすべて、プログラムを起動するとすぐに終了します。

これは、クラッシュを修正するために何も挿入されていない電卓です。

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 を入力すると、プログラムがクラッシュすることもわかっています。下にある行に戻す方法はありますか?

また、プログラムを終了する場合、プログラムを表示した直後に終了したり、コマンドを同時に実行したりしているため、表示されるはずのメッセージを読み取ることができません。いずれにせよ、メッセージは読めません。別のダイアログ ウィンドウにメッセージを表示して、ウィンドウを閉じたときにプログラムを終了させる方法はありますか? または、少なくとも閉鎖する前に遅らせる方法はありますか?

用語が間違っている場合は修正してください。私はまだこれに少し慣れていません。

また、いつものように、プログラムのどの部分についても (建設的な) フィードバックをお待ちしております。

4

5 に答える 5

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)
于 2011-07-13T01:58:26.113 に答える
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

乾杯!

于 2011-07-13T02:06:51.620 に答える
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."
于 2011-07-13T02:01:42.100 に答える
0

これはあなたのコーディングの質問に答えるものではありませんが、コメントする価値があると思います。

sqrt:負の数の平方根は虚数です。Pythonは、で複素数をサポートしcomplex(real_part, imaginary_part)ます。

したがって、平方根の計算は次のように書くことができます。

elif choice == "5":
    numberA = raw_input("Enter the number you wish to find the square root of: ")
    numberA = float(numberA)
    if numberA < 0:
        sqrt_numberA = complex(0, sqrt(abs(numberA)))
    else:
        sqrt_numberA = sqrt(numberA)

    print "Your result is:", sqrt_numberA

除算:0による除算は無限大です。Pythonは「inf」で無限を示します。実際、1E309より大きい数値の「inf」を返します。

>>> 1E309
inf

そして、これらの数値の2つを除算すると、「nan」が生成されます。

>>> 1E309/1E309
nan

あなたが書くことができるように:

elif choice == "4":
    numberA = raw_input("Enter your dividend: ")
    numberB = raw_input("Enter your divisor: ")
    try: 
        div = division(numberA, numberB)
    except ZeroDivisionError:
        div = 'inf'

    print "The quotient of those numbers is:", div

このコードをさらに拡張して、numberAが負の場合に-infを返し、0/0などの状況を考慮に入れる必要があります。

于 2011-07-13T05:50:31.377 に答える
0

try:...except:ステートメントの形式が間違っています。これを試して:

elif choice == "4":
    numberA = raw_input("Enter your dividend: ")
    numberB = raw_input("Enter your divisor: ")
    print "The quotient of those numbers is:"
    try:
        print division(numberA, numberB)
    except ZeroDivisionError:
        print "You cannot divide by zero. Please choose another divisor."
于 2011-07-13T02:02:12.317 に答える