probably I am gessing not properly but I can't figure out why that happen.
A break through the script I am trying to write, OS Windows 10, Visual Studio Code, Python 3.7
I wrote a class with a function which should print out into the console and in a .txt file some data scraped by a web page.
Here the function:
def create_alimento(Componenti_principali):
for col1, col2 in zip(soup.select('#tblComponenti > tr.testonormale > td:nth-of-type(1)'), soup.select('#tblComponenti > tr.testonormale > td:nth-of-type(2)')):
print('{: <70} {}'.format(col1.text, col2.text))
The console's output doesn't have any problem, it does it's own job and seems all clear to me. What I don't understand is the .txt output, it comes to an error, TypeError precisely: write() argument must be str, not None.
It clearly say that the Class I am trying to print (which include also the function above) is a None type, therefore is the main object.
Now, the thing is, if I flip:
print('{: <70} {}'.format(col1.text, col2.text))
with :
return('{: <70} {}'.format(col1.text, col2.text))
...the function object type is "string", not anymore NoneType.
I wouldn't point it out if all would be ok, obviously, using return
instead of print
, doesn't give a .txt output.
Anybody does know what happen here? and any advice to print both at console and in a .txt the same output?
Thanks in advance, Mx
A return
returns a value from a function, for example:
def f():
return 7
seven = f()
# value of seven is now 7
A print does not return a value, for example:
def f():
print(7) # at this point "7" is printed to the standard output
seven = f()
# value of seven is now None
If you want to both print a value and return a value, you should do exactly that, e.g.:
def f():
print(7) # at this point "7" is printed to the standard output
return 7
seven = f()
# value of seven is now 7
BTW, It would be a better design to just return the value. You can always print it from the outside if you want, i.e.:
def f():
return 7
seven = f()
# value of seven is now 7
print(seven) # at this point "7" is printed to the standard output