Python 3 Count和While循环

时间:2018-02-26 18:18:04

标签: python-3.x

我试图找出下面代码中的错误。我需要满足以下条件:

1)如果等于零或更低,我需要python来声明“输入无效”

2)如果大于零,则询问是否有其他输入

3)只要有另一个输入,我需要程序继续询问

4)如果“完成”,那么我需要Python来计算最低的输入。我还没有完成这一部分,因为我在“完成”部分收到错误。

print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
        print ("Input should be greater than zero.")
while True:
        number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
        if number < 0 or number == 0:
            print ("Input should be greater than zero. Please enter score: ")
        if number == "Done":
            print ("NEED TO COUNT")
            break

1 个答案:

答案 0 :(得分:0)

我写了一个替代解决方案,它在输入错误方面更加强大。它可能包括一些改进代码的想法,但可能也不是最好的解决方案。

print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
   foo = input('Please enter score: ')
   try:
      number = float(foo)
      if number > 0:
         num_arr.append(number)
         valid_input = True
      else:
         raise ValueError
      while foo != 'Done' and valid_input:
         try:
            number = float(foo)
            if number > 0:
               num_arr.append(number)
            else:
               raise ValueError
         except ValueError:
            print('Invalid input! Input should be number greater than zero or 
"Done".')
         finally:
            foo = input('Do you have another input? If yes type another score, 
if no type "Done": ')
   except ValueError:
      print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))