想在按“ e”后退出while循环,但是循环认为“ e”是输入,给我一个错误

时间:2019-07-09 02:14:43

标签: python

代码是较大程序的一部分,在该程序中,我必须获取用户输入数字的列表,删除最低的数字(如果列表中包含5个或更多项目),然后取平均值。在程序中输入“ e”应停止循环并显示列表。

def get_input():
    stop_loop = False
    number_list = []
    print('Press "e" to exit program once all numbers are inputted.')
    while not stop_loop:
        user_input = input('Please enter number: ')
        number = float(user_input)
        number_list.append(number)
        print(number_list)
        if user_input == 'e':
            stop_loop = True
    return number_list
Traceback (most recent call last):
  File "C:/Users/Duck/PycharmProjects/untitled/grader.py", line 105, in <module>
    main()
  File "C:/Users/Duck/PycharmProjects/untitled/grader.py", line 95, in main
    number_main = get_input()
  File "C:/Users/Duck/PycharmProjects/untitled/grader.py", line 34, in get_input
    number_list = float(user_input)
ValueError: could not convert string to float: 'e'

输入数字后,程序应继续执行下一个功能。

2 个答案:

答案 0 :(得分:3)

您应在user_input = input('Please enter number: ')之后检查输入是否为“ e”,因此您的代码应类似于:

def get_input():
    number_list = []
    print('Press "e" to exit program once all numbers are inputted.')
    while True:
        user_input = input('Please enter number: ')
        if user_input == 'e':
            break
        number = float(user_input)
        number_list.append(number)
        print(number_list)
    return number_list

答案 1 :(得分:1)

发生错误是因为您无法将字符串“ e”转换为浮点数。要解决此问题,您可以将

if user_input == 'e':

紧接着

user_input = input('Please enter number: ')

并添加一个break语句,以防止将'e'字符串转换为浮点数。像这样

def get_input():
    stop_loop = False
    number_list = []
    print('Press "e" to exit program once all numbers are inputted.')
    while not stop_loop:
        user_input = input('Please enter number: ')

        if user_input == 'e':
            stop_loop = True
            break

        number = float(user_input)
        number_list.append(number)
        print(number_list)
    return number_list