2017-07-28 99 views
0

我需要設計一個計算器以下界面:計算器功能輸出沒有

Welcome to Calculator! 
1 Addition 
2 Subtraction 
3 Multiplication 
4 Division 
Which operation are you going to use?: 1 
How many numbers are you going to use?: 2 
Please enter the number: 3 
Please enter the number: 1 
The answer is 4. 

這是我到目前爲止有:

print("Welcome to Calculator!") 

class Calculator: 
    def addition(self,x,y): 
     added = x + y 
     return sum 
    def subtraction(self,x,y): 
     diff = x - y 
     return diff 
    def multiplication(self,x,y): 
     prod = x * y 
     return prod 
    def division(self,x,y): 
     quo = x/y 
     return quo 


calculator = Calculator() 

print("1 \tAddition") 
print("2 \tSubtraction") 
print("3 \tMultiplication") 
print("4 \tDivision") 
operations = int(input("What operation would you like to use?: ")) 

x = int(input("How many numbers would you like to use?: ")) 

if operations == 1: 
    a = 0 
    sum = 0 
    while a < x: 
     number = int(input("Please enter number here: ")) 
     a += 1 
     sum = calculator.addition(number,sum) 

我認真地需要一些幫助! Python 3中所有關於計算器的教程都比這個簡單得多(因爲它只需要2個數字,然後簡單地輸出答案)。

我需要幫助獲取我開始工作的Calculator類中的函數。當我嘗試運行我迄今爲止所擁有的功能時,它會讓我輸入我的號碼和其他號碼,但這只是結束。它不運行操作或任何。我知道我到目前爲止只有補充,但如果有人能幫我找出補充,我想我可以做其餘的。

+1

你永遠不打印結果。也許'印刷總額'在底部將解決您的問題。 – Prune

+2

另外,在你的加法函數中,你將總和存儲在'added'中,但是返回一個變量'sum'。 –

+0

哎呀,我沒有注意到我沒有注意到。謝謝! –

回答

0

代碼原樣不起作用。在addition函數中,返回變量sum,這將與sum函數中的構建發生衝突。

所以才返回添加和一般避免sum,使用類似sum_

這對我工作得很好:

print("Welcome to Calculator!") 

class Calculator: 
    def addition(self,x,y): 
     added = x + y 
     return added 
    def subtraction(self,x,y): 
     diff = x - y 
     return diff 
    def multiplication(self,x,y): 
     prod = x * y 
     return prod 
    def division(self,x,y): 
     quo = x/y 
     return quo 

calculator = Calculator() 

print("1 \tAddition") 
print("2 \tSubtraction") 
print("3 \tMultiplication") 
print("4 \tDivision") 
operations = int(input("What operation would you like to use?: ")) 

x = int(input("How many numbers would you like to use?: ")) 

if operations == 1: 
    a = 0 
    sum_ = 0 
    while a < x: 
     number = int(input("Please enter number here: ")) 
     a += 1 
     sum_ = calculator.addition(number,sum_) 

    print(sum_) 

運行:

$ python s.py 
Welcome to Calculator! 
1 Addition 
2 Subtraction 
3 Multiplication 
4 Division 
What operation would you like to use?: 1 
How many numbers would you like to use?: 2 
Please enter number here: 45 
Please enter number here: 45 
90 
0

您的程序需要輸入,執行一系列操作,然後結束而不顯示結果。 while循環結束後嘗試類似print(sum)

+0

謝謝!我不敢相信我忘了那個哈哈。 –