0

I am learning python from here. In this exercise what it says is to find out the errors in his code that is given in this particular location

Now in the previous exercise, number 25, he made us write a few defs. In this code I see him using words = ex25.break_words(sentence). Now I am not sure if we can do this or not.

So what I did was to create a new python script and name it testScript.py. In this, I defined a function that just prints something out. In another python script, say myScript.py what I do is

testScript.callFunction()

I get an error when I run myScript.py:

NameError: name 'testSCript' is not defined.

But I do not get any such error when I am running the above code from the location given by the author. Also, in the Common Questions By Student section in the end in here. I am not sure what is he talking about in the first question. What exactly does he mean by removing the references.

Thanks

1 Answer 1

2

You can import your testScript given that the two files are in the same directory. In your myScript.py file, add this on top:

import testScript

Then you can do:

testScript.callFunction()

Alternatively, you could do it as (although I highly advise against this method):

from testScript import *
callFunction()             #no need to write testScript. anymore

Alternatively, you could also do it as:

import testScript as ts
ts.callFunction()

And finally, you also have the option of doing (again, I'd stay away from this one as well):

from testScript import callFunction
callFunction()

Hope that helps.

Sign up to request clarification or add additional context in comments.

5 Comments

but I want to know, howcome in the code from the link that the author has provided, I did not have to do any imports. How is it working and not giving any error?
@Kraken, They probably weren't in different files. Maybe just different classes in the same file.
There's one line that says ex25.break_words. Yeah, there's a function break_words in the same file but it is still preceded by ex25, now that is the file name for exercise 25. Should not it be an error?
@Kraken, Perhaps (just perhaps) the author chose not to include that part of the code so as to avoid confusion and focus on teaching about some other topic. I'm not entirely sure. It is hard to understand from your links. However, I can assure you that you have to import a file to use it's methods.
It's not just the author's code. I did try to run it on my machine. Maybe I missed something. Will try again.

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.