1

この簡単なプロジェクトを実行する必要があります。これは私がこれまでに持っているコードであり、完全に正常に機能します。しかし、誰かが文字や不明な記号を入力すると、プログラムがクラッシュします。このエラープルーフを作成し、間違ったものが入力された場合にメッセージを表示または印刷するにはどうすればよいですか?

def excercise5():

    print("Programming Excercise 5")
    print("This program calculates the cost of an order.")
    pound = eval(input("Enter the weight in pounds: "))
    shippingCost = (0.86 * pound) + 1.50
    coffee = (10.50 * pound) + shippingCost
    if pound == 1:
        print(pound,"pound of coffee costs $", coffee)
    else:
        print(pound,"pounds of coffee costs $", coffee)
    print()

excercise5()
4

5 に答える 5

5

を使用しないことをお勧めしevalます。セキュリティの観点からは良くありません。目的のタイプに明示的に変換するだけです。

pound = float(input("Enter the weight in pounds: "))

無効な入力を処理するには:

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Invalid input.')
    return
# the rest of the code

または:

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Invalid input.')
else:
    # the rest of the code

変換が成功すると終了する無限ループで入力をラップすることもできます。

while True:
    try:
        pound = float(input("Enter the weight in pounds: "))
    except ValueError:
        print('Invalid input. Try again.')
    else:
        break
# do the rest with `pound`
于 2013-02-21T21:52:01.303 に答える
0

例外処理を使用します。

誰かがあなたに無効な入力を与えてもPythonはクラッシュせず、代わりに例外をスローします。Pythonにプログラムを終了させる代わりに、そのような例外をキャッチして処理することができます。

この場合、浮動小数点数のみが必要なので、実際には使用しないでくださいeval()。これには多くの異なる入力が必要であり、多くの異なる例外がスローされます。

代わりに関数を使用してください。間違った入力をした場合float()にのみ、をスローします。ValueError次に、それをキャッチしてエラーメッセージを表示します。

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Not a valid number!')
    return
于 2013-02-21T21:52:55.413 に答える
0

ステートメントをtry/exceptで囲みます

def excercise5():
    print("Programming Excercise 5")
    print("This program calculates the cost of an order.")
    pound = eval(input("Enter the weight in pounds: "))
    try:
        shippingCost = (0.86 * pound) + 1.50
        coffee = (10.50 * pound) + shippingCost
        if pound == 1:
            print(pound,"pound of coffee costs $", coffee)
        else:
            print(pound,"pounds of coffee costs $", coffee)
    except ValueError:
        print("Please Enter a valid number")
    print()

注意する必要があります:弾丸の校正が不可能であるように、何かを「エラープルーフ」する方法はありません。コーディングと同じように、十分な大きさの弾丸が何かに浸透します。あなたができることは良いコードを書くことだけです。コーディングにおいて絶対的なものはありません。

于 2013-02-21T21:54:00.593 に答える
0

asciiを使用できませんでしたか?たとえば、文字列を数値に変換し、数値ウィンドウ内にない結果を無視します。たとえば、「if (c <= 47 and c >= 57):」などです。これにより、クラッシュが停止するはずです。私は思う:P

于 2015-11-15T18:41:03.863 に答える
0

例外は、重要なプログラムでエラーを快適にルーティングして処理する方法です。しかし、明確な概念は、プログラムが大きくなったときにそれを無作為にハックしないようにするのに役立ちます。(たとえば、ビルトインを遠くで
キャッチしたり、たまたま ing / 続行したりすると、すぐに毛むくじゃらになります。)ValueErrorreturn

発生したエラーには主な違いがあります

  • 無効な/奇妙なユーザー入力による
  • バグによる
  • 動的なシステム/環境の制限によって。

これらのエラーを分離、ルーティング、および処理する合理的な方法は次のとおりです。

  • (A) ユーザー入力エラーが発生する可能性がある時点で非常に早い段階でキャッチまたは比較します。単純な回復/繰り返しの場合はすぐに反応します。それ以外の場合 (ブレイクアウト用)は、さらに下またはコール スタックの下部で (または既定のハンドラーによって)キャッチして区別できる強化された例外に変換します。sys.excepthook

  • (B) バグの例外をコール スタックの一番下にクラッシュさせます - 未処理。または、快適なバグ プレゼンテーションとフィードバック アクションを開始することもできます。

  • (C) システム環境エラーについては、開発の現在の段階でどの程度のコンテキスト、詳細、および快適な情報を提示するかに応じて、(A) と (B) のいずれかのアプローチを選択します。

このようにして、これはあなたの例でユーザー指向のエラー処理のスケーラブルなパターンになる可能性があります:

# Shows scalable user oriented error handling

import sys, traceback

DEBUG = 0

class UserInputError(Exception):
    pass

def excercise5():

    print("Programming Excercise 5")
    print("This program calculates the cost of an order.")

    # NOTE: eval() and input() was dangerous
    s = input("Enter the weight in pounds: ")
    try:        
        pound = float(s) 
    except ValueError as ev:
        raise UserInputError("Number required for weight, not %r" % s, ev)
    if pound < 0:
        raise UserInputError("Positive weight required, not %r" % pound)

    shippingCost = (0.86 * pound) + 1.50
    coffee = (10.50 * pound) + shippingCost
    if pound == 1:
        print(pound,"pound of coffee costs $", coffee)
    else:
        print(pound,"pounds of coffee costs $", coffee)
    print()

if __name__ == '__main__':
    try:
        excercise5()
    except UserInputError as ev:
        print("User input error (please retry):")
        print(" ", ev.args[0])
        if DEBUG and len(ev.args) > 1:
            print("  EXC:", ev.args[1], file=sys.stderr)
    except (EnvironmentError, KeyboardInterrupt) as ev:
        print("Execution error happend:")
        print(" ", traceback.format_exception_only(ev.__class__, ev)[0])
    except Exception:
        print("Please report this bug:")
        traceback.print_exc()
于 2016-08-26T10:53:32.433 に答える