2011-09-10 35 views
1

這是我的項目介紹:如何在Python中終止程序?

寫,顯示以下菜單的程序:

1)轉換到華氏攝氏度
2)轉換攝氏到華氏

輸入1,2,或0退出:

在選項1和2的情況下,程序應該提示用戶輸入溫度,執行轉換並輸出結果。然後程序應該重新顯示菜單。當選擇選項0時,程序應該退出。

這是我到目前爲止有:

a = raw_input("1) Convert Fahrenheit to Celsius \n2) Convert Celsius to Fahrenheit \nEnter 1, 2, or 0 to exit: ") 

x = raw_input("Enter degree: ") 

y = float((x - 32)/1.8) 

x = raw_input("Enter degree: ") 

z = float((x + 32) * 1.8) 

if a == 1: 
    print(y) 

if a == 2: 
    print(z) 

我怎樣才能終止這個程序?我在哪裏搞亂了?

+1

嘗試'sys.exit()' –

+0

作業?如果是這樣,你應該這樣標記它。 –

+1

如果我沒有指出你的z方程應該是這樣的,我會覺得自己像個混蛋: z = float((x/1.8)+32) – Vorticity

回答

1
  • 擺脫第二個x = raw_input(...線。你不需要它。
  • 計算y之前你print它,在if塊內。沒有意義的數學用戶不想要的。
  • z相同:在需要之前計算。
  • 將這個在a = raw_input(...行後:

代碼:

if a == 0: 
    import sys 
    sys.exit(0) 
+1

只是一個加法:目前爲止還沒有人提到這個循環。當然,所有這些都必須在'while True:'循環中進行。然後你也可以使用'break'離開那個循環並終止。 – glglgl

0

您需要:

  1. 轉換a和x爲int。

    a = int(raw_input("1) Convert Fahrenheit to Celsius \n2) Convert Celsius to Fahrenheit \nEnter 1, 2, or 0 to exit: ")) 
    
    x = int(raw_input("Enter degree: ")) 
    
  2. 在塊內部進行計算。

  3. 而且,擺脫了第二x = raw_input("Enter degree: ")

  4. 而在上面的回答是說,你可以使用sys.exit(0)