0

I have a question about Nested loops, primarily converting the lists into an int and then testing to see if it is less than a limit(230) and if it is, it adds one to the limit and one to a count. Here's the code I have so far Whenever I try to work this code: I get an Error message of:

ValueError: invalid literal for int() with base 10: '487 , 440 , 488 , 496 , 55 , 345 , 26 , 446 , 249 , 402 , 311\n'

I think it means that im trying to take the int of that whole string? How could I split it up so that it takes the int of 487, 440, 488, etc

def Nested_Loop():

    count = 0
    lines = []
    limit = 230
    listt = open ('numbers.txt', 'r')
    value = listt.readlines()
    for line in value:
        lines.append(line)

    for line in lines:
        line = int(line)

    if line < limit:
        limit = limit + 1
        count = count + 1
    else:
        line = limit + 0
        count = count + 0

Nested_Loop()

I don't know how to upload the numbers.txt on here, but here is a picture of it.

enter image description here

5
  • Wondering: what effects do you expect to gain from that else block up there? What is the point of adding 0 to something? Commented Apr 27, 2017 at 6:44
  • So that if the numbers are greater than the limit, the count and limit stay the same and it reads the next value in the .txt Commented Apr 27, 2017 at 6:47
  • When you read a line from a file, it is always a string. Convert them to array might be suitable in your case. You can convert string in to an array by using "split" function. And you could do the opposite option using "join" function. These two functions are standard name for many programming languages. Commented Apr 27, 2017 at 6:49
  • The code you have right now can only work if you have one integer per line in that file. Try what Hackaholic suggests. Commented Apr 27, 2017 at 6:49
  • for example: str = "123,456,789" ; str.split(',') will return array of string as such ['123', '456', '789'] then you could turn them in to integer. Commented Apr 27, 2017 at 6:51

1 Answer 1

1

you better do like this:

read a line from file, split on comma

with open('numbers.txt') as f:
    for line in f:
        nums = list(map(int, line.strip().split(",")))
        if len(nums)< limit:
        # now your code
Sign up to request clarification or add additional context in comments.

4 Comments

TypeError: object of type 'map' has no len()
are you using python 3.x, Updated the solution
print "line" variable to check its data type before using it. strip and split is a string function
Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.