I have done little text game and and all info of this try expect thing is some professional language what i do not understand. I am just started to studying Python so this is not easy for me.
I have lot of inputs in my game, example answer yes or no. If player writes something else, game stop working and error comes. I must do something with this. How can i use try except? Can you tell me it simply.
Piece of my game:
print('Hello you! Welcome to the Ghetto! What is first name?')
first_name=input()
print('Hello',first_name+'! Now tell me your last name also!')
last_name=input()
print('You are my bailout',first_name,last_name+'! I really need your help here. I lost my wallet last night when i was drunk.')
print('The problem is i dont wanna go alone there to get it back cause this place is so dangerous. Can you help me? Answer "YES" or "NO"')
lista1 = ['yes','y']
lista2 = ['no','n']
answer1=input().lower()
if answer1 in lista2:
print('If you are not interested to help me with this problem, go away from here and never come back!!')
print('*** Game end ***')
if answer1 in lista1:
print('That is awesome man! You can see that big house huh? There is three apartments and my wallet is in one of them.')
print('But you have to be god damn careful there you know, these areas is not safe to move especially you are alone. So lets go my friend')
Is there any chance to get error name input? Is there some letter or character what Python does not understand?
And if you answer something else than yes or no, how can i tell to python with try except to give question again? I hope you understand. And sorry for so long post.
If something is causing an error, it's after the code you've shown... Using input() alone should have no reason to try-except it because anything typed is always accepted as a string.
If you want to repeat input, you'll need a loop
while True:
answer1=input().lower()
if answer1 in ["yes", "y"]:
print("ok")
break
elif answer1 in ["no", "n"]:
print("end")
break
else:
print("try again")
Related
answer = int(raw_input("How many hours a day do you play computer games? "))
if answer < 2:
print "That seems a fairly healthy balance. Well done!"
elif:
print "You’re probably good enough by now with all that practice."
print "PS5 are better than any game console"
Errors keep popping up that says "There's an error in your program: expected an indented block"
When you code in python you have to indent the code otherwise you'll get the errors like you got. Other programming languages use ; such as php or java in order to differentiate the lines to execute, but in python we have the indentations. Besides, you can't use elif statement without some condition and if you don't have it you have to use else instead.
answer = int(raw_input("How many hours a day do you play computer games? "))
if answer < 2:
print "That seems a fairly healthy balance. Well done!"
else: # instead of elif, which requires a condition
print "You’re probably good enough by now with all that practice."
print "PS5 are better than any game console"
I'm using a series of inputs and if statements to create a text game/ choose your own adventure where input decides what happens next within a function.
I was testing part of a function, and there should be a total of four strings that print with an input prompt, but after the first two it just moves onto the cell after the function. No error message. I'm using Jupyter Notebook with the latest version of Python. Any help appreciated in making the full function run. (Please ignore the goofy text, sorry for errors this is my first question)
start = input('Welcome to Witness Protection, enter HELP if you need help')
def helper():
if start == 'HELP':
answer= input('')
if answer == 'PICK':
answer= input('')
elif answer == 'WALK':
print('')
if answer == 'TRY':
answer= input('')
elif answer == 'WALK AWAY':
print('')
if answer == 'IN':
answer = input('')
elif answer == 'PUT':
print('')
if answer == 'ON':
answer = input('')
elif answer == 'BACK':
print('')
if start == 'HELP':
helper()
I have checked that I am using the right input, changed elifs to ifs nothing else came to mind that could be the issue any help appreciated
It looks like you want another input instead of a print after elif answer == 'WALK':. When you hit if answer == 'TRY' you haven't given them a chance to change the value of answer yet.
Also, you probably want a different kind of structure for your code. When you use if, only the code that is indented after the if and before the elif or else at the same level of indentation will get run. This means that if someone answers PICK, then none of the code below WALK will get run because the elif answer == 'WALK' section never gets entered. You may want to try a while loop with code that checks different variables to determine what to print at each loop (like what room they are in, what items they have, etc.), and then gets a new input from the user at the end of each loop.
Seems you have some mismatch with the nested if's.
you should indent the if's according to the flow of the questions, something like that:
def helper():
if start == 'HELP':
answer= input('Woah. As you are walking to the FBI office, you see a glistening penny on the floor. Something about it looks strange. What do you do? Enter PICK to pick it up or WALK to keep walking')
if answer == 'PICK':
answer= input('You reach down and grasp the penny, and try to pull it. It doesn’t move. Enter TRY to try again or WALK AWAY to walk away')
if answer == 'WALK AWAY':
print('You keep walking until you reach the FBI office. You make your way to the office of your agent, and sit down to wait for them.')
elif answer == 'TRY':
answer= input('The penny clicks out of place and slides along a track between the paving slabs. One of the slabs slides open. Enter IN to climb in or PUT to put the penny back where it was')
if answer == 'IN':
answer = input('A few metres down, you hit the floor, and see the opening above you close up. You find yourself in an ice cavern, surrounded by the bodies of slain ice dwarfs. Enter ON to walk on or BACK to back')
if answer == 'ON':
answer = input('You enter the realm of the evil wizard. He tells you he is thinking of giving up evil and asks you if you would like to join him in taking over the world and establishing a utopia. Enter YES for \'Of course I will join you, let’s do this!\' Enter THINK for \'That’s a big decision, I need some time to think about it\' Enter NO for \'Woah, sorry buddy, I’m just lost, I’m gonna have to bounce\'')
elif answer == 'BACK':
print('You scramble back to the surface and try to forget what just happened. You continue towards FBI HQ, and wait for your agent at their desk')
elif answer == 'PUT':
print('You move the penny back to where it was, and the slab slides back into place. You continue your walk towards the FBI offices, and wait for your agent in front of their desk')
elif answer == 'WALK':
print('You enter the building and make your way to the office of your agent, and sit down to wait for them.')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
Question1 = input("We will start off simple, what is your name?")
if len(Question1) > 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers.
Question2 = input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1)
if Question2.lower() in m: #checks if the user input is in the variable m
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
elif Question2.lower() in w: # checks if the user input is in the variable w
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
else: #if neither of the statements are true (incorrect answer)
print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")
else:
print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name)
Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?")
In order to get the right answer, I will first tell you what happens when I run it:
There are several scenarios but I will walk you through 2. When I run the program I am first asked what my name is, I can enter anything here that is alphabetic, then it asks me if I like men or woman, weird I know but it's a project I am working on, if I were to say 'men' or 'women' the program runs perfectly, but if I were to enter say... 'dogs' it would follow the else statement print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!") but then it continues the code and goes to the last line shown above "Now I know your name and what gender attract you...... blah blah". What I am trying to do is have it restart the script if you were to enter anything other than 'men' or 'women'.
I was told that a while statement would work, but I would need an explanation as to why and how... I'm new to Python in a sense.
That's what loops are for.
while True:
# your input and all that here
if answer == "man" or answer == "woman":
# do what you want if the answer is correct
break # this is important, as it breaks the infinite `while True` loop
else:
# do whatever you want to do here :)
continue
If you want the script to repeat indefinitely, you can simply wrap everything in a while loop like so:
while True:
# Do yo your logic here.
# Break out when a condition is met.
If you want to be more savvy with it you can use a method and have the method call itself over and over until it's done.
def ask_questions():
# Do your logic here
if INPUT_NOT_VALID:
ask_questions()
else:
# Continue on.
Also, search on this site for you text because I've seen about five or six questions all involving this programming scenario which means it has to be a common problem from a programming class (one I'm assuming you are in). If that's the case discuss with classmates and try to stimulate each other to find the solution instead of just posting online for an answer.
The second rule for If-Statements here, which has me confused states that:
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Here's the code from the last exercise:
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
choice = raw_input("> ")
if choice == ‘left’:
bear_room()
else:
dead(‘You stumble around the room until you starve.’)
Is it essentially saying that you must successfully terminate the program if a condition is not met?
Yes, the idea is:
import sys
def die(msg):
print msg
sys.exit(1)
if condition:
# do stuff
else:
die('This cannot happen!')
You could also use an assert instead, or raise an exception, or anything else that would fail catastrophically. This helps you validate at runtime that the clause you didn't expect to execute, really didn't run.
IMHO you shouldn't get too hung up on how this die is done, exactly. The important point the referred text tries to make is that when you're sure some condition is true, you might as well assert it forcefully so that you can catch runtime bugs.
The guide is trying to show you that you can see the choice that a user gives when it's something that you don't check for in your if statement. If your else looks like:
else:
dead(choice)
You will be able to see what the user input that you didn't expect.
The problem is that the syntax only allows for "Left", when the prompt allows entry of anything. In other words, if I enter "Bob", I will starve. I should be trapping for anything that isn't appropriate and "die"ing at that point (or helping the user make an appropriate decision).
This is an attempt at teaching error handling and die. You would rewrite it such that you allow accurate entry or die (no exit). If you don't choose left, there is no other choice even though the prompt states there are two choices.
If you truly expect only 'left' to be added, a better way of checking for unexpeted input would be
if choice != ‘left’:
dead(‘You stumble around the room until you starve.’)
bear_room()
That way you still validate that the input is what you expected, but it saves indentation and space for the main logic.
I was trying to make a simple Python game for some struggling math students at my high school, however our computers are not allowed to run Python due to security issues. So I decided to give them the code and have them run it online, but every site I go to says that the code has an EOFerror and an indention error. I have ran the code a dozen times in Powershell and everything was fine. It is always focused on my raw_input() statements. Can someone please tell me what is going on and any solution would by greatly appreciated. This is just the Intro so there is no math, just something to set the story.
def cell():
print """
"Welcome roomie!"
You wake up to find yourself in a jail cell
"You have been sleeping since the guards threw you in here.
They must have hit you pretty hard, ha ha ha."
You look around
finally your eyes focus on the source of the voice
across the room was a man
he looked as if he was nothing but skin and bone.
Then you noticed the scar... it ran down his arm
It was an open wound,
but wasn't bleeding just black.
The man followed your eyes
"Ah so you noticed, yes I am forsaken."
1) Remain quit
2) Ask about the forsaken
3) Quickly check your body for scars
4) Scream
Please choose one:"""
answer = raw_input("> ")
if answer == "1":
print '"You don\'t talk much"'
cell_name()
elif answer == "2":
print '"Not sure, all I know is if you have a scar like this"'
print '"They throw you in jail."'
cell_name()
elif answer == "3":
print '"Don\'t worry I already checked you."'
cell_name()
elif answer == "4":
print '"Shut up! Jeez pansy."'
cell_name()
else:
print "Pick one of the numbers"
cell()
def cell_name():
print "Well whats your name kid."
name = raw_input("> ")
print "Alright, nice to meet ya %r" % name
print "Well my name is Esman."
destroyed_cell()
def destroyed_cell():
print """
All of a sudden you hear a rumble...
rumble...
rumble...
silence.
"What do you suppose that wa..."
Crash!
Huge parts of the ceiling had fallen down
one had nearly crushed you
instead it had landed perfectly right next to you
the force was enough to break through the floor
you turn to check on Esman
But a huge piece of the ceiling had landed on him
1) Stare in bewilderment
2) try and help him
3) he's a dead man, leave him
Please choose one:"""
answer = raw_input("> ")
if answer == "1":
print "Hurry kid get out of here."
elif answer == "2":
print "It's no use you have to save yourself"
elif answer == "3":
print "Run!"
else:
print "Pick one of the numbers"
cell()
I tried your code at http://repl.it/languages/Python and it works