-1

私はPythonで小さなコンソール電卓を書いて​​いました:

def calculator(num1=0, num2=0):
    conta = input("Type operation(+,x,/ or -:)")
    if (conta == "+"):
        print("Result:" + repr(num1) + " + " + repr(num2) + " is " + str(num1 + num2))
    elif (conta == "-"):
        print("Result:" + repr(num1) + " - " + repr(num2) + " is " + str(num1 - num2))
    elif (conta == "x"):
        print("Result:" + repr(num1) + " x " + repr(num2) + " is " + str(num1 * num2))
    elif (conta == "/"):
        print("Result: " + repr(num1) + " + " + repr(num2) + " is " + str(num1 / num2))
    else:
        print("Result:" + repr(num1) + conta + repr(num2) + " is Are you Joking?")

try:
    num1 = float(input("Type a number:"))
    num2 = float(input("Type a number:"))
    calculator(num1, num2)
except:
    print("Error.")
    exit()

IDLE シェルでは正常に動作します。置いた:

500.65 + 300 = 700.65
12 joke 12 = Are you Joking?

そして....PYファイルからロードすると、番号を聞かれます。私はそれを置きます。別の人に尋ねます。それを置く。操作を求めます。1つ入れました。ウィンドウが閉じます。

今度は Python コンソールで実行してみます。戻り値:

1 行目の SyntaxError => 無効な構文です。

それで、何が問題なのですか?私に何ができる?

4

2 に答える 2

4

主な問題は、間違ったインデントです。

また、operatorモジュールを使用して、ユーザー定義の文字列を数学演算でマッピングすることもできます。

import operator


def calculator(num1, num2, op):
    op_map = {'+': operator.add,
              '-': operator.sub,
              'x': operator.mul,
              '/': operator.div}

    if op not in op_map:
        raise ValueError("Invalid operation")

    return op_map[op](num1, num2)

num1 = float(input("Type a number:"))
num2 = float(input("Type a number:"))
op = input("Type operation (+,x,/ or -):")

print(calculator(num1, num2, op))

デモ:

Type a number:10
Type a number:10
Type operation(+,x,/ or -):+
20.0

Type a number:10
Type a number:10
Type operation (+,x,/ or -):illegal
Traceback (most recent call last):
  File "/home/alexander/job/so/test_mechanize.py", line 19, in <module>
    print calculator(num1, num2, op)
  File "/home/alexander/job/so/test_mechanize.py", line 11, in calculator
    raise ValueError("Invalid operation")
ValueError: Invalid operation
于 2013-09-07T18:54:03.777 に答える
0

python read eval ループでスクリプトを実行するには、次のようにする必要があります

>>> import script
于 2013-09-07T18:59:37.157 に答える