How to fix NameError: in Python? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am building code to find the largest prime factor of a number. I have written the code. Please point out the changes that need to be made to the code. Any help is appreciated !!
I have tried removing the class declaration and just declaring two functions as mentioned in the code but still the NameError: 'isPrime' used before declaration still persists.
class Soln(object):
def isPrime(self,num):
c=0
if (num<2):
return False
else:
for x in range(1,num):
if (num%x == 0):
c+=1
if (c>1):
return False
else:
return True
def nLargest(self,n):
for x in range(n,0,-1):
if(isPrime(x)):
print ("\nLargest Prime Factor is"+str(x))
exit()
a=Soln()
a.nLargest(12)
The output should be 3 but it gives
NameError: isPrime used before declaration.

You don't have 'global' method isPrime defined. You probably want to use the one, which is in the class Soln. In order to do this, you can write:
self.isPrime(x) (while calling from another method of Soln)
or
a.isPrime(x) (while calling on Soln object a from outside of this object)
or make the method static and use:
Soln.isPrime(x)

Use rhis code:
def nLargest(self,n):
for x in range(n,0,-1):
if(self.isPrime(x)):
print ("\nLargest Prime Factor is"+str(x))
exit()

Related

why does the return function in python is returning a value of 1 in factorial prog [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
#factorial prog
def fac(y):
fact=1
i=1
for i in range(1,y+1):
fact=i*fact
return fact
x=int(input("enter no"))
y=fac(x)
print(y)
why does the return function return 1
when I remove the defined function and find the factorial by same method in the main function its giving the correct answer and even in the defined function when i print fact value is providing the correct ans but only the return function is not working
can someone give me the same method code instead of recursive function
Indentation level of your return statement is wrong. You should do as following:
#factorial prog
def fac(y):
fact=1
i=1
for i in range(1,y+1):
fact=i*fact
return fact

Why isn't one of my variables defined? -Python 2.7 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So I'm fairly new still to python, and I'm trying to create a "word guessing" program, and part of that is creating a function that takes the inputted letter and then compares it to a list of letters, however it does not seem to recognize my definition of the variable "guess" in while (guess != ans):, any thoughts on why that is?
(Also here's my code as a reference):
def main():
ans = str("a")
guess = str("null")
letterList = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z]
while (guess != ans):
if(letterList[0] == ans):
guess = letterList[0]
main()
Error:
NameError: Name 'guess' is not defined on line 5
Python is an interpreted language and the interpreter relies on indentation to distinguish the different blocks of code.
If you don't know what that is, here's something you could read:
https://www.geeksforgeeks.org/indentation-in-python/
The problem in your code lies within the while loop.
Because your variable "guess" is within the scope of the function main, so only other variables and functions inside "main" can see it.
Also, your letterList has a problem, because each character should be within quotes(" " or ' ') otherwise python interprets them as variables which are not even defined.
Your while loop is in a different scope, the "global" scope and that is why your program doesn't recognize the "guess" variable.
And your loop is infinite because "guess" will always be different than "ans" is not changing.
If you could express what you want to accomplish in a better way, I could help you out.
def main():
ans = str("a")
guess = str("null")
letterList=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
while (guess != ans):
if(letterList[0] == ans):
guess = letterList[0]

Getting a Colon Syntax Error in Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Input
yourChoice = True
while yourChoice:
inf_or_ltd = input('Would you like to play infinte or a limited game?: '):
if inf_or_ltd = ((('Limited') or ('limited')) and (compScore == ('3'))):
exit = True
print("You lost, Goodbye")
break
time.sleep(1)
Why is the colon a invalid syntax? I've checked the bracket balance and the previous lines (which are just variables and importing a few modules). It says that a limited game?: '): is invalid syntax.
In Python, a colon : defines the start of a scope block, it's essentially the same as { in most languages.
But the colon isn't enough, scope blocks also need to be idented. The amount of identation depends on the parent block.
scope1:
scope2:
scope3:
A block ends when its identation ends, i.e.:
scope1:
scope1_statement
scope2:
scope3:
scope3_statement
scope2_statement
scope1_statement
Now, when would you create a new scope block? Well, you create them when you need to define a new scope, such as:
Declaring new methods (def, lambda, ...)
Declaring new code branches (if conditions, try-catch...)
In your scenario, you are trying to create a new scope after a statement (an instruction) which in this case is an assignment inf_or_ltd = input('...').
Python instructions cannot create a new scope block.
You need to place your if on the same identation as the above assignment;
inf_or_ltd = input('...')
if inf_or_ltd == anything:
# do something
else:
# do something else

Program skipping over if statement in for loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to update a clients details with a function. But it doesn't work. I debug the program and I realized that it never goes into the if. I don't know why?
This is the function:
def UpdateClient(self,id,cnp,name,adress):
for i in range (len(self.clients.get_all())):
if self.clients.get_all()[i].get_id==id:
self.clients.get_all()[i].set_name(name)
self.clients.get_all()[i].set_cnp(cnp)
self.clients.get_all()[i].set_adress(adress)
When I try to update the client, I give the id, name, cnp, and adress, but when I print the list nothing is changed. I cannot go into the if with the debugger because it said that they are never equal. Why?
Note that get_id is not the same as get_id(). The former references the method, while the latter actually calls it.
In addition, consider simplifying your code by writing more idiomatic Python. For example:
for client in self.clients.get_all():
if client.get_id() == id:
client.set_name(name)
...
The issue here is you are making your check as get_id == id but it is a function. Your if should be like:
if self.clients.get_all()[i].get_id()==id:
# ^ making it a function call
Also, better way to do this is by storing self.clients.get_all() in a separate variable. Hence, your code should look like:
def UpdateClient(self,id,cnp,name,adress):
clients = self.clients.get_all()
for i in range (len(clients)):
if clients[i].get_id()==id:
clients[i].set_name(name)
clients[i].set_cnp(cnp)
clients[i].set_adress(adress)

Python __dir__() doesn't change dir() [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I want to add 'dir' method to my object so when dir() is called on it, my function will be called.
My code looks like this:
class c(object):
def __dir__(self):
return ["a"]
print dir(c())
print c().__dir__()
Only the second print shows ["a"], and the first acts like normal.
I've tried this in several ways and sometimes it works and sometimes it doesn't. Any ideas why?
Edit:
I was missleading, my code is more complex then I showed. To be exact, my code creates an object 'x' with dir method and writing:
x.__dir__()
Works, but
x.__dir__() == dir(x)
Returns false
I suspect you are writing dir(c) instead of dir(c()) somewhere. The difference is calling dir on a class (dir(c)) invokes the class object which itself has a default __dir__(), which will give the undesired default behavior. What you have in your question right now (dir(c())) should work.

Categories

Resources