Python 3.4.2 | NameError: name 'x' is not defined - python

I'm working on a word based maze game in Python 3.4.2, and I am having problems with this error message when I try to run it: NameError: name 'direction' is not defined
This is how I have defined it:
def chooseDirection():
direction = input('''What way will you go? (Type Left or Right or Forward then press enter.) ''')
Then I tried using 'direction' this way:
if direction == str(Right or right):
print ('Congrats! You have turned the right way, you can live...')
time.sleep(1)
print ('For now o.O')
I can't find any issues with my code, and I have checked some other similar questions from stackoverflow, but none have worked.
Here is my full code
Any idea's would be greatly appreciated and let me know if you need any more information.
Thanks, Sebastian.

def checkDirection(chooseDirection):
print('You have now entered the maze.')
time.sleep(0.5)
if direction == str(Right or right):
print ('Congrats! You have turned the right way, you can live...')
time.sleep(1)
print ('For now o.O')
replace direction with chooseDirection because that is the argument you are trying to pass ( or take the value)
for if else if you use
if (direction == 'Right' or direction == 'Left'):
Also
def chooseDirection():
direction = input('''What way will you go? (Type Left or Right or Forward then press enter.) ''')
return chooseDirection
I think you want to return direction, not chooseDirection.

I checked your code. You really need to read a good tutorial on Python.
For correction your code;
First of all you should change checkDirection parameter to direction. You do not have direction variable in checkDirection method.
def checkDirection(direction):
...
Also you do not handle return value of chooseDirection method.
Inside while loop you should put it a variable and call checkDirection with it
d = chooseDirection()
checkDirection(d)
Finally chooseDirection not return correct variable. It should be direction

Related

can't get program to iterate properly (TypeError: 'NoneType' object is not iterable)

So just getting started learning python. as practice i decided to build a program that would handle my attacks for my D&D character and i can't quite seem to get this to iterate properly.
from random import randint
def roll_dice():
type = raw_input("Initiative (i) or Attack (a): ") #variable that is passed through the function
roll = randint(1,20)
if roll == 1:
print "Natural 1"
elif roll == 20:
print "Natural 20"
else:
crit = "n"
if type == 'i':
result = roll + 5
print "Initiative = %d" % result
return
elif type == 'a':
""" most of the rest of the program is after here but that all works fine so there is no reason to take up space with that"""
roll_dice()
for type in roll_dice():
if type == 'a' or type == 'i':
continue
program will loop once and then gives me:
TypeError: 'NoneType' object is not iterable
I know this means that the second time it goes to iterate it is passing nothing through but i can't quite figure out how to fix it.
any help and/or explanations would be greatly appreciated
Edit:
I know it does not run as posted. The whole thing is over 100 lines and I did not want to swamp people with that. Once I get home I will post with the whole thing.
For clarification: With the whole program it will run once through loop back to the start and then return the error after a completed second run through the program. So the first time through the loop works it is after the completed second run and attempting to start a third.
It doesn't seem like your roll_dice() function returns anything, causing the TypeError. The reason it "seems" like the program loops once is because of the line right before the for loop, which calls the function.
What it seems like you are trying to do is extract the type variable from inside your function, which can be done by returning the type with return type instead of just return and using the if statement alone. To loop until type isn't a or i, a while loop may be more useful, like so:
while True:
type = roll_dice()
if type != 'a' and type != 'i':
break

How should I redefine my function variable to point to the correct function, position and index?

I know this is basic, but I'm just learning and can't seem to figure this out. I've set my user_guesses function with the definition of right_answer, which returns an error because "stage" isn't defined.
I've tried looking for an answer on here, but I know that it's not that my global name is misspelled. I don't think I can eliminate this variable, since it's the only variable of the function. If it simply needs to be defined, I can't seem to figure out how - maybe it's obvious, but not to me yet.
I've tried to be as detailed as possible. Please let me know if I can clarify anything further.
Maybe I just need to reorganize my code somehow? There very well may be more issues than this one with my code, since I can't quite figure out how to effectively debug yet, but I hope you all will have mercy on me and help me to realize why user_guesses isn't right. Thanks in advance.
blanks = {"Easy": ['__1__', '__2__', '__3__', '__4__'],
"Medium": ['__1__', '__2__', '__3__', '__4__', '__5__'],
"Hard": ['__1__', '__2__', '__3__', '__4__', '__5__', '__6__']}
answers = {"Easy": ['modern', 'mineral', 'mathematical', 'hypotenuse'],
"Medium": ['judgment', 'alibi', 'bargain', 'jean valjean', '24601'],
"Hard": ['capri', 'eliza', 'enormous', 'spring', 'windowsill', 'loverly']}
Easy_ABS = answers["Easy"], blanks["Easy"], song["Easy"]
Medium_ABS = answers["Medium"], blanks["Medium"], song["Medium"]
Hard_ABS = answers["Hard"], blanks["Hard"], song["Hard"]
index = 0
#Stage Selection#
def difficulty(stage):
if stage == 'easy':
print "\nGreat choice! Good luck, Major-General:\n"
return (Easy_ABS)
elif stage == 'medium':
print "\nVery good! Now, who am I?:\n"
return (Medium_ABS)
elif stage == 'hard':
print "\nOoo, interesting! Enjoy the eloquent ramblings of Audrey Hepburn:\n"
return (Hard_ABS)
def user_guesses(right_answer):
user_input = raw_input("What's your best guess?: ")
right_answer = difficulty(stage)[0][index]
for answer in answers:
if user_input == right_answer:
return True
print "Nice! On to the next!"
return replace_blank(song, blank, index)
index += 1
else:
print "Sorry, not quite. Try again!"
user_guesses(user_input, right_answer)

scanning user input in python

direction = input("enter a direction: ")
if direction != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction != "look":
print ("please enter in the following format, go (north,east,south,west,up,down)")
elif direction == "quit":
print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ... the game should then end.")
elif direction == "look":
print ("You see nothing but endless void stretching off in all directions ...")
else:
print ("You wander of in the direction of " + direction)
i need to know how to do this in python.
i need to scan user inputs first 2 letters
for example
i = user_input
#user inputs go ayisgfdygasdf
i need it to be able to scan the user input, check if the first 2 letters are go, and if they are go but it doesnt recognise the second word which in this case is "ayisgfdygasdf" then to print "sorry, i cant do that"
He could also try using:
directions.split()
But it may require to use try/except in some cases.
For more information about split and methods try using:
dir(directions)
to see what methods object directions have
or:
help(directions.split)
to see help about a specific method (in this case method split of object directions)
You can access characters of a string in python by index using the [] notation. You can check the first two character in a string by typing user_input[:2]. This code will include all characters up to, but not including the index typed. So this notation will include user_input[0] and user_input[1]. You can then check if user_input[:2] is equal to 'go' or not, and continue from there.
Hope this helped.
Instead try using:
direction = sys.stdin.readlines()
It may require you to ctrl+D after you are done but you will be able to capture so much more.
Also, to get the subarray you can then you can even check:
direction[:2] != "go"
or alternatively, for more readable code:
if not direction.startswith("go"):
Also I'd recommend, for making your code more readable,
defined_direction = frozenset(["quit", "go north", "go south"])
if( direction not in defined_direction):
print "please enter...."
You can index the individual characters of your input:
if direction[:2] == "go":
print "Sorry, I can't do that."
However, trying assign an if-else branch to each possible input is typically a bad choice... It becomes difficult to maintain very quickly.
A cleaner approach in this case might be to define a dictionary with valid input as follows:
input_response = {"quit":"OK ... but", "go north": "You wander off north", \
"go south": "You wander off south"} # etc
You could then re-write your code to something like:
try:
print input_response[direction]
except KeyError:
if direction[:2] == "go":
print "Sorry, I can't do that."
else:
print ("please enter in the following format...")

only letting user do a function once in Python?

I am very new to Python. running on windows while I wait for some stuff for my Pi.
I am writing a game where the user travels through a tower via text inputs.
the user can use "a" "d" "w" to look around a room to collect sutff. but if the user has already looked in "a" (which is "look left") i need to let them know they have already been there.
this is my code but it has an obvious flaw.
#if user hits 'a' they look left
def roomOneLeft():
print '-- You search some loose rubble and find some cloth'
return roomOneMoves()
#where the user selects a movement
def roomOneMoves():
left = 0
move = raw_input("")
if left == 1:
print 'you have already looked here'
return roomOneMoves()
if move == "a":
left = left + 1
roomOneLeft()
can i set "left" to static? and ant work out how to set it as global variable like java. this obviously doesn't work because when it returns, it sets itself back to 0. any help would be greatly appreciated!
You can define "left" as global. Like this:
left = 0
#where the user selects a movement
def roomOneMoves():
global left
move = raw_input("")
if left == 1:
print 'you have already looked here'
return roomOneMoves()
if move == "a":
left = left + 1
roomOneLeft()
To make a variable global, declare in the module scope, and then to change it in a function, use the global keyword.
left = 0
def some_func()
global left
left = 1
That will allow you to edit global variables inside a function.
To address your static variable question, I believe you cannot do this in python. See this question.

python list Index out of range error

I am working on a python tetris game that my proffessor assigned for the final project of a concepts of programming class. I have got just about everything he wanted to work on it at this point but I am having a slight problem with one part of it. Whenever I start moving pieces left and right I keep getting "index out of range error". This only happens when it is up against a piece. Here are the culprits that are giving me grief.
def clearRight(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]+1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
def clearLeft(block=None):
global board, activeBlock, stackedBlocks
isClear = True
if(block == None):
block = activeBlock
if(block != None):
for square in block['squares']:
row = square[1]
col = square[0]-1
if(col >= 0 and stackedBlocks[row][col] !=None):
isClear=False
return isClear
I am not looking to get anyone to fix it for me, I'm only looking for tips on how to fix it myself. Thanks in advance for any help that is given.
There a typo that would cause that problem in the first method.
When you're checking each cell in the block shifted one right, you don't check if they are off the grid.
if (col >= 0 and ...)
probably should be
if (col < num_cols and ...)
I also agree with CrazyDrummer, make a generic clear function
Spoilers ...
def clear(x_offset, block=None):
if not block:
block = activeBlock
if not block: return True
for x,y in block:
x += x_offset
if not (0 <= x < num_cols) or stackedBlocks[x, y]:
return False
return True
Look at what's different when you're getting the exception. Try printing out program state information to help you zero in. There's only one place where you access an array with variable indexes, so you can narrow your search radius a bit.
Separate suggestion: Make a generic clear that takes determines what direction you want to clear from by the parameters.
I highly recommend the book debugging rules!, it will aid you in searching out and properly fixing problems. :D

Categories