NameError: name 'home' is not defined - python

Im writing a text game and all other parts of my code are working i think but ive been trying to figure out why my variable isnt defined.
I could be missing something simple but i just cant find it.The problem is under def aussie().
Ive tried changing indents, changing variable name and checking for " or () missing/
def aussie():
home= input("""
'Where are you from? it'd be better off taking you home than you travelling with us
A)Ortus
B)...""")
if "A" in home:
print("""
Eugene says 'How the hell did you end up out here then?You know what doesnt matter'
They take you back home to Ortus.
You Win""")
start()
if "B" in home:
print("""
Eugene says 'Right then guess your coming back to Australia with us!'
You live happily ever after with Eugene
You Win?!""")
start()
def boat():
h= input("How will you get help?")
if "swim" in h:
print("""
The boat goes right past you leaving you stranded.
You Lose""")
start()
if "shout" in h:
print("""
One of the crew members hear you and shout orders to slow the boat.You notice he has a
very strong Australian accent. The crew help you onto the boat wrapping you in towels
and blankets before sitting you at a table.You are in a state of shock.
You try to stand up but feel nauseous and dizzy.You fall to the floor with a thud.
The same Australian man rushes in and props you up against a wall before sitting next
to you on the floor.He sits for a while and chats to you letting you know his name is Eugene.
When you feel better he asks,""")
aussie()
start()
direct()

Your indentation is wrong. You must be very careful with indentation in Python Because start() is in column 1, it is no longer considered part of the function. It will be executed immediately. You might consider storing your very long strings in a global array up at the top, to make the indentation more obvious.
And, by the way, if start ends up calling aussie or boat, then you have recursion going on. That is NOT a good way to design something like this. These functions should return True or False telling the caller whether they should loop around again or exit.

Related

Why did I get an error from this python code?

I have a question on this code im trying to write. It says an error with "NameError: name 'answer' is not defined on line 1". Can someone point out what is wrong?
def main():
answer = input("Would you like to play a game? yes or no")
if (answer == "yes"):
firstChoice = input(
"There was once a knight, stuck in a forest trying to look for a princess. The knight had 2 ways he could go. Should he go left, or right?"
)
if (answer == "left"):
secondChoice = input(
"He decides to go left. As he passes the trees, he sees something he hasn’t seen before. A GIANT DRAGON! He pulls out one of his weapons. Which weapon did he pull out? Oversized Sword or Flamethrower?"
)
if (answer == "mighty sword"):
thirdChoice = input("He pulls out his mighty weapon. It was about as tall as a bus! The dragon said, Wait, just the size of a bus? I’m like, 200 buses. The knight, realizing that his choice was stupid, got the heck out of there! The dragon, being the 200 buses that he is, couldn’t find the puny mortal. He decided to brush it off and went to his dome. The poor knight, out of breath, gets a drink of water from a creek. The knight says, Wait, I know this creek! This is the Golden Creek, so if I follow this path, the dome should be right there! The knight decides to go with his gut and follow the path. And before he knows it, the princess was trapped inside of the dragon’s dome! He knew he had to do something, but what? Should he sneak in, or barge in alone?")
if (answer == "sneak in"):
print("He tries to sneak in. Getting past every dragon guard, was surprisingly easy. Their eyes are on the side of their head, so if you just walk in front of them, you should be good. Luckily, when the knight came, the dragon was asleep. He needed crucial silence, where not the single creek of wood, or cling of the armor could wake up the dragon. The knight whispers to the princess, I have come to save you! The princess carefully follows the brave knight, and they make it out! The king is happy with your success in keeping the princess alive, and you are promoted to secretary, the highest rank below the king! YOU WIN")
This is a scope error. You initalize answer in your main method, however as soon as that method closes, the variable is deleted. The 3 if statements do not have access to this variable.
First, you don't need to use the parenthesis in the if statements. The error is likely caused by not using a tab when you define the function.
Sorry about suggesting an IDE, don't know how you could have copy and pasted the text...
Without running your code, i can see a big problem, you may want to try this
After each input tag, you say "if answer =="
But remember, the answer variable is going to be the first thing the user inputted
so if they put "yes" the answer variable will always be "yes" throughout the entire script unless you redefine it
EDIT
When i first answered, the post was not entirely in the code block so i couldn't see the indentation
The variable answer is only within main() to use it outside of main() you should define it globally, meaning before the main function
Actually, you just need to use global before the declaration.

why is there def enter(self): function in all the classes of ex43.py of LPTHW that's never called anywhere in the whole project?

i am on exercise 43 from Learn Python The Hard Way by Zed Shaw. There are so many things i don't get but they are here or there been asked in different forums. what i didn't get here is in the following code excerpts:
class Scene(object):
def enter(self):
print("This scene is not yet configured.")
print("Subclass it and implement and enter().")
exit(1)
this enter(self) has been defined in almost all the classes of the project. but i don't see it being called anywhere. what's its purpose?
class LaserWeaponArmory(Scene):
def enter(self):
print(dedent("""
You do a dive roll into the Weapon Armory, crouch and scan
the room for more Gothons that might be hiding. It's dead
quiet, too quiet. You stand up and run to the far side of
the room and find the neutron bomb in its container.
There's a keypad lock on the box and you need the code to
get the bomb out. If you get the cod e wrong 10 times then
the lock closes forever and you can't get the bomb. The
code is 3 digits.
"""))
code = f"{randint(1,9)}{randint(1, 9)}{randint(1, 9)}"
guess = input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print("BUZZZZZED!")
guesses += 1
guess = input("[keypad]> ")
if guess == code:
print(dedent("""
The container clicks open and the seal breaks, letting
gas out. You grab the neutron bomb and run as fast as
you can to the bridge where you must place it in the
right spot.
#########
"""))
return 'the_bridge'
else:
print(dedent("""
The lock buzzes one last time and then you hear a
sickening melting sound as the mechanism is fused
together. You decide to sit there, and finally the
Gothons blow up the ship from their ship and you die.
"""))
return 'death'
i found similar things called context manager: enter, though i still dont understant what that mean as i am just a beginner.
please explain each of them, if different, differently.
thank you

How would I sent user to new "block" instead of continue same path?

response = ""
while response not in directions_window:
print("While crouched below the window you begin weighing you options")
print("You decide your only options are to listen in, knock on window, or wait")
response = input("Which are you doing?\nlisten/knock/wait")
if response == "listen":
print("You raise your head slightly to hear better\n")
print("You can ony make out a few words before the figure inside sees you\n")
print("Latin words can be heard screaming as it charges towards the window\n")
print("You try to run away, but slip and fall on your stomach.\n")
print("The figure catches up to you only to knock you unconsious.\n")
print("You wake up with scratches and marks around your wrist\n")
print("Taking in your surroundings, you notice you're at the entrance to the forest.\n")
print("You cut your losses, and leave the forest. Forever wondering who, or what, that was.\n")
quit()
I'm in the process of making a text-based adventure game. I want to send the user to a new "part" of the game if this option is selected instead of quit(). How would I skip to a new block? Also, I know I can write it without print every line, but I wrote this over time as ideas came to me. Will fix later
What you might be looking for is to use functions to branch your adventure's "path" into different "sections" which each direct the user to a different area (and can even loop the user back to an area they were before if desired), like this:
def adventure_listen():
print("you picked listen")
# ... more text
response = input("Which do you pick?\nA/B")
if response == "A":
do_something()
elif response == "B":
do_something_else()
def adventure_knock():
# code similar to above
def adventure_wait():
# code similar to above
print("message1")
response = input("Which are you doing?\nlisten/knock/wait")
if response == "listen":
adventure_listen()
elif response == "knock":
adventure_knock()
elif response == "wait":
adventure_wait()
"Jumping blocks" as you call it, is something that is used in assembler code. In high level languages (such as python), flow control structures are used (if else, for loops, while, etc).
For your specific case, if you decide to use flow control structures, and your story is long you will sooner than later get lost in your own code. Functions, as proposed by Cristopher Rybicki, would be a better way to go. For this you should either (a) first know your story in advance and/or (b) find a common structure or pattern in your story that allows you to "open" and "close" chapters.
(a) because it will help you structure better your code
(b) because if you cannot draw at first your story it will help you keep a structure and follow some patterns.
Execution of code is sequential, so you (cannot) should not "jump" from one function to another avoiding (or hoping to) the code after some "branch" line not to execute.
The more advanced approach (and the one I would recommend), is to go with classes and learn your way through inheritance. So your program could have Actions, Moves or whatever you choose it to have. Because you might now want to adventure_knock, and later it might be adventure_throw_the_door_down. They both (i) come from another step in the story, (ii) will have a feedback given to the user, and (iii) will have to go back to a point in the story.
in your main execution you can have a loop that initiates your stories, chapters?, and so on.
a pseudocode example would be:
Action:
abstract function start_action:
...
abstract function end_action:
...
abstract function give_feedback:
...
function ask_for_input:
input('What are you waiting for?')
Knock extends Action:
function start_action:
#specific implementation of knock...
...

When I try to start my code it says unindent does not match any outer indentation level

So i'm a brad new coder and took my first class today and I thought it was sooo fun so I decided to do it at home and on the learning course page one of the activities was making a game and it would help me step by step but then I came across a problem where when I stated the program a pop up would say unindent does not match any outer indentation level and so I looked for problems and then I copied the code from the course and it still doesn't work can somebody please help me thanks!
store = raw_input("\nDo you want to buy weapons? (yes or no)\n\n").lower()
if store == "yes":
print "\nWEAPON\t\tCOST\n"
for items in WEAPONS_STORE:
print items, "\t\t", WEAPONS_STORE[items], "\n"
print "\nYou have", gold, "gold\n\n"
weapon_purchase = raw_input("Which weapon would you like to buy?\n\n").lower()
game()
It looks like the indentation is just messed up a little bit, not sure if they went over it in your class but a : should tell you that the code that follows should be indented, anything involved in an if statement or for loop etc should be nested inside.
store = raw_input("\nDo you want to buy weapons? (yes or no)\n\n").lower()
if store == "yes":
print "\nWEAPON\t\tCOST\n"
for items in WEAPONS_STORE:
print items, "\t\t", WEAPONS_STORE[items], "\n"
print "\nYou have", gold, "gold\n\n"
weapon_purchase = raw_input("Which weapon would you like to buy?\n\n").lower()
game()
Note how everything under the for loop is all inline because it's nested inside the for loop, it helps to also visualize what code is going to run when you get to the foor loop.
Also I think you're using python 2, so if you're learning to code in python I'd recommend you switch over to python 3 now and start learning that instead.

Why is my program ending early?

I was recently able to get this to run thanks to all of your help, but I cant figure out why my program is ending here. Looking at it, if answer == 3: should just bring you to the next encounter, but my program is closing. Am I missing something?
# First Encounter (main program really)
def fi_en():
global pow, cun, per
print"""
It smells of damp vegetation, and the air is particularly thick. You can
hear some small animals in the distance. This was a nice place to sleep.
1. Stay close, find some cover, and wait for food to show up.
2. Explore the nearby marsh & find the nearest river, following it downstream.
3. Walk towards the large mysterious mountain in the distance.
"""
answer = int(raw_input(prompt))
if answer == 1:
cun_one = roll_3d6()
if cun_one <= cun - 2:
print"""Time passes as eventually you capture some varmints.
You feel slightly more roguish."""
cun = cun + 1
fi_en()
else:
print """Time passes and a group of slavers marches into right
where you are hiding in the woods. They locate you, capture you, and haul you
away for a lifetime of servitude in the main city.
Goodbye %s""" % name
elif answer == 2:
power = roll_3d6()
if power <= pow - 4:
print"""You trudge through the marshes until you eventually reach
a large river. Downstream from the river is a large temple covered in vines,
you walk towards it. You feel more powerful."""
pow = pow + 2
te_en()
else:
print """The vegetation here wraps itself around your legs making
it impossible to move. You will most likely die here in the vegetation.
Goodbye %s.""" % name
elif answer == 3:
cun_two = roll_3d6()
if cun_two <= cun:
print """You make your way towards the mountain and you encounter
a really large group of devil dogs guarding the entrance to the mountain."""
dd_en()
else:
print"You have gotten lost and ended up right where you started."
fi_en()
And my output is:
It smells of damp vegetation, and the air is particularly thick. You can
hear some small animals in the distance. This was a nice place to sleep.
1. Stay close, find some cover, and wait for food to show up.
2. Explore the nearby marsh & find the nearest river, following it downstream."
3. Walk towards the large mysterious mountain in the distance.
> 3
Raymond-Weisss-MacBook-Pro:lod Raylug$
It sounds to me like you're missing a really large group of devil dogs. Are you sure you want to fix this?
You haven't defined your globals anywhere. You have no "else" statement within condition three, so since cun_one is not less than/equal to your undefined cun variable, there is nothing else to do when answer == 3.
Deleted everything since you already got it working, just a comment.
You can use input('Prompt') since it automatically becomes an int, raw_input converts the input to a string, and then you are converting that string to an int, which is unnecessary.

Categories