2016-06-08 29 views
0

我正在使用python3製作簡單的分數計算器。 我仍然可以輸入choice,但它不會調用任何函數;加,減,除,乘。 我錯過了什麼嗎? 在此先感謝!它不會在python3中調用函數?

from fractions import Fraction 
class Thefraction(): 

    def add(a,b): 
     print('The result is %s' % (a+b)) 
    def subtract(a,b): 
     print('The result is %s' % (a-b)) 
    def divide(a,b): 
     print('The result is %s' % (a*b)) 
    def multiply(a,b): 
     print('The result is %s' % (a/b)) 

    if __name__=='__main__': 
     try: 
      a = Fraction(input('Please type first fraction ')) 
      b = Fraction(input('Please type second fraction ')) 
      choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ') 
      if choice ==1: 
       add(a,b) 
      if choice==2: 
       subtract(a,b) 
      if choice==3: 
       divide(a,b) 
      if choice==4: 
       multiply(a,b) 

     except ValueError: 
      print('No fraction') 
+1

別的不說,問題是,在python3, 「輸入」 接收串。你需要使用'int(choice)'或者將它與數字的'字符串'表示進行比較'if choice =='1''。另外,你的'if __name__ =='__main __「:'塊需要在類定義之外。然後,要使用類的方法,用'TheFraction'前綴它們(例如:TheFraction.add(a,b)' –

+0

謝謝你的建議!我現在要修復 – jaykodeveloper

回答

2

當您在輸入中輸入某些內容時,它將其保存爲字符串而不是整數。所以,你可以改變if語句:choice =='1'或使用choice =int(choice)

例如:

choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ') 
     if choice == '1': 
      add(a,b) 
     if choice== '2': 
      subtract(a,b) 
     if choice== '3': 
      divide(a,b) 
     if choice== '4': 
      multiply(a,b) 

或者:

choice = input('Please select one of these 1. add 2. subtract 3. divide 4.multiply ') 
choice = int(choice) 
      if choice ==1: 
       add(a,b) 
      if choice ==2: 
       subtract(a,b) 
      if choice ==3: 
       divide(a,b) 
      if choice ==4: 
       multiply(a,b)