Why isn't one of my variables defined? -Python 2.7 [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 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]

Related

Python Beginner: Why is this my output? function generate at 0x0000021EE6848700 [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 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to generate random numbers using user input. This is for a homework question and is structured as the professor instructed. I'm returning x amount of this instead of numbers. function generate at 0x0000021EE6848700
I feel like this is a stupid question and I'm missing something obvious. When I try to define main with generate I get an error that I'm missing a positional argument. I have tried using print and return, and neither under generate. Am I not defining something correctly?
import random
def generate():
print(random.randint(-100, 100))
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(generate)
main()
You're not calling the generate method - you're literally printing the method itself. I think that you meant print(generate()).
That being said, print(generate()) doesn't make sense either because generate() doesn't return anything - it already prints. If you want to print the result of generate in main, you should return the result instead of printing. If you do that, though, the generate function wouldn't make much sense in the first place because all it would do is return the result of random.randint(-100, 100). In that case, you should just call that method "directly."
So, the corrected versions could be any one of the following:
def generate():
print(random.randint(-100, 100))
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
# Let the generate() function print
generate()
or
def generate():
return random.randint(-100, 100)
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(generate())
However, in this second version, the generate function is kind of pointless; it would be better to just do:
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(random.randint(-100, 100))

How to fix NameError: 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 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()

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

Python not finding array in locals() even though it is there [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making an algorithm that converts numbers into roman numerals, which involves an array. However, when I run my code, I tell it to check if they array exists, and create it if it doesn't (I use this complex method because the code has to restart itself a lot, you will see).
number = input("What number would you like to convert?")
number = int(number)
def alg(n):
if 'roman' in locals():
print("yes")
if n >= 1000:
roman = roman + ["M"]
n = n - 1000
print(roman)
print(n)
#alg(number)
else:
print("end")
else:
print("no")
roman = [""]
print(len(roman))
print(locals())
alg(number)
alg(number)
I have tried researching it on the Python documentation and on this site, but to no avail.
Every invocation of a function has its own set of local variables. Your check will always return false, because you have just entered the function.
If you want to keep the recursive implementation that you currently have, you should pass the roman variable as a second parameter to the alg function.
Are you sure you want to find it in locals() (which will only look in the scope of your function alg which is just starting, thus cannot containing your roman variable) ?
Maybe you want to look up into globals variables with globals() ?
You check for the word 'roman' in locals; this is not going to happen, as you have yet to define roman. A function's locals do not persist from call to call.
Your decrement
n = n - 1000
doesn't do anything useful (yet). The local copy of n gets changed, but you never use it. The original copy (from the main program) is still intact, as integers are not mutable.
Note that your recursive call passes number -- the main program's original number. You're always converting the original, never working on the smaller quantity.
I'll stop here: without design, structure, or comments, this code is a bit hard to follow.

Variables defined inside if or for statements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
What happens to variables assigned for the first time (defined) inside if statement or for loop if long time passed from when their code run. Is there some sort of garbage collection that may result in a not defined variable exception. For example:
if True:
a=1
else:
a=3
# long time passed and other codes run
# .
# .
# .
print (a)
I encountered an error in my code that I suspect this to be the reason. Is it documented somewhere in official Python documentation ?
In Python, if you define a variable within an if statement, it will continue to exist after the if statement concludes. Scopes are defined for a class, a def, or the global scope; if you're in a function and you define a variable inside if, for example, that variable will exist until the function is done executing.
Be careful, however, of defining variables in code like this:
if x == True:
a = 1
else:
print "Not true"
If you have code like this, and x ends up being False, then a will not be defined. Later calls to a will throw an exception as a result. So make sure that you get rid of any potential problems of that sort.

Categories

Resources