How to solve python's NameError: name 'xx' is not defined? - python

I am learning python, according to the logic written in the code in the book, I want to see the running result, the code is as follows, but the output error NameError: name 'pr' is not defined
code show as below:
stack=[]
def pushit():
stack:append(input(' Enter New String: ').strip())
def popit():
if len(stack)==0:
print('Cannot pop from an empty stack!')
else:
print ('Removes [','stack.pop()',']')
def viewstack():
print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
pr='''
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYou picked:[%s]'%choice)
if choice not in 'uovq':
print('Invalid option,try again')
else:
break
if choice=='q':
break
CMDs[choice]()
if _name_=='_main_':
showmenu()
The error message is as follows:
Traceback (most recent call last):
File "/Users/zego/Desktop/test.py", line 22, in <module>
choice=input(pr).strip()[0].lower()
NameError: name 'pr' is not defined

You have not inserted the showmenu function code at right index. The while loop should be started from one tab space ahead.
Look at the below code.
stack=[]
def pushit():
stack:append(input(' Enter New String: ').strip())
def popit():
if len(stack)==0:
print('Cannot pop from an empty stack!')
else:
print ('Removes [','stack.pop()',']')
def viewstack():
print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
pr='''
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
while True:
while True:
try:
choice=input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice='q'
print('\nYou picked:[%s]'%choice)
if choice not in 'uovq':
print('Invalid option,try again')
else:
break
if choice=='q':
break
CMDs[choice]()

Related

How can I repeat a function in python 3?

So here is my code:
membership_data = open("C:\\Users\\user\Desktop\Pre-release\membership_data.txt", "w")
def ValidateMemberID(MemberID):
if len(MemberID) !=6:
return("Wrong Format")
elif MemberID[:1] == (MemberID[:1]).lower():
return("Wrong Format")
elif MemberID[1:3] == (MemberID[1:3]).upper():
return("Wrong Format")
elif (MemberID[3:]).isdigit() == False:
return("Wrong Format")
else:
return("Correct Format")
def inputdata():
Name = input("Please input member name")
MemberID = input("Please input member ID")
ValidateMemberID(MemberID)
if ValidateMemberID(MemberID) == "Correct Format":
NameID = [Name, MemberID, "\n"]
else:
print ("Invalid MemberID")
membership_data.writelines(NameID)
for _ in range(5):
do()
inputdata(_)
membership_data.close
The issue I get is:
Traceback (most recent call last):
File "C:\Users\user\Desktop\Pre-release\task_3.1.py", line 31, in <module>
do()
NameError: name 'do' is not defined
What I want to do is to input 5 different records upon the first instance of my program. Essentially I need to run inputdata() for 5 times. However, my for in range do function keeps giving back this error. I tried different ways of writing it but to no avail.
I think you must delete 'do()' from your code
for x in range(5):
inputdata()
membership_data.close()

How to capture the enter key in Python without Tkinter

I need to make my program start over in Python if the enter key is pressed. I found this question and solution: how to check if the enter key is pressed python. However when I googled event.keysym, it seemed to have something to do with Tkinter which I don't think I have.
When I try using the solution I get an error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if event.keysym == 'Return':
NameError: name 'event' is not defined
I am a complete newbie having just completed a course with Dr. Severance on Coursera.
Here is the program I wrote to play pigs and bulls at work. Everything works as I want. The only problem is to exit the program if any key other than the "enter" button is pushed.
while True:
while True:
word= raw_input("Enter a four letter English word with no repeating letters: ")
print
if len(word) <> 4:
print "What part of 'four letter word' did you not understand? Try again."
print
continue
else: break
guesses = 0
while True:
correct = 0
position = 0
cnt = 0
result = 0
guess= raw_input("Enter a guess: ")
guesses = guesses+1
#print "guessses", guesses
for w in guess:
cnt = cnt+1
#print "cnt", cnt
position=0
for g in word:
position=position+1
#print "position", position
if g == w:
correct = correct+1
if position == cnt:
result = result+1
#print "result", result
print
print "Number correct:", correct
print "Number in the right position:", result
print
if correct<>4 and result<>4:
print "Give me another guess"
print
continue
elif correct == 4 and result == 4:
print
print "YOU WIN"
print
print "It took you", guesses, " guesses to get it right"
print
break
answer= raw_input("press ""enter"" to play again")
if event.keysym == 'Return':
continue
else:
exit
print
print
Then I thought, maybe I have replace "event" with my string variable "answer" but then I got this error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if answer.keysym == 'Return':
AttributeError: 'str' object has no attribute 'keysym'
Also, If I press any other key, it simply prints in Idle and the program does not exit.
By the way, I know there has to be a better way to program this using lists or dictionaries, but this is all I know how to do.
pressing enter would result in a zero-length word. make that your first check.
however, if you want to catch a single keyhit, like getch() in C, it's a lot more complicated, e.g. https://stackoverflow.com/a/6599441/493161
another alternative would be to trap ^C (control-C):
try:
answer = raw_input('Control-C to exit, <ENTER> to play again: ')
if len(answer) > 0:
raise(ValueError('Unexpected input'))
else:
continue
except (KeyboardInterrupt, ValueError):
sys.exit(0)

Python Syntax Error (except ValueError:)

I have a small code which is just for me to get more used to python and I have encountered a problem with try and except.
I am trying to get the code below to ask a question and receive an answer using raw_input. If you know what the syntax error in line 22 is? (except ValueError)
Thank you very much.
def start():
print("Type start")
prompt_sta()
def prompt_sta():
prompt_0 = raw_input ("Enter command start")
try:
if prompt_0 == "start":
prompt_sta()
elif prompt_0 == "begin":
print ("You must learn to follow commands")
prompt_sta()
elif promt_0 == "help":
print ("Commands:")
print ("Help")
print ("start")
print ("begin")
prompt_sta()
else:
print ("Please enter a valid command.")
prompt_sta()
print ("Type start")
**except ValueError:**
def outside_house():
print("There is a strange man outside.")
Just in case the error that IDEL is showing has ** on both sides and if you know any better ways for doing what I am trying to do please tell me. Thanks
You need to provide a body for except: statements:
try:
a = "something"
except ValueError:
pass # empty body

ERROR-HANDLING not working

My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()

Using .readlines() and struggling to access the list

I am struggling to access the list created by using .readlines() when opening the text file. The file opens correctly, but I am not sure how I can access the list in the function 'display_clues()'.
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clues_open()
print(clue_list)
Error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
display_clues()
File "N:\Personal Projecs\game\game.py", line 35, in display_clues
print(clue_list)
NameError: name 'clue_list' is not defined
Thanks!
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
#print clue_list #either print the list here
return clue_list # or return the list
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = raw_input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clue_list = clues_open() # catch list here
print clue_list
display_clues()
You have to return the list from clues_open() to display_clues():
def clues_open():
with open("clues.txt","r") as cluesfile:
return cluesfile.readlines()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
if clues_yes_or_no.lower() == "y":
clues_list = clues_open()
print(clue_list)
As a side note: I removed your worse than useless except block. Never use a bare except clause, never assume what actually went wrong, and only catch exception you can really handle.

Categories

Resources