【问题标题】:are there any ways to add ValueError for each input?有什么方法可以为每个输入添加 ValueError 吗?
【发布时间】:2020-03-03 05:28:05
【问题描述】:

所以我尝试编写一个代码,您可以在其中输入矩形的宽度和高度,它会为您提供面积和周长,现在显然输入只能是数字,所以我希望能够要求另一个输入,如果当前输入不是数字。 (告诉用户只输入数字)。问题是如果第一个输入(宽度)是一个数字而只有第二个输入(高度)不是数字,我不希望程序要求用户输入宽度同样,我只希望用户再次输入高度而不是宽度,因为宽度已经作为数字输入。我该怎么做?

while True:
try:
    a = float(input("Please enter width :"))
    b = float(input("Please enter height :"))

except ValueError:
    print("PLease only enter numbers ")
    continue

area = float(a*b)
perimeter = float((a+b)*2)

print('The area of the rectangle is {} and the perimeter of the rectangle is {} '.format(area, perimeter))

【问题讨论】:

    标签: python python-3.x valueerror except


    【解决方案1】:

    基本答案是将每个对float 的调用包装在一个单独的try 中并分别处理它们。不过,从字面上写出两个trys 会很乱而且很笨重。

    相反,我会将 try 移动到它自己的函数中,然后调用该函数两次:

    # Let this function handle the bad-input looping 
    def ask_for_float(message):
        while True:
            try:
                return float(input(message)) 
    
            except ValueError:
                print("Please only enter numbers ")
    
    a = ask_for_float("Please enter width :")
    b = ask_for_float("Please enter height :")
    

    【讨论】:

      【解决方案2】:

      将您的输入写入单独的 try 块中,然后您可以单独捕获错误。 例如,

      try:
      a = float(input("Please enter width :"))
      
      except ValueError:
          print("PLease only enter numbers ")
      
      try:
          b = float(input("Please enter height :"))
      
      except ValueError:
          print("PLease only enter numbers ")
          continue
      
      area = float(a*b)
      perimeter = float((a+b)*2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-20
        • 2018-11-19
        • 1970-01-01
        • 2015-06-25
        • 1970-01-01
        相关资源
        最近更新 更多