2012-11-22 58 views
0

我剛剛在python中編寫了一個簡單的計算器腳本,通常Python應該默認識別( - )減號,(*)乘法,(/)除號,但在考慮這個腳本時,它無法識別跡象。請留下您的意見,以清除我...python中的基本計算器程序

#! /usr/bin/python 

print("1: ADDITION") 
print("2: SUBTRACTION") 
print("3: MULTIPLICATION") 
print("4: DIVISION") 

CHOICE = raw_input("Enter the Numbers:") 

if CHOICE == "1": 
    a = raw_input("Enter the value of a:") 
    b = raw_input("Enter the value of b:") 
    c = a + b 
    print c 

elif CHOICE == "2": 
    a = raw_input("Enter the value of a:") 
    b = raw_input("Enter the value of b:") 
    c = a - b 
    print c 

elif CHOICE == "3": 
    a = raw_input("Enter the value of a:") 
    b = raw_input("Enter the value of b:") 
    c = a * b 
    print c 

elif CHOICE == "4": 
    a = raw_input("Enter the value of a:") 
    b = raw_input("Enter the value of b:") 
    c = a/b 
    print c 

else: 
print "Invalid Number" 
print "\n" 
+1

我不明白這個問題。你不處理這個腳本中的符號,你處理數字。 (雖然與a和b的類型有關的單獨問題。) –

+1

順便說一句,它是'division'。 –

回答

5

您需要將您的輸入,字符串更改爲整數或浮點數。因爲,有部門,你最好改變它浮動。

a=int(raw_input("Enter the value of a:")) 
a=float(raw_input("Enter the value of a:")) 
4

當你得到輸入時,它是一個字符串。 +運算符是爲字符串定義的,這就是爲什麼它可以工作,但其他運算符卻不能。我建議使用一個輔助函數來安全地獲得一個整數(如果你正在做整數算術)。

def get_int(prompt): 
    while True: 
     try: 
      return int(raw_input(prompt)) 
     except ValueError, e: 
      print "Invalid input" 

a = get_int("Enter the value of a: ") 
1

Billwild說你應該改變你的變量整數。但爲什麼不漂浮。它不是重要的,如果它是整數或浮點數,它必須是數字類型。 Raw_input接受任何像字符串一樣的輸入。

a=float(raw_input('Enter the value of a: ')) 

或者蒂姆的形式給出

def get_float(prompt): 
    while True: 
     try: 
      return float(raw_input(prompt)) 
     except ValueError, e: 
      print "Invalid input" 

a = get_float("Enter the value of a: ") 

您可以隨時轉換結果漂浮或爲int或背部。只是你在編程什麼樣的計算器才重要。

+0

你是對的 - 既然有分裂,如果你轉換爲浮動,它會更好。 – billwild