如何只允许输入"停止",""的字符串值,然后检查并转换为浮点数

时间:2012-10-15 12:41:28

标签: python python-3.x

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

完整的当前代码如下。

我目前的想法如下:

  1. 检查“停止”,“
  2. 检查输入是否为浮点数。
  3. 如果不是1或2,则请求有效输入。
  4. 有什么想法吗?如果它简单的东西只是指向我的方向,我会尝试搅拌它。否则...

    由于

    # 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))
    

1 个答案:

答案 0 :(得分: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.')