【问题标题】:I keep getting a syntax error on exception我不断收到异常的语法错误
【发布时间】:2017-05-01 02:59:09
【问题描述】:
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()

我想知道为什么我不断收到语法错误。它看起来不错,但我一直收到错误

【问题讨论】:

  • 您的代码格式不正确,如图所示。除了缺少def 之外,您还有try-except 中的缩进错误。不确定这是否是由于粘贴造成的。
  • A try 需要在同一缩进级别上的 exceptfinally

标签: python syntax error-handling syntax-error


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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.
    

    【讨论】:

    • 如果weight1 不为零,if 语句也会为真。
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2022-07-21
    • 2012-10-22
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    相关资源
    最近更新 更多