2017-05-01 12 views
-1
main(): 
try: 
    weight1 = int(input("Enter the weight of package one: ")) 
    weight2 = int(input("Enter the weight of package two: ")) 
    if weight1 or weight2 <= 0: 
     raise ValueError('Invalid weight') 
    price1 = float(input("Enter the price for package one: ")) 
    price2 = float(input("Enter the price for package one: ")) 
    math1 = weight1/price1 
    math2 = weight2/price2 
    if math1 < math2: 
     print("Package 1 has two has the better price") 
    else: 
     print("Package 2 has the better price price") 
    except ValueError as excpt: 
     print(excpt) 
     print('Please provide a valid weight. \n') 
    except ZeroDivisionError: 
     print('Invalid price entered.') 

main() 

我想知道爲什麼我一直從這裏得到一個語法錯誤。它看起來不錯,但我不斷收到錯誤我一直收到異常的語法錯誤

+0

您的代碼格式不正確,如圖所示。除了缺少'def'外,'try-except'中還有縮進錯誤。不知道這是否是由粘貼造成的。 – DyZ

+0

'try'在同一個縮進級別上需要'except'或'finally'。 –

回答

0

您在main():定義之前缺少def

0
def main(): 

    try: 
     weight1 = int(input("Enter the weight of package one: ")) 
     weight2 = int(input("Enter the weight of package two: ")) 
     if weight1 or weight2 <= 0: 
      raise ValueError('Invalid weight') 
     price1 = float(input("Enter the price for package one: ")) 
     price2 = float(input("Enter the price for package one: ")) 
     math1 = weight1/price1 
     math2 = weight2/price2 
     if math1 < math2: 
      print("Package 1 has two has the better price") 
     else: 
      print("Package 2 has the better price price") 
    except ValueError as excpt: 
    print(excpt) 
    print('Please provide a valid weight. \n') 
    except ZeroDivisionError: 
    print('Invalid price entered.') 


main() 

1. Missing def before main(). 
2. improper Indentation. 
+0

如果'weight1'不爲零,'if'語句也會變爲true。 – kindall

相關問題