Juicyduck
Juicyduck

Reputation: 3

Want to exit while loop after pressing "e", but the loop thinks "e" is an input and gives me an error

The code is part of a larger program where I have to take a list of user-inputted numbers, remove the lowest number (if the list has 5 or more items), and then average them. Entering "e" into the program should stop the loop and display the list.

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'

The program should move on to the next function when numbers are inputted.

Upvotes: 0

Views: 51

Answers (2)

James Casia
James Casia

Reputation: 1527

The error happens because you can't convert a string 'e' to a float. To fix that, you can put the

if user_input == 'e':

right after

user_input = input('Please enter number: ')

and add a break statement to prevent converting the 'e' string to a float. Like this

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

Upvotes: 1

ToughMind
ToughMind

Reputation: 1009

You shoul check whether the input is "e" or not right after user_input = input('Please enter number: '), so your code can be like:

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

Upvotes: 3

Related Questions