Function not being defined even though ive saved it - python

I have a fully working programme that I wish to run. It executes on my friend's laptop, but not mine, (I've saved it to my documents folder) the following is the program:
def DigitCount(n):
#how many decimal digits in integer 'n'
if n<0:
n=-n
digitCount=1
powerOfTen=10
while powerOfTen<=n:
digitCount+=1
powerOfTen*=10
return digitCount
But I keep getting the following error:
>>> DigitCount(100)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
DigitCount(100)
NameError: name 'DigitCount' is not defined

Wait, are you saying you do the following from the command line?
$ python DigitCount.py
$ python
>>> DigitCount(100)
That won't work. You have to do this:
$ python
>>> import DigitCount
>>> DigitCount.DigitCount(100)

Related

issues running a face_recogition file using editors and cmd

When I run the code below in jupyter, it is excellent, I get the results I want.
real = fr.load_image_file("image.jpg")
unknown = fr.load_image_file("image2.jpg")
# encodings
real_encoding = fr.face_encodings(real)[0]
unk = fr.face_encodings(unknown)[0]
result = fr.compare_faces([real_encoding], unk)
print(result)
but when I copy and paste the same code to an editor(atom the one I am using), and then run it using command prompt, I get an error as shown below
Traceback (most recent call last):
File "face_recognizer.py", line 13, in <module>
real_encoding = fr.face_encodings(real)[0]
IndexError: list index out of range
I activated the environment in which I was running the cmd.
Can someone advise me where I maybe going wrong?
There was no face captured in the photo.
That is why it throws an exception.

My question is about the functionality of the 'eval' function when this is included in a function of an imported module

I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC

python 3 NameError

Edit: Thank you for your helpful answers! I downloaded Python 3.7.0 but you are right, my Mac is running Python 2.7. I have homework now :) Figure out how to get it running 3.7. I will come back if I have more questions. Thank you!
Beginner here. I'm getting NameError when executing in Mac with Python Launcher. When testing in Python 3.7.0 Shell it works ok. I've read other answers to NameError questions, but do not understand what I'm doing wrong. Help is appreciated.
Code used
first_name = input ("Hi, what's your first name? ")
print ("Hi," , first_name)
Error received
Traceback (most recent call last):
File "/Users/imperio/Documents/pythonpractice/Name.py", line 1, in <module>
first_name = input ("Hi, what's your first name? ")
File "<string>", line 1, in <module>
NameError: name 'Imperio' is not defined
This is most likely because you are not executing it using Python 3+.
Please check the output of python -V to see which version you are executing your code with.
On mac you may already have both installed, Python 3 is sometimes aliased under python3 file.py
Here's your program converted to valid Python2:
first_name = raw_input ("Hi, what's your first name? ")
print ("Hi, {}".format(first_name))
You're running Python 2. In Python 2, input executes the input. raw_input just returns the string entered.
Here's an example:
>>> x = 1
>>> y = 2
>>> z = 3
>>> print input('variable? ')
variable? x # Note output is the value of the variable
1
>>> print input('variable? ')
variable? w # Variable 'w' doesn't exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'w' is not defined
>>> print raw_input('variable? ') # Raw input just returns the input.
variable? x
x

Running a python method/function directly from a file

I would like to know if there is a way to directly run a python function directly from a file by just mentioning the filename followed by the function in a single line.
For example, lets say I have a file 'test.py' with a function 'newfunction()'.
----------test.py-----------
def newfunction():
print 'welcome'
Can I run the newfunction() doing something similar to this.
python test.py newfunction
I know how to import and to call functions etc.Having seen similar commands in django etc (python manage.py runserver), I felt there is a way to directly call a function like this. Let me know if something similar is possible.
I want to be able to use it with django. But an answer that is applicable everywhere would be great.
Try with globals() and arguments (sys.argv):
#coding:utf-8
import sys
def moo():
print 'yewww! printing from "moo" function'
def foo():
print 'yeeey! printing from "foo" function'
try:
function = sys.argv[1]
globals()[function]()
except IndexError:
raise Exception("Please provide function name")
except KeyError:
raise Exception("Function {} hasn't been found".format(function))
Results:
➜ python calling.py foo
yeeey! printing from "foo" function
➜ python calling.py moo
yewww! printing from "moo" function
➜ python calling.py something_else
Traceback (most recent call last):
File "calling.py", line 18, in <module>
raise Exception("Function {} hasn't been found".format(function))
Exception: Function something_else hasn't been found
➜ python calling.py
Traceback (most recent call last):
File "calling.py", line 16, in <module>
raise Exception("Please provide function name")
Exception: Please provide function name
I think you should take a look at:
https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/
All those commands like migrate, runserver or dbshell etc. are implemented like how it was described in that link:
Applications can register their own actions with manage.py. To do this, just add a management/commands directory to the application.
Django will register a manage.py command for each Python module in that directory whose name doesn’t begin with an underscore.

Python : NameError: global name 'GetText' is not defined

I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!

Categories

Resources