Python Scope and Nonlocal Issues [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 7 years ago.
Improve this question
I'm new to Python and a little confused with the whole nonlocal thing. Here's the problem snippet of code:
positon = 0b0
while True:
pos_choice = input("\tPlease enter your choice: ").lower()
if pos_choice == '1':
position = position | Baseball.pitcher
break
elif pos_choice == '2':
position = position | Baseball.catcher
break
elif (pos_choice == 'd') and (position != 0b0):
break
elif (pos_choice == 'd') and (position == 0b0):
print("\tChoose a position.")
else:
print("Invalid choice.")
print(position)
So this throws me :
Traceback (most recent call last):
File "driver.py", line 252, in <module>
load_student()
File "driver.py", line 142, in load_student
position = position | Baseball.catcher
UnboundLocalError: local variable 'position' referenced before assignment
Based upon what I've read on answers to other questions, the problem would be because the problematic "position" is nested two loops in from the original call (is that right?).
My main problem is that I can't figure out how to bind the two "position"s using nonlocal, though I have tried various solutions to no avail. Also, is using nonlocal a taboo like it is when using global? Thanks for the help!

You have a typo in your code. In the declaration, the variable is spelled positon instead of position.

There is a simple typo in your first line.

Related

I have an indentation error in python 3 in an elif statement how do I fix this [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 10 months ago.
Improve this question
I keep getting an indentation error on line 17 but I cannot figure out why, this is a code from a tutorial I found online (https://picovoice.ai/docs/quick-start/porcupine-python/)
this is the error message:
File "/home/luke/Documents/wake_word/wake_word.py", line 17
elif keyword_index == 1:
^
Indentation Error: expected an indented block
I am using vim text editor and python3, here's my code:
import pvporcupine
porcupine = pvporcupine.create(
access_key='${ACCESS_KEY}',
keywords=['picovoice', 'bumblebee']
)
def get_next_audio_frame():
pass
while True:
audio_frame = get_next_audio_frame()
keyword_index = porcupine.process(audio_frame)
if keyword_index == 0:
# detected `porcupine`
elif keyword_index == 1:
# detected `bumblebee`
Comments do not count as a statement. To add a null statement, put pass keyword below the if/elif/else condition to avoid errors.
Also, an else statement after would help eliminate any future problems.
Eg:
if keyword_index == 0:
pass
# detected `porcupine`
elif keyword_index == 1:
pass
# detected `bumblebee`
Comments are not taken in account by the interpreter. So it sees:
if keyword_index == 0:
elif keyboard_index == 1:
and this is an illegal code because there's no things to execute after the :.
I suggest adding the keyword pass after the : llike this:
if keyword_index == 0:
# detected `porcupine`
pass
elif keyboard_index == 1:
# detected `bumblebee`
pass
so the interpreter will know there's nothing to do and will not say, "I see nothing to execute so let's raise an error".

Uncaught Error: NameError: name 'true' is not defined [duplicate]

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.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to use Boolean ( true / false ) in my python source file, but after running the application, I receive the following error:
NameError: name 'true' is not defined
The error lies on while true:, when I am trying to make the Raspberry Pi run a HTML script when it receives input on port 17:
import RPi.GPIO as GPIO
import time
import os
inputSignal = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(inputSignal,GPIO.IN)
while true:
if (GPIO.input(inputSignal)):
os.system("html /home/pi/index.html")
else:
print("No Input")
Python’s boolean constants are capitalized: True and False with upper case T and F respectively.
The lower-case variants are just valid free names for variables, so you could use them for whatever you want, e.g. true = False (not recommended ;P).
You haven't defined a variable true. Maybe you meant the built-in boolean value True?
while True:
# but seems like inifite loop

How can I define a Boolean to a variable? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
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.
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.
Improve this question
I am trying to make a calculator. I have the code that does the operations working, but I am trying to allow the user to keep the calculator running without having to rerun the code. i an trying to assign a Boolean to variable, but python keeps telling me there is a name error, which is the the variable is not defined. Can you please help me?
Thank you in advance.
I have tried to change the available name but it doesn't do anything.
The code stopped working when it got to the while run == true line.
else:
print('Invalid operator, please run code again')
run = True
while run == True:
print(' do you need another problem solved? y/n')
if input() == y:
run = True
elif input() == n:
run = False
I expected the code to ask me if I need another problem solved, but there is a name error.
If the error is complaining about y or n it's because you need to surround it with quotes
if input() == "y":
run = True
Also, run == True is not needed
while run:
does the trick
else:
print('Invalid operator, please run code again')
run = True
while run:
print(' do you need another problem solved? y/n')
inp=input()
if inp == 'y':
run = True
elif inp == 'n':
run = False
you have used input 2 times so your code will wait 2 times for input, use input() once.

Weird python syntax error with variable [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
I keep getting a syntax error on line 10 that says
Traceback (most recent call last):
File "main.py", line 5, in <module>
user = input("Choose a number")
File "<string>", line 1
python main.py
^
I can't figure it out. Can anyone help?
import random
number = random.randint(1, 20)
attempt = 5
def game():
global attempt
attempt -= 1
if attempt > 0:
if int(user) > number:
user = input("Choose a number")
print("Choose a smaller number\n " + (str(attempt) + " tries left"))
game()
elif int(user) < number:
print("Choose a larger number\n "+ (str(attempt) + " tries left"))
game()
elif int(user) == number:
print ("You guessed the number ")
else:
print("CONGRATULATIONS ")
game()
First, this is a run-time error, not a syntax error.
The problem is actually in the previous line: you've tried to use the value of user before it has one. You have to fix this before you can continue debugging your program. You need to get the user's first number before you can test it.
Problem A
I can't help but notice that your traceback message doesn't align with the code you have provided. It seems as though you already have the user variable assigned before defining and calling the game() function.
Solution A
If that is the case, try removing that line and apply the changes Prune recommended for you in the other answer. This will solve the code related problems in the program.
Problem B
However, the traceback also mentions that on line 1 you have python main.py. This is most likely caused by the way you are running the script.
Solution B
Try running it instead in the IDLE (distributed with Python) or Terminal / Command Prompt (depends on your OS) if not doing so already.
Last Resort
If the problem still arises, try running the snippet of code you included in the question by itself to see if it is functional ( add on Prune's revisions with it ).
Since the revised snippet should work, any errors that occur is definitely caused by how the code is ran. If no errors occur then look through your original source code for anything else that might be causing problems.
Good luck!

Syntax error 'continue' not properly in a loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
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.
Improve this question
elif command == 'join':
if len(params) < 1: continue
safeexec(params[0], getattr(botimpl, 'onenter', None), (params[0], prefix))
it says
Syntax error 'continue' not properly in a loop
when I run the file.
You cannot continue from an if statement. You need it to be in a loop.
for x in range(10):
if x == 4:
continue
# Do work
Whereas,
if x == 4:
continue
is wrong.
Python Docs state this:
The continue statement, also borrowed from C, continues with the next iteration of the loop:
The continue keyword is used to go directly to the next iteration of a loop, skipping the code after the keyword. So, the error
SyntaxError: 'continue' not properly in loop
indicates that the elif clause is not inside a loop (like for or while).
What can you do?
Check your logic. Do you really want to use continue?
Put the code inside a loop:
while (...):
if command == 'join':
continue
continue must be inside a while or for loop, check if your elif statement is within a for or while loop. if yes, check your indentation.
The continue keyword is reserved to skip the iteration of a loop and not a if condition block. What you want to do is more this:
elif command == 'join' and len(params) >= 1:
safeexec(params[0], getattr(botimpl, 'onenter', None), (params[0], prefix))
From the documentation:
continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. It continues with the next cycle of the nearest enclosing loop.
When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

Categories