Learn python the hard way, exercise 25 - python

Hello everyone i am new to the python language and i have chosen learn python the hard way to learn it and to better my understanding... I am stumped on exercise 25 , When we import the code directly into the terminal
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
And then I get an attribute error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'break_words'
I am using python 2.7 on
windows 7 please help..... http://learnpythonthehardway.org/book/ex25.html

It appears to me that the exercise does not instruct the learner to save the file prior to the import. In order for this to work, you've got to save the code that defines the break_words function in a file called ex25.py using your text editor. Then, from the same directory open the python interpreter by typing:
python
and you should be able to import ex25 and run the break_words function which the ex25.py module has defined.

The code in your link for ex25.py does include that function - that yours doesn't suggests that you've somehow missed it when you transcribed the code into your file. Check that your ex25.py includes all the code from the page, and in particular contains this function (it's the very top one):
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
Consider pasting the code into your editor in preference to transcribing it in order to avoid errors like this.

Related

"AttributeError: 'module' object has no attribute" - Can someone explain the meaning of this error message?

I'm trying to get the ODB library working. In the documentation at https://python-obd.readthedocs.io/en/latest/ it lists the following code:
import obd
connection = obd.OBD("/dev/ttyUSB0") # connects to USB or RF port
cmd = obd.commands.SPEED # select an OBD command (sensor)
response = connection.query(cmd) # send the command, and parse the response
print(response.value) # returns unit-bearing values thanks to Pint
print(response.value.to("mph")) # user-friendly unit conversions
When I put this in a file called test.py and I run it:
python2 test.py
I get the following error message:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import obd
File "/home/ubuntu/obd.py", line 3, in <module>
AttributeError: 'module' object has no attribute 'OBD'
Stackoverflow comes up with several iterations of this error message, but none clearly explain the problem, only giving specific solutions to those libraries.
I guess it's obvious that I'm new to Python, and I'm having trouble interpreting this error message, even after several hours of writing several small Python programs. I am of course also interested in why the error message is so un-intuitive to a newcomer and where I can gain the common knowledge I might be missing, and I guess this is as good a case to discover that through as any.
So far I have figured out the following:
<module> refers to the name of my python script that I am trying to run.
The mistake I made at first, was to name my test.py file, initially obd.py. This conflicted with the import obd as it was trying to import the file itself - even after I deleted it! The reason was that when I tried to run it the first time, it created a file called obd.pyc - and even though obd.py was no longer there, import OBD found the initially created obd.pyc and tried to import that - which of course does not contain the OBD object from the library I was trying to use.
This is not the detailed answer I'm looking for, so please add a more detailed explanation - or a link to how Python compiling works, if you can.

python 2.7.9/pycharm 4/windows7: 'file' object has no attribute 'readall'

I'm trying to write some VERY trivial thing in pycharm.
Problem:
sourceText = ""
with open("lang.txt", "rt") as sourceFile:
sourceText = sourceFile.readall()
print sourceText
when I enter "." after "sourceFile", I get popup that offers me "readall()" method. However, when I attempt to run the script, I get"
Traceback (most recent call last):
....languages/languages.py", line 4, in <module>
sourceText = sourceFile.readall()
AttributeError: 'file' object has no attribute 'readall'
The method is documented (I get popup, can get documentation for this method using Ctrl+Q) but it seems to be inaccessible.
I'm a bit confused.
I'd like to either:
Not receive any popups for inaccessible methods in pycharm.
Or figure out why I can't see it despite it being documented.
Advice?
I'm using windows 7 64 bit, and have two python 2.7.9 installations (32bit and 64bit), with 64bit being in path 1st. Pycharm is 4.0.5 community edition.
You are correct that readall is documented for the io module, but it's complaining about file, which does not have that method. You want the read() method to read all the data in the file in one large clump. You could also use readlines() which well return a list. I have the Pro 3.4 edition of PyCharm and it does not do this. I would report this as a bug to PyCharm.

Calling a function from another file in Python

Yes, this question has been asked before. No, it did not answer my question satisfactorily.
So, I'm creating my Giraffe Program in Python first (don't ask) and I'm trying to get the user to name their giraffe.
My files are all in one package called code. In the file Main_Code, the function createGiraffe is called from code.Various_Functions. Here is my code.
import code
print("Welcome to The Animal Kingdom.")
userGiraffe = code.Various_Functions.createGiraffe()
And the code in code.Giraffes:
import code
def createGiraffe():
print("Name your giraffe.")
GiraffeName = input()
return GiraffeName
However, when I run Main_Code, it gives me this error:
Traceback (most recent call last):
File "C:\Users\Jonathan\Documents\Aptana Studio 3 Workspace\The Animal Kingdom\src\code\Main_Code.py", line 3, in <module>
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
AttributeError: 'module' object has no attribute 'Giraffes'
How do I fix this? I believe that I've done everything by the book. It's all using the same package so I can call the function, I'm calling it from the right place, and the function has no syntax errors. Can anyone help with this?
Do
import code.Giraffes
before executing the offending line:
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
When you call function like:
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
it means you have a project in dir code with internal dir Giraffes and module Giraffes with function createGiraffe. Is this your exception?

Python NameError: name 'harris' is not defined

I apologize in advance if there is somewhere the same thread of mine.
I am new in Python programming and trying to compute an example from "Programming Computer Vision with Python" written by Jan Erik Solem.
Here is the code of the example (saved in a file called "harris.py"):
https://github.com/jesolem/PCV/blob/master/pcv_book/harris.py
(Be aware that my code ends at line 70)
After a good explanation of this code, in the book is stated: "Try running the following commands:"
im = array(Image.open(’empire.jpg’).convert(’L’))
harrisim = harris.compute_harris_response(im)
filtered_coords = harris.get_harris_points(harrisim,6)
harris.plot_harris_points(im, filtered_coords)
The problems I've encountered are two:
I am not sure where to run those last lines of code, in harris.py
or in a separate python file.
In whichever file I run it, the following error is shown:
harrisim = harris.compute_harris_response(im)
NameError: name 'harris' is not defined
I don't understand why this error is shown, since 'harris' should call the python script harris.py. Or am I wrong?
It is meant to go into a separate file, but you need to import the harris module first:
import harris
before the module is available to your code.
Harris name does not exists in your script (it was not initialised at any time before using it, so Python does not know what harris is). If import harris does not work, it is because the fact that you do not have any module called that way.

Python 3: tokenize library changes

According to this: http://code.activestate.com/lists/python-list/413540/, tokenize.generate_tokens should be used and not tokenize.tokenize.
This works perfectly fine in Python 2.6. But it does not work anymore in Python 3:
>>> a = list(tokenize.generate_tokens(io.BytesIO("1\n".encode()).readline))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/tokenize.py", line 439, in _tokenize
if line[pos] in '#\r\n': # skip comments or blank lines
However, also in Python 3, this works (and returns also the desired output):
a = list(tokenize.tokenize(io.BytesIO("1\n".encode()).readline))
According to the documentation, it seems like tokenize.tokenize is the new way to use this module: http://docs.python.org/py3k/library/tokenize.html. tokenize.generate_tokens isn't even documented anymore.
But, why is there still a generate_tokens function in this module, if it's not documented? I haven't found any PEP regarding this.
I'm trying to maintain a code base for Python 2.5-3.2, should I call generate_tokens for Python 2 and tokenize for Python 3? Aren't there any better ways?
generate_tokens seems to be really a strange thing in Python 3. It doesn't work like in Python 2. However, tokenize.tokenize behaves like the old Python 2 tokenize.generate_tokens. Therefore I wrote a little workaround:
import tokenize
if sys.hexversion >= 0x03000000d:
tokenize_func = tokenize.tokenize
else:
tokenize_func = tokenize.generate_tokens
Now I just use tokenize_func, which works without problems.
generate_tokens in python3 is undocumented but not uncommented. it's there for backward compatibility, so you can use it, but it's probably better to use the changed tokenize instead...

Categories

Resources