0

I am writing a code where the user inputs as many numbers as they want until they input Stop. Each input gets added to a list. I want the input to be integer so the inputs are able to be sorted correctly but then when 'Stop' is inputted an error message will be created. But if I make the input string then the numbers will be sorted incorrectly.

Here is the code:

Num_List = list()
Numbers = input('Enter a number: ')
Num_List.append(Numbers)
Num_B = False
while Num_B == False:
    Numbers = input('Enter a number: ')
    Num_List.append(Numbers)
    if Numbers == 'Stop':
        Num_List.remove('Stop')
        Num_List = [i for i in Num_List if i is not '']      
        Num_List.sort(reverse=False)
        sorted(Num_List)
        print(Num_List)
        Num_B = True

3 Answers3

1

I suspect that you are using python <2.8, so input() behave differently and execute what is given instead of returning it as string (like eval(input())). When given an int, no problems occurs but when given a "Stop", python does not know what to do with it (unless your code have a variable named "Stop" ...).

Here is a simple rework of your code for python2:

# little trick to use input with python2 or python3 !
# source: http://stackoverflow.com/a/7321970/956660
try: input = raw_input
except NameError: pass

# variables naming is prefered in snake_case
num_list = []
curr_num = '' # only use one variable for input
while curr_num.lower() != 'stop': # lower allows to be case insensitive
    # raw_input prevent the "bug"
    curr_num = input('Enter a number or "stop": ')

    # conversion to int raise an error on invalid string, so we ignore errors
    try: num_list.append(int(curr_num))
    except ValueError: pass

# we print and sorted only when everything have been inputted
print('Numbers: %s' % num_list)
print('Sorted: %s' % sorted(num_list))

Edit: Refactor code to be python 2 & 3 compatible. So you can use input() the same way anywhere ;)

Cyrbil
  • 6,341
  • 1
  • 24
  • 40
  • After I modified my code in update 2, I saw your raw_input/input trick. Credit go to your source, because that is where I learned it from – Hai Vu Dec 01 '15 at 14:30
0

Here is my approach: In an infinite loop, get a user's input. If it is 'Quit' then break out of the loop. Otherwise, convert to integer and append to the list of numbers. The code:

numbers = list()
while True:
    token = input('Number: ')
    if token == 'Quit':
        break
    numbers.append(int(token))

print('List is:', numbers)

Update

Judging by the original poster's ignoring empty strings, I guess some of the imput are empty strings, which causes ValueError. With that guess, I modified my code to take in accounts of those tokens that are not converted to numbers successfully.

numbers = list()
while True:
    token = input('Number: ')
    if token == 'Stop':
        break
    try:
        numbers.append(int(token))
    except ValueError:
        print('Invalid token, ignore: {!r}'.format(token))

print('List is:', numbers)

Update 2:

I have modifying my code yet again. This time, the code runs fine in both Python 2 and 3 interpreters.

from __future__ import print_function

# Level the difference between Python 2 and 3
try:
    raw_input
except NameError:
    raw_input = input

numbers = list()
while True:
    try:
        token = raw_input('Number: ')
        numbers.append(int(token))
    except ValueError:
        if token == 'Stop':
            break
        print('Invalid token, ignore: {!r}'.format(token))

print('List is:', numbers)

Update 3

Output for update 2 from Python 3 run:

Number: 7
Number: 87
Number: 120
Number: 
Invalid token, ignore: ''
Number: foo
Invalid token, ignore: 'foo'
Number: bar
Invalid token, ignore: 'bar'
Number: Stop
List is: [7, 87, 120]

Output from Python 2 run is the same.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • How does this address the error? Inputting `Stop` in your code is also going to error if the OP is using python2 which based on the problem description is most likely what is happening? – Padraic Cunningham Dec 01 '15 at 13:58
  • @PadraicCunningham I ran the OP's code and did not see any error. I am still waiting for the OP to update with any specific error. My post do address the OP concern: converting the tokens to integers. – Hai Vu Dec 01 '15 at 14:05
  • The OP's own code breaks when Stop is entered which is what would happen using python2 as there would be a `NameError` using input. – Padraic Cunningham Dec 01 '15 at 14:09
  • The OP specifically stated Python 3. Yes, I am well aware of the different between `input` and `raw_input` in Python 2.x. – Hai Vu Dec 01 '15 at 14:12
  • It works except for a few problems: 1. Typing Stop does nothing, anything other than Stop prints the list 2. It prints the first number fine but all the others get repeated twice. –  Dec 01 '15 at 18:13
  • I tested my solution. Perhaps if you care showing me your input sequence so I can test (and fix) – Hai Vu Dec 01 '15 at 18:19
  • Typing in numbers work and adds it to a list. Words do not get added. '' causes a value error. Inputting 7, 87, 120 outputs [7, 87, 87, 120, 120]. It only stops when inputting something that isn't Stop. –  Dec 01 '15 at 19:24
  • Are you sure you are running my update 2 version? I added update 3 to show the output and it looks alright to me. – Hai Vu Dec 01 '15 at 20:27
  • Yes, the only difference is the variabee names, raw_input is input and everything above nukbers = list() (I do not know if I need everything above numbers = list() or not, I am using Pythin 3.x) –  Dec 01 '15 at 21:33
0

You can do it like this:

Num_List = list()
Numbers = input('Enter a number:')
while Numbers != 'Stop':
    Num_List.append(int(Numbers))
    Numbers = input('Enter a number:')

Num_List = [i for i in Num_List if i is not '']      
Num_List.sort(reverse=False)
sorted(Num_List)
print(Num_List)
Ryan
  • 365
  • 1
  • 3
  • 9