How to allow a user to quit a program - python

I am making a text adventure game and I am trying to allow the user to quit the game using q. I don't know what to input, here's my code.
print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi deset.")
print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")
print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi deset.")
print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")
done = False
while done == False:
print("Print the letter only.")
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
first_question = input("What do you want to do? ")
if first_question.lower() == "q":
done = True
if done == True:
quit
The lines are all indented properly in the code (the website makes it weird when copy pasting). Any help is appreciated.

Your program is nearly fine as is, and in fact it runs just fine in python3. The problem is that in python2, input will actually evaluate your input. In order to support python2, use raw_input.

print ("Welcome to Camel!")
print ("You have stolen a camel to make your way across the great Mobi deset.")
print ("The natives want their camel back and are chasing you down! Survive your desert trek and out run the natives.")
done = False
while done == False:
print("Print the letter only.")
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
first_question = input("What do you want to do? ")
if first_question.lower() == "q":
done = True
if done == True:
break
Now, when you input 'Q' or 'q' program will quit.
It's about tabulation. Is that what you asked?

Related

Python if else exit

This a chat-respond program and the problem I am currently facing is that I try to make it exit if the input answer does not match one of my answers, but since all the answers of the three of the questions were put together as Response so even the right for the question it randomly chose was inputted, python still thinks it is not right because it does not meet the other two and then it will exit. Please tell me how can I take a different approach on this programs.Thanks for the help1
import random
x=input("What is your name? ")
def main():
def feeling():
return input("How are you feeling right now " +str(x)+"? ")
def homesick():
return input("Do you miss your home? ")
def miss():
return input("Who do you miss?")
prompts = [feeling,homesick,miss]
response = random.choice(prompts)()
if response==("tired"):
Tired=['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(Tired))
else:
exit()
if response==("yes"):
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
else:
exit()
if response==("my mom"):
print("Mom will be in town soon")
else:
exit()
main()
main()
Python provides nice flow control structure for this using elif. See the official documentation here: https://docs.python.org/3/tutorial/controlflow.html
So the idea is that all statements are evaluated as a unit.
if response==("tired"):
Tired=['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(Tired))
elif response==("yes"):
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
elif response==("my mom"):
print("Mom will be in town soon")
else:
exit()
Now the statements will run until one is True. If all are false, it will default to the else statement.
Instead of
if
else: exit
if
else: exit
if
else: exit
do this:
if
elif:
elif:
else: exit
because otherwise, if the 1st ifis false, you will exit and not check the others.
import random
name = input("What is your name? ")
def main():
def feeling():
response = input("How are you feeling right now {name}?".format(name=name))
if response == "tired":
tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(tired))
else:
exit()
def homesick():
response = input("Do you miss your home? ")
if response == "yes":
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
else:
exit()
def miss():
response = input("Who do you miss?")
if response == "my mom":
print("Mom will be in town soon")
else:
exit()
prompts = [feeling, homesick, miss]
random.choice(prompts)()
main()
You should group the prompts and the expected answers and replies by the chatbot, e.g. as tuples in the form (prompt, expected_answer, [some, possible, replies])
feeling = ("How are you feeling right now " +str(x)+"? ", "tired",
['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.'])
miss = ...
homesick = ...
prompts = [feeling,homesick,miss]
choice = random.choice(prompts)()
prompt, ans, replies
resp = input(promp)
if resp == ans:
print(random.choice(replies))
else:
exit()
This will also make it easier to extend your chatbot with more question/answer pairs or also to provide different chatbot replies to different user-answers.
Don't understand your code, but you can do something like:
if response!=("tired"):
exit()
return
Tired=['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(Tired))
if response!=("yes"):
exit()
return
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
[...]

Python 2.7.13 multiline print

This is a begginer question. I am writing a text game and have some problems.
code:
def river():
print "You are traveling through deciduous forest."
print "There is nothing going on, except a few squirrels and a hedge."
print "Squirrels are fighting over nuts and a hedge is getting fat eating an apple."
print "Then you see a wide, deep river. The stream is very strong."
print "What are you going to do next?"
print "1. Try to swim the river."
print "2. Watch the squirrels and hedge."
print "3. Turn back."
while True:
choice = raw_input("> ")
if choice == "1" or choice == "swim":
print """You are doing well when in the middle of a river
something begins to bite you near legs. The bitting gets stronger
and you soon realize that piranhas are tearing chunks of your meat
off. Soon there is nothing left of you that the bones. The piranhas
seems satisfied, since they got a free meal."""
dead()
if choice == "2" or choice == "watch":
print "You keep watching animals and are becoming more and more thirsty and hungry."
if choice == "3" or choice == "turn back" or choice == "turn":
start_rewind()
start()
I do not like these print statements. If I use multiline print, like under choice 1, the indentation does not look nice. It is in the same row as def river(). Is this a normal or a bad style? If i indent the text under choice I so it is in the same row as choice 1,.. then it does not look good when i start the script in command promt. How could i solve that?
Thanks
I would write something like this:
print ("You are traveling through deciduous forest.\n"
"There is nothing going on, except a few squirrels and a hedge.\n"
"Squirrels are fighting over nuts and a hedge is getting fat eating an apple.\n"
"Then you see a wide, deep river. The stream is very strong.")
The parentheses above implicitly continue the string. See the Python docs. For example:
print ("foo "
"bar")
and print "foo bar"
will give the same output. Note the space after "foo".
Note that there is a space between the print statement and the first parenthesis. In python3, where print is a function, there should be no space there.
try this:
print("""
You are traveling through deciduous forest.
There is nothing going on, except a few squirrels and a hedge.
Squirrels are fighting over nuts and a hedge is getting fat eating an apple.
Then you see a wide, deep river. The stream is very strong.
What are you going to do next?
1. Try to swim the river.
2. Watch the squirrels and hedge.
3. Turn back.
""")

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

When is an appropriate time to use and modify global variables?

I'd like to start out that I'm new to programming. I've never taken any classes on it. I just decided it sounded interesting and try it.
Anyway, I've been reading the "Learn Python the Hard Way" online and have gotten to exercise 36. This exercise involves making my own text-based game. Now, for the question. When is an appropriate time to use and modify global variables? I just started my adventure and want to add things that the player has to do before other events happen, such as pull a lever in a different room before the gate in the first room opens. And if the player wishes to return to the first room later on, the gate and lever still be triggered.
Here's the code so far. Mind you it's not fleshed out. Just wanted to know if it worked.
print "You are a lone adventurer with the bounty to clear out the crypt."
print "You come with nothing but your sword and a compass."
print "You enter the crypt."
print "To the north you have a gated portaculas and rooms to the west and east."
print "What do you do?"
gate = False
lever = False
def entrance():
global gate
while True:
choice = raw_input('> ')
if choice == 'west':
guard_shack()
elif choice == 'east':
lever_rm()
elif choice == 'north' and gate == False:
print "The gate is still closed and locked."
entrance()
elif choice == 'north' and gate == True:
fountain_rm()
else:
entrance(gate)
def lever_rm():
global lever
global gate
print "You enter the room."
print "What do you do"
while True:
choice = raw_input('> ')
if 'search' in choice:
print "You look around the room and notice a lever on the opposite wall."
elif "pull lever" in choice:
print "You pull the lever."
lever = True
gate = True
elif choice == 'west':
entrance()
else:
print '> '
def fountain_rm():
print "you're in the lever room!"
entrance()
Unfortunately, many tutorials (and professors) teach bad code in the name of simplicity (and they usually never bother to teach the right way later). In this case, the problem is exacerbated by the fact that you are directly executing top-level code instead of putting it in a main function and using if __name__ == '__main__': main() at the end.
You should try to avoid all global state that can be mutated. It's okay to declare constants, or even lists/sets/dicts that you're not allowed to change. But everything else should be either passed as a function parameter, or stored as an attribute on self of some class.
If nothing else, think about how you would write unit tests in the presence of mutable global variables (hint: it's impossible).
To transform code like you've given, indent everything and add a heading class CryptGame:, add self as the first argument to every function, and replace all variables declared global foo with self.foo.

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