简体   繁体   中英

Python error "TypeError: object of type 'NoneType' has no len()

I am getting an error from this python code

def read_lines():
    user_entries = []
    contin = True
    while contin == True:
        user_input = input(str("Enter string or just press enter to finish: "))
        user_entries.append(user_input)
        if len(user_input) == 0:
            contin = False
    print(user_entries)

lines = read_lines()
print(lines)
ci = o
contin = True
while contin:
    if ci == len(lines):
        contin = False
    else:
        line = lines(ci, ci + 1)
        ci = ci + 1
        print(ci, line)

I then get this error...

Traceback (most recent call last):
  File "test.py", line 8 in <module>
    if ci == len(lines):
Type Error: object of type 'NoneType' has no len()

I'm not quite sure why i get this error. When it executes the line print(lines) it returns None. That's probably the issue but I'm not sure how to fix it.

Your function read_lines doesn't return anything

def read_lines():
    user_entries = []
    contin = True
    while contin == True:
        user_input = input(str("Enter string or just press enter to finish: "))
        user_entries.append(user_input)
        if len(user_input) == 0:
            contin = False
    print(user_entries) # this prints user_entries but doesn't return it

Add a return user_entries to your function after the call to print and your code should work

The function you defined read_lines() does not return anything to lines so it is None .

In your function add return after printing.

return user_entries

Also you need do changes in your code such as line = lines(ci, ci + 1)

lines is a list: it's not callable.

ci = 0 instead of ci = o

Please remove the typos, errors and try again. Should work.

I have executed this code using python 2.7

-- > function read_lines() does not return anything that is one thing.

but inside the while loop, instead of using :

user_input = input(str("Enter string or just press enter to finish: "))

Use :

user_input = raw_input("Enter string or just press enter to finish: ")

So you will not have next errors. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM