Home > Enterprise >  Code runs as wanted, but an error message still pops up after outputing the correct definition (Pyth
Code runs as wanted, but an error message still pops up after outputing the correct definition (Pyth

Time:03-09

Apologies, I am new to coding so this might seem simple for some.

from PyDictionary import PyDictionary

dictionary=PyDictionary("hotel")


x = dictionary.printMeanings()
x = x.split()
y = x.pop()
y = y.join("")
print(y)

The error message is:

Traceback (most recent call last): 
    File "main.py", line 7, in <module> 
       x = x.split() 
AttributeError: 'NoneType' object has no attribute 'split'

CodePudding user response:

You'll get good at reading error messages. In this case, the message is telling you exactly what's up:

(6) x = dictionary.printMeanings()
(7) x = x.split()

It is complaining about line 7, x = x.split(). It is saying that x contains a value of type NoneType. This type can only have one value, the value None, so it's telling you that x contains None. You're trying to call .split() on this None value. You can't call .split() on a None. It's telling you that too, and that's why Python raised this particular exception.

What you can take from that is that the call to dictionary.printMeanings() on line 6 is returning None. Since you're calling .split() on the result returning that method, you must think it returns a string. It doesn't. It doesn't return anything. That's what getting back None means.

CodePudding user response:

This is very often confusing to new programmers: What you see on the screen (i.e., what print() outputs) is not the same as what print returns to the Python running program.

Basically, most functions and operations, e.g. string.split() or 2 2, return a value (which you can assign to a variable), but print nothing to the output. print sends something to the output but returns nothing. A few functions do both.

In Python, returning "nothing" means you actually return None, so that's what ends up in the variable x.

  • Related