2013-03-08 119 views
0

我對以下代碼有兩個問題。 一,第一次raw_input,如果我嘗試格式化爲raw_input生活再次運行的方式,我會得到一個語法錯誤,我不明白爲什麼。Python代碼錯誤

第二,一旦我完成了運行程序並啓動y,它會在停止時開始,但是如果我再次輸入一個數字,它會回到問我是否想再次運行,就好像它做了什麼本應該這樣做。如果我輸入負數或字母它會給我正確的錯誤信息,但如果我輸入一個數字,它將無法正常工作。它只會跳到詢問我是否想再次運行。

這發生在我添加了格式化代碼後,在那之前我使用了空格,並且所有工作都正常。

total15 = 0 
total20 = 0 
while True: 
     print '' 
     while True: 
       try: 
        userNum = float(raw_input('       Enter the total of your bill:')) 
        if (userNum) > 0 and (userNum) != 0: 
         break 
        else: 
         print '' 
         print('{:^80}'.format('Oops! That was no valid number. Try again...')) 
         print '' 

       except ValueError: 
       print '' 
       print('{:^80}'.format("Oops! That was no valid number. Try again...")) 
       print '' 
     while total15 <= 0: 
      total15 = float((15*userNum)/100) 
      total20 = float((20*userNum)/100) 
      print '' 
      print('{:^80}'.format('You should leave ' + str(total15) + '$' + ' of tip' \ 
        ' for 15%' + ' or ' + str(total20) + '$' + ' for 20%')) 
      print '' 
     while True: 
      answer = raw_input(('{:>50}'.format('Run again? (y/n): '))) 
      if answer in ('y', 'n'): 
       print'' 
       break 
      print('{:>50}'.format('Invalid input.')) 
     if answer == 'y': 
      continue 
     else: 
      print '' 
      print('{:>45}'.format('Goodbye!')) 
      break 
+2

」每個縮進級別使用4個空格。「 - [PEP 8 - Python代碼樣式指南](http://www.python.org/dev/peps/pep-0008/#indentation)。如果你使用一致的縮進,你會發現更容易發現錯誤。 – Johnsyweb 2013-03-08 21:35:41

+2

如果包含錯誤消息,它將幫助人們回答您的問題,因爲語法錯誤可能在任何地方。 – askewchan 2013-03-08 21:38:56

回答

2

與您的代碼的功能,問題是在while循環:

while total15 <= 0: 

你不需要這一點,你不能得到答案的原因後第一次迭代是因爲你已將total15設置爲大於0的數字。如果你在while循環中刪除這個循環,並把循環中的所有內容都移到左邊,那麼你的代碼就可以工作

要回答你的格式問題,如果你只是把第一個raw_input調用中的字符串替換成'{:>50}'.format('Enter the total of your bill:'),它應該可以工作。

此外,您可以通過一些工作減少此代碼的長度和複雜性。

2

我看到幾個問題:

  1. 你爲什麼要使用之類的語句while total15 <= 0:?您似乎需要使用if語句代替。
  2. 您不會重置total15total20,因此如果用戶重新運行程序,它將不會計算並輸出提示的金額(因爲這些變量具有非零值)。 「