2017-06-20 87 views
-5
print('Select operation') 
print('Choose from:') 
print('+') 
print('-') 
print('*') 
print('/') 

choice=input('Enter choice (+,-,*,/):') 

num1=int(input('Enter first number:')) 
num2=int(input('Enter second number:')) 

if choice== '+': 
print(num1,'+',num1,'=', (num1+num2)) 
while restart **=** input('Do you want to restart the calculator y/n'): 
    if restart == 'y':t 
     print('restart') 
     else restart == 'n': 
      print('Thanks for using my program') 
      break 

elif choice== '-': 
print(num1,'-',num2,'=', (num1-num2)) 

elif choice== '*': 
print(num1,'*',num2,'=', (num1*num2)) 

elif choice== '/': 
print(num1,'/',num2,'=',(num1/num2)) 

else: 
print('Invalid input') 

=粗體字有什麼問題?我不明白它有什麼問題嗎?有人請回答我的問題。爲什麼它說粗體=是一個無效的語法?

謝謝 夏洛特

+4

修復您的縮進。 – SLaks

+1

是的,你有一個無效的語法。使用相等運算符'restart == input(...)' –

+1

有些語言允許您在有條件的時間內使用賦值語句。 Python不是這些語言之一。 – Kevin

回答

0

的多個問題:

  1. 分配從input到不能在while循環來檢查一個變量,你應該把它分割成分配和檢查。

  2. else不能包含一個條件

  3. 你也有一個bug在打印結果 - 你打印num1兩次

  4. 的缺口是有意義的Python - 請務必將它張貼正確縮進未來時間

用於上述問題的解決辦法:

def calc(): 
    print('Select operation') 
    print('Choose from:') 
    print('+') 
    print('-') 
    print('*') 
    print('/') 

    choice=input('Enter choice (+,-,*,/):') 

    num1=int(input('Enter first number:')) 
    num2=int(input('Enter second number:')) 
    if choice == '+': 
     print("{}+{}={}".format(num1, num2, num1+num2)) 

    elif choice == '-': 
     print("{}-{}={}".format(num1, num2, num1-num2)) 

    elif choice == '*': 
     print("{}*{}={}".format(num1, num2, num1*num2)) 

    elif choice == '/': 
     print("{}/{}={}".format(num1, num2, num1/num2)) 
    else: 
     print('Invalid input') 


if __name__ == '__main__': 
    restart = 'y' 
    while restart: 
     if restart == 'y': 
      print('restart') 
      calc() 
      restart = input('Do you want to restart the calculator y/n')  
     elif restart == 'n': 
      print('Thanks for using my program') 
      break 
+0

「重新啓動計算器」循環是無限的。 –

+0

@ Jean-FrançoisFabre - 修復 – alfasin

+0

@Charlotte注意 - 我通過提取獲取輸入並將計算轉換爲函數並從main調用該函數的業務邏輯來重構代碼。你可以(也應該)保持重構它,並讀取(和驗證)輸入到一個專用的函數中 - 並以不同的方式進行計算。 – alfasin

0

不像C和Java,Python不支持循環或條件語句中指定。

假設您想要爲restart分配一個值,您必須在外部執行並測試它。

restart = input(...) 
while restart: 
    ... # do something here 

但是,如果你想要做的是一個比較,你需要改變===

while restart == ...: 
    ... # do something here 
+0

這會導致無限循環,儘管 –

+0

@ Jean-FrançoisFabre其實,您是對的。我看到了突破,但我不知道它是如何被稱呼的。是的,肯定無限循環。 –

0

你試圖使用一個賦值語句作爲一個布爾值;這在幾個方面都失敗了。最重要的是,你正在用幾行代碼來傳播你的邏輯,並且使解析器混淆不清。

你可能想是這樣的:在這裏

restart = input('Do you want to restart the calculator y/n') 
while restart.lower() == 'y': 
    ... 
    restart = input('Do you want to restart the calculator y/n') 
相關問題