0

I'm making a program to sort numbers from lowest to highest as long as the numbers are under 300, but I can't figure out how to change the user input into a list. Here's my code:

List1=[] List2=[] var=1 thing=input("Insert numbers here") List1.append(thing) while var < 300: for that in List1: if that < var: List2.append(number) var = var + 1 print(List2) 

When I run the code, it says that in the 8th line, a string can't be compared with an int. Please help. Thanks in advance.

4
  • How is the user's input formatted? Commented Apr 11, 2013 at 1:28
  • Where did number come from? Commented Apr 11, 2013 at 1:28
  • Just a simple int() cast should do, along with some exceptions. Commented Apr 11, 2013 at 1:28
  • just try int(that) stackoverflow.com/questions/379906/… Commented Apr 11, 2013 at 1:30

3 Answers 3

2

It looks like your variable that is a string. This is why you can't compare it against an integer. If you need to convert your string to an int you can simply wrap it with int(your_variable_here).

For example

if int(that) < var:

This would convert the string that to an integers (number). The benefits of converting it to a integer is that you can compare it against other integers, and use basic arithmetic operations. That wouldn't be possible if you used a string.

An even better solution would be to directly store the input as an integer.

List1.append(int(thing)) # We wrap the keyboard input with int 

Also, if you are running Python 2.x I would recommend that you use raw_input, instead of input.

Sign up to request clarification or add additional context in comments.

Comments

0

Since this doesn't seem to be in any loop, I don't see how you can have more than one entry in the list.. Perhaps you could have space seperated numbers entered? Using python 3, this could be minimized like so (minus error handling):

nums = [x for x in list(map(int, input("Enter numbers: ").split())) if x < 300] nums.sort() 

Or..

nums = input("Enter numbers: ") # Get the number string nums = nums.split() # Split the string by space character nums = list(map(int, nums)) # call int() on each item in the list, converting to int nums.sort() # sort the list of numbers nums = [x for x in nums if x < 300] # remove any numbers 300 or over. 

Input/output:

Enter numbers: 1 5 301 3000 2 [1, 2, 5] 

1 Comment

Thanks a lot, but I'm kind of a nube at python. Could you possibly explain what you just did?
0

If you enter the numbers separated by commas, the following single line will work:

>>> sorted(list(input("Enter numbers: ")), reverse=True) Enter numbers: 1, 2, 3 [3, 2, 1] 

To remove numbers < 300:

>>> sorted([num for num in input("Enter numbers: ") if num < 300], reverse=True) Enter numbers: 1, 301, 299, 300, 2, 3 [299, 3, 2, 1] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.