Python function (ifs and inputs) stops partway through, no error - python

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.')

Related

Capitals game with dictionary python

I am trying to a make a simple game. I will supply of a dictionary of states and capitals and a list of states. Using loops and conditionals, I will ask the user if they want to learn some capitals and supply the list of states. The state gets removed from the list and the user should be prompted again if they want to play, repeatedly until the list is empty. With my code right now the loop piece works, if keeps asking if they want to play and as long as the user keeps saying yes my code works running till the list is empty and the loop. But when I try to add a layer for if the player says no and break the loop its not doing anything. Thanks in advance for help!!
states3 = ["NH", "MA", "MS", "SC", "HI"]
print("Let's test my geography skills!")
def state3(states3):
state_caps = {"NH": "Concord", "HI": "Honolulu", "SC":"Columbia", "MS": "Jackson", "MA":"Boston"}
play = input("Would you like to learn some capitals:")
while play == "Yes" or "yes":
if play == "Yes" or "yes":
print ("The states I know the captials of are:", states3)
yourstate = input("What state do you want to know the capital of: ")
print("The capital of", yourstate, "is", state_caps.get(yourstate, "That is not a vaild choice"), "!")
states3.remove(yourstate)
play = input("Would you like to learn some capitals:")
if len(states3) == 0:
print ("That's it! That's the end of geography skills")
break
state3(states3)
while play == "Yes" or play == "yes":
if play == "Yes" or play == "yes":
print ("The states I know the captials of..")
.....
....
elif play == "no" or "No":
break
Checking for yes/no is problematic. For example, "YES" is not covered in the above code, yet seems a reasonable response. To distinguish between the two choices, do we need to look at the entire word or only the first letter? (string "slicing")
Such reduces the set of applicable responses to the set: y, Y, n, N. Now, if we apply the string.lower() or string.upper() method*, we are down to two choices.
However, consider this even more closely. Is there really only one user-response that interests us? That the game should continue. Thus, any response other than 'yes' could be considered to mean stop looping!
Another question: once the while-condition has been satisfied and the loop starts to run, is it possible for the first if-condition to be anything other than True? Could the latter be removed then?
Instead of merely adding a "layer", let's review the entire game. How's this for a spec[ification]: repeatedly invite the user to choose a state, and then present its capital.
How do we define "repeatedly", or more precisely, how do we end the looping? There are two answers to that question: either all the states have been covered, and/or the user loses interest (the new "layer"). What happens if we use (both of) these to control the while-loop? (NB reversing the logical-statement) Loop if there are states to review and the user consents. Thus, can the last if-condition move 'up' into the while-condition...
Because you are evidently (enjoying) teaching yourself Python, I have left the writing of actual code to your learning experience, but herewith a few items which may increase your satisfaction:-
in the same way that the 'heading print()' is outside the loop, consider where the farewell should be located...
A list with contents is considered True, whereas an empty/emptied list is considered False. Very handy! Thus, you can ask if states3 (ie without the len()).
also consider the upper()/lower() 'trick' when accepting the state's abbreviation-input.

Python try except input

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")

How to define functions in python to repeat a prompt? (Beginner)

Im new to python so I decided to help myself learn by creating a basic game using python 3! My problem occurs whenever I try to use "def". When I try to run this program it skips all user input entirely because of the def. The goal of using a function in this case would be to return the player to the where it presents the two doors. Maybe its an issue related to indentation? If anyone could give it a shot and see if you can spot the error your help would be greatly appreciated! :D
def sec1 ():
print ("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')
if room1 == "L":
print ("********")
print ("Good choice",name)
elif room1 == "R":
print ("********")
print ("Uh oh. Two guards are in this room. This seems dangerous.")
print ("Do you want to retreat or coninue?")
roomr = input('Type R or C and hit enter.')
if roomr == "R":
print ("Good choice!")
sec1()
You have an indentation problem. Indentation matters in Python. According to the PEP8 styling guideline it is recommended to use 4 spaces instead of tabs for indentation. Also you are missing the name variable.
Below is a quick fix:
def sec1 ():
print("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')
name = "Player Name"
if room1 == "L":
print("********")
print("Good choice", name)
elif room1 == "R":
print("********")
print("Uh oh. Two guards are in this room. This seems dangerous.")
print("Do you want to retreat or coninue?")
roomr = input('Type R or C and hit enter.')
if roomr == "R":
print("Good choice!")
sec1()
sec1()
Why we have sec1() at then end?
Functions are like machines. It does nothing by it's own. Somebody has to operate it. sec1() (notice the parenthesis) at the end is sending a signal to start executing the function sec1 defined at the top.
I think the best way to learn is to put break points and use the debugger to learn which way the program flows.
Run the program in a debug mode and click on the icons to step through, step over etc. It sounds complicated but it is very easy and saves you a lot of time once you know how to do this feature.
Mathematical Functions
Maybe it is a bit off topic to mention Mathematical Functions here but I think, it's completely worth it. Functions in programming languages are heavily inspired by Mathematical Functions, however, in most of the programming languages these days (except functional programming languages like Haskell, F# etc) the concepts of the original Mathematical Functions are quite deviated over the year.
In Mathematics, the output of a function purely depends upon it's input and does not modify the values outside the function, however, in most of the programming languages this is not always the case and sometimes it can be a source of run time errors.
Tips
As you are a beginner, I highly recommend to use a proper IDE (Integrated Development Environment) if you haven't already. PyCharm has a free community version. IDEs come with a PEP8 style checker, debugger, profiler etc and help you to learn Python much more easily.
def sec1 ():
print ("You have two doors in front of you. Do you choose the door on the left or right?")
room1 = input('Type L or R and hit Enter.')
the function body should be indented
In Python, indentation is very important. Here's an example of your code with proper indentation (And a couple of liberties take on my part):
def sec1 ():
print ("You have two doors in front of you. Do you choose the door on the left or right?")
name = input('Enter your name.')
room1 = input('Type L or R and hit Enter.')
if room1 == "L":
print ("********")
print ("Good choice",name)
elif room1 == "R":
print ("********")
print ("Uh oh. Two guards are in this room. This seems dangerous.")
print ("Do you want to retreat or coninue?")
roomr = input('Type R or C and hit enter.')
if roomr == "R":
print ("Good choice!")
elif roomr == "C":
print ("Run!")
sec1()

User inputted script

I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")

Error in trying to run Python code online

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

Categories

Resources