0

嗨,我在循环结束时遇到问题。我需要接受输入作为字符串来获取“停止”或“”,但我不需要任何其他字符串输入。输入转换为浮点数,然后添加到列表中,但如果用户键入“bob”,我会收到转换错误,并且我无法设置输入(浮点数),因为那时我不能接受“停止”。

完整的当前代码如下。

我目前的想法如下:

  1. 检查“停止”,“”
  2. 检查输入是否为浮点数。
  3. 如果不是 1 或 2,则请求有效输入。

请问有什么想法吗?如果它很简单,只需指出我的方向,我会尝试将其制作出来。否则...

谢谢

# Write a progam that accepts an unlimited number of input as integers or floating point.
# The input ends either with a blank line or the word "stop".


mylist = []

g = 0
total = 0
avg = 0


def calc():
    total = sum(mylist);
    avg = total / len(mylist);
    print("\n");
    print ("Original list input: " + str(mylist))
    print ("Ascending list: " + str(sorted(mylist)))
    print ("Number of items in list: " + str(len(mylist)))
    print ("Total: " + str(total))
    print ("Average: " + str(avg))


while g != "stop":
    g = input()
    g = g.strip()  # Strip extra spaces from input.
    g = g.lower()  # Change input to lowercase to handle string exceptions.
    if g == ("stop") or g == (""):
        print ("You typed stop or pressed enter") # note for testing
        calc() # call calculations function here
        break

# isolate any other inputs below here ????? ---------------------------------------------
        while g != float(input()):
            print ("not a valid input")
    mylist.append(float(g))
4

1 回答 1

3

我认为pythonic方式是这样的:

def calc(mylist): # note the argument
    total = sum(mylist)
    avg = total / len(mylist) # no need for semicolons
    print('\n', "Original list input:", mylist)
    print("Ascending list:", sorted(mylist))
    print ("Number of items in list:", len(mylist))
    print ("Total:", total)
    print ("Average:", avg)

mylist = []
while True:
   inp = input()
   try:
       mylist.append(float(inp))
   except ValueError:
       if inp in {'', 'stop'}:
            calc(mylist)
            print('Quitting.')
            break
       else:
            print('Invalid input.')
于 2012-10-15T12:55:33.083 回答