Getting a Colon Syntax Error 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 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

Related

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]

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()

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)

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.

Pythonic way to check logics [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I have found so far in many cases python code for checking business logic or any other logic is some thing like below(simplified):
user_input = 100
if user_input == 100:
do_something()
elif user_input > 100:
do_sth_different()
else:
do_correct()
When a new logic need to be checked what new python programmer(like me) do just add a new bock in elif...
What is pythonic way to check a bunch of logic without using a long chunk of if else checking?
Thanks.
The most common way is just a line of elifs, and there's nothing really wrong with that, in fact, the documentation says to use elifs as a replacement for switches. However, another really popular way is to create a dictionary of functions:
functions = {100:do_something,101:do_sth_different}
user_input = 100
try:
functions[user_input]()
except KeyError:
do_correct()
This doesn't allow for your given if user_input > 100 line, but if you just have to check equality relationships and a generic case, it works out nicely, especially if you need to do it more than once.
The try except case could be replaced by explicitly calling get on the dictionary, using your generic function as the default parameter:
functions.get(user_input,do_correct)()
If that floats your boat.
Aside from the fact that the way you're doing it is probably the best way, you could also write it as:
user_input = 100
do_something() if user_input == 100 else
do_sth_different() if user_input > 100 else
do_correct()

Categories

Resources