Why did I get an error from this python code? - python

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.

Related

How to add SYLT tags to a mp3 file?

I want to add synchronized lyrics to songs in mp3 format. I am using the mutagen module for doing so. While i can add unsynchronized lyrics without any problem, I can't seem to get SYLT working. Here is the code
aud = ID3("C:\\Music\\Ghost.mp3")
aud.add(SYLT(encoding=Encoding.UTF8, format=2, type=1, text=sl))
aud.save()
Where "sl" is a list of the format as shown below
sl = [("lyric", millisecond), ("lyric", millisecond), ("lyric", millisecond)]
Can anyone please guide me with this problem? I would be extremely grateful if somebody can lead me in the right direction. Your explanation need not be in python. Please feel free to explain in any language you are comfortable with. Thank you in advance.
PS: Sorry for bad english. It isn't my native.
I got this figured out from another post and turns out it stores the placement in MilliSeconds (1 second = 1000 ms).
Here is a basic example of how:
from mutagen.id3 import ID3, SYLT, Encoding
filename = '/Users/JayRizzo/Music/Tom MacDonald - Angels (Explicit).mp3'
tag = ID3(filename)
sync_lrc = [
("It's not the liquor I'm addicted to, it's feeling brave", 1000),
("The feeling of not feeling the pain", 2000),
("I been on and off the bottle, I put oxys up my nostrils, believe me", 3000),
("You do anything to breathe before you suffocate", 4000),
("I couldn't stop it, staying clean was not an option", 5000),
("I was tryna be myself but being me was such a problem", 6000),
("I just wanted to be Thomas, but Thomas was at the bottom of a hole he dug", 7000),
("And getting comfortable inside a coffin, ay", 8000),
("He locked it and swallowed the key, he caught up, forgot all his dreams", 9000),
("Robbed outta calm and became embalmed in a toxic routine", 10000),
("Beer was the escape but I got stuck escaping", 11000),
("Whiskey was the blanket in the coldest basement", 12000),
("Way before the fame, I was wasted", 13000),
("Freezing, doing anything I could to keep the flame lit", 14000),
("To anyone going through the same shit", 15000),
("Heaven's got enough angels, you need to stay here", 16000),
("And I can't make you stay but sometimes going ain't a choice", 17000),
("And every choice you make is one that you didn't avoid", 18000),
("Crash the whip and ditch the car, burn a bridge, follow the stars", 19000),
("You'll find monsters in the dark but nothing's worth it till it's hard", 20000),
("Sometimes it's hard to see things clear (through your tears)", 21000),
("But anywhere is way better than here (fight your fears)", 22000),
("It's not the liquor I'm addicted to, it's feeling tough", 23000),
("When you get bullied half your life you feel weak like you just ain't enough", 24000),
("Then you have a couple drinks and you catch a buzz", 25000),
("And finally have the courage to defend yourself and throw a punch", 26000),
("And that adrenaline goes straight into your brain and blood", 27000),
("Addicted to the confidence, it's practically the greatest drug", 28000),
("Chasing dragons every night in all the latest clubs", 29000),
("What used to be your favorite thing somehow became a dangerous crutch", 30000),
("It was what it was", 31000),
("And that's the thing, it can happen to like any of us", 32000),
("I had great parents, tight friends, strong walls, nice threads", 33000),
("Good school, good looking, good grades, time spent", 34000),
("Being normal only lasted for a while", 35000),
("One bad choice sparked a downward spiral", 36000),
("I've spent half my life tryna climb outta that hole", 37000),
("Heaven's got angels, we need you at home", 38000),
("And I can't make you stay but sometimes going ain't a choice", 39000),
("And every choice you make is one that you didn't avoid", 40000),
("Crash the whip and ditch the car, burn a bridge, follow the stars", 41000),
("You'll find monsters in the dark but nothing's worth it till it's hard", 42000),
("Sometimes it's hard to see things clear (through your tears)", 43000),
("But anywhere is way better than here (fight your fears)", 44000),
("It ain't the liquor we're addicted to, it's everything else", 45000),
("The happiness we had but we forget how it felt", 46000),
("We been drinking with the devil 'cause we're going through hell", 47000),
("Pray to God for a little bit of help", 48000),
("Man, I been there, I did those things, I drank those drinks", 49000),
("I took those pills, I puked in sinks", 50000),
("And the truth ain't pretty, listen up, it's a tough one", 51000),
("You get saved by your angels or become one", 52000),
("Crash the whip and ditch the car, burn a bridge, follow the stars", 53000),
("You'll find monsters in the dark but nothing's worth it till it's hard", 54000),
("Sometimes it's hard to see things clear (through your tears)", 55000),
("But anywhere is way better than here (fight your fears)", 56000)
]
tag.setall("SYLT", [SYLT(encoding=Encoding.UTF8, lang='eng', format=2, type=1, text=sync_lrc)])
tag.save(v2_version=4)
print(tag.get('SYLT::eng'))
Returns the following:
# [1000ms]: It's not the liquor I'm addicted to, it's feeling brave
# [2000ms]: The feeling of not feeling the pain
# [3000ms]: I been on and off the bottle, I put oxys up my nostrils, believe me
# [4000ms]: You do anything to breathe before you suffocate
# [5000ms]: I couldn't stop it, staying clean was not an option
# [6000ms]: I was tryna be myself but being me was such a problem
# [7000ms]: I just wanted to be Thomas, but Thomas was at the bottom of a hole he dug
# [8000ms]: And getting comfortable inside a coffin, ay
# [9000ms]: He locked it and swallowed the key, he caught up, forgot all his dreams
# [10000ms]: Robbed outta calm and became embalmed in a toxic routine
# [11000ms]: Beer was the escape but I got stuck escaping
# [12000ms]: Whiskey was the blanket in the coldest basement
# [13000ms]: Way before the fame, I was wasted
# [14000ms]: Freezing, doing anything I could to keep the flame lit
# [15000ms]: To anyone going through the same shit
# [16000ms]: Heaven's got enough angels, you need to stay here
# [17000ms]: And I can't make you stay but sometimes going ain't a choice
# [18000ms]: And every choice you make is one that you didn't avoid
# [19000ms]: Crash the whip and ditch the car, burn a bridge, follow the stars
# [20000ms]: You'll find monsters in the dark but nothing's worth it till it's hard
# [21000ms]: Sometimes it's hard to see things clear (through your tears)
# [22000ms]: But anywhere is way better than here (fight your fears)
# [23000ms]: It's not the liquor I'm addicted to, it's feeling tough
# [24000ms]: When you get bullied half your life you feel weak like you just ain't enough
# [25000ms]: Then you have a couple drinks and you catch a buzz
# [26000ms]: And finally have the courage to defend yourself and throw a punch
# [27000ms]: And that adrenaline goes straight into your brain and blood
# [28000ms]: Addicted to the confidence, it's practically the greatest drug
# [29000ms]: Chasing dragons every night in all the latest clubs
# [30000ms]: What used to be your favorite thing somehow became a dangerous crutch
# [31000ms]: It was what it was
# [32000ms]: And that's the thing, it can happen to like any of us
# [33000ms]: I had great parents, tight friends, strong walls, nice threads
# [34000ms]: Good school, good looking, good grades, time spent
# [35000ms]: Being normal only lasted for a while
# [36000ms]: One bad choice sparked a downward spiral
# [37000ms]: I've spent half my life tryna climb outta that hole
# [38000ms]: Heaven's got angels, we need you at home
# [39000ms]: And I can't make you stay but sometimes going ain't a choice
# [40000ms]: And every choice you make is one that you didn't avoid
# [41000ms]: Crash the whip and ditch the car, burn a bridge, follow the stars
# [42000ms]: You'll find monsters in the dark but nothing's worth it till it's hard
# [43000ms]: Sometimes it's hard to see things clear (through your tears)
# [44000ms]: But anywhere is way better than here (fight your fears)
# [45000ms]: It ain't the liquor we're addicted to, it's everything else
# [46000ms]: The happiness we had but we forget how it felt
# [47000ms]: We been drinking with the devil 'cause we're going through hell
# [48000ms]: Pray to God for a little bit of help
# [49000ms]: Man, I been there, I did those things, I drank those drinks
# [50000ms]: I took those pills, I puked in sinks
# [51000ms]: And the truth ain't pretty, listen up, it's a tough one
# [52000ms]: You get saved by your angels or become one
# [53000ms]: Crash the whip and ditch the car, burn a bridge, follow the stars
# [54000ms]: You'll find monsters in the dark but nothing's worth it till it's hard
# [55000ms]: Sometimes it's hard to see things clear (through your tears)
# [56000ms]: But anywhere is way better than here (fight your fears)
Doesn't seem to show up in iTunes, QuickTime, or VLC that I can tell so far.

NameError: name 'home' is not defined

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.

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

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.

Making a loop based on user input, then saving the result for a MUD in Python

I'm trying to do two things:
Make a loop in python that provides the user a prompt with 4 possible options; entering "1", "2", "3", or anything else. If the user selects 1,2,or 3 they are presented with text. If a user enters anything else they are presented with text, and the prompt all over again. This repeats until they enter 1,2,or 3.
I want to then take that input from the user to use outside of that loop and continue through the game.
My solution thus far:
Before I post my code I'll describe it, I've basically placed all the code I want in the loop within a function with no arguments. I then call that function within the else statement.
What the code is doing:
The code is looping the way I want it to, but I don't know how to "break out" of the loop to continue based off of what the user entered. I know it has to be a return, but I guess I don't know where to place it.
What I've tried:
post calling the function I entered:
if blackdoor(decision) == "1":
And continue from there, but that isn't working.
The Code:
def blackdoor():
print """After having recently died you awake to find yourself standing in an all white room with a black door that seems to go into the sky forever. What do you do?\n1.Touch the door.\n2.Shout at the door.\n3.Stare at the door."""
decision = raw_input("> ")
if decision == "1":
print "You touch the door. It is as cold as ice. You can feel a vibration pulsing from the door through your body.\n"
elif decision == "2":
print "You shout 'Hello?! Is anybody there?!' at the door. But nothing responds. Your voice echoes off in the distance.\n"
elif decision == "3":
print "You stare at the door intensely. You envision it opening when all of a sudden you get the feeling of something staring back at you.\n"
else:
print "You don't follow instructions very well, do you?\n"
blackdoor()
return decision
blackdoor()
How can I pull the input for decision out to use it as a condition to keep the game going?
You're recursively calling blackdoor() but you are not returning the result from the call. You need to return blackdoor() to get the result back to the caller.
A simple change should do it;
def blackdoor():
print """After having recently died you awake to find yourself standing in an all white room with a black door that seems to go into the sky forever. What do you do?\n1.Touch the door.\n2.Shout at the door.\n3.Stare at the door."""
decision = raw_input("> ")
if decision == "1":
print "You touch the door. It is as cold as ice. You can feel a vibration pulsing from the door through your body.\n"
elif decision == "2":
print "You shout 'Hello?! Is anybody there?!' at the door. But nothing responds. Your voice echoes off in the distance.\n"
elif decision == "3":
print "You stare at the door intensely. You envision it opening when all of a sudden you get the feeling of something staring back at you.\n"
else:
print "You don't follow instructions very well, do you?\n"
return blackdoor()
return decision
According to my understanding to your problem, your code seems fine, however, it'll probably run out of stack due to numerous recursion, if you haven't set the recursion limit to a large number.
I'd go for an iterative solution, as follows:
def blackdoor():
end_condition = False
while not end_condition:
end_condition = True
print """After having recently died you awake to find yourself standing in an all white room with a black door that seems to go into the sky forever. What do you do?\n1.Touch the door.\n2.Shout at the door.\n3.Stare at the door."""
decision = raw_input("> ")
if decision == "1":
print "You touch the door. It is as cold as ice. You can feel a vibration pulsing from the door through your body.\n"
elif decision == "2":
print "You shout 'Hello?! Is anybody there?!' at the door. But nothing responds. Your voice echoes off in the distance.\n"
elif decision == "3":
print "You stare at the door intensely. You envision it opening when all of a sudden you get the feeling of something staring back at you.\n"
else:
print "You don't follow instructions very well, do you?\n"
end_condition = False
return decision
decision = blackdoor()
I am assuming that you are having many of these decision points throughout your game and you will get lost trying to embed them in functions. If this is the case, then you should explore using a simple Finite State Machine (FSM).
A list of FSM implementations exists on PythonWiki.
Using an FSM seems overkill if you have only one or two actions, but you will find it needlessly difficult to program even a simple adventure game without the help of one.
Update I found a useful answer on Python and FSM for future reference.

Categories