Prompting for numbers instead of letters Python 2.7.x [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
So I have a few questions about the code below.
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
gold_greedy = "50"
if next > gold_greedy:
dead("You are too greedy to live, die.")
elif next < gold_greedy:
dead("You are fair and therefore you win.")
else:
dead("Man, you BARELY made it")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "Take honey":
dead("The bear looks at you then slaps you.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "Taunt Bear" and bear_moved:
dead("The bear gets pissed off and chews your legs off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
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?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
When I get to the gold_room, why when I take any letters instead of numbers it gives me "You are too greedy to live, die. Good job!", shouldn't it give me an error message? or give me the "Man, you BARELY made it" message?
If the user types anything other than whole numbers, how can I prompt him to type a number?

If you type:
print type(next)
you can see the next variable is of type str. You have to convert it to an integer by using the int() function:
next = int(raw_input("> "))

Related

Does Python basically execute code from the top to the bottom? [duplicate]

I am currently learning how to code in Python and I have stumbled across this code in the book I am learning from (Learning Python the Hard Way [I don't recommend to anyone that JUST started coding btw]).
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "Take honey":
dead("The bear looks at you then slaps you.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "Taunt Bear" and bear_moved:
dead("The bear gets pissed off and chews your legs off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
next = raw_input("> ")
if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
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?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
I have always thought that Python reads codes from left to right and from up to down but in the code above, it starts running the program from
def start():
print "You are in a dark room."
I don't understand what is making Python do this, if anyone can clear this up for me it would be of great help. Thanks a lot in advance.
I have always thought that Python reads codes from left to right and from up to down
Reads, yes, top-down, left to right.
The def gold_room(): only defines function gold_room, it does not run it. Without gold_room() somewhere below, it will never be executed. Same with start().

If returning wrong answer (python)

I am working through the "Learn python the hardway." I apologize if this is a duplicate but I really can't figure out what I'm doing wrong. When I enter anything less than 50 it tells me to try again, and upon the second time calls a string in another function. If I enter something greater than 50 same thing on the second entry it calls another string in another function. it will call from green_dragon() and print "Both dragons cook you alive and eat you." Thank you for any insight you are able to offer. I apologize for the simplicity, lol. Had to make my own "game and I'm not that creative yet, lol.
def gold_room():
print "You have entered a large room filled with gold."
print "How many pieces of this gold are you going to try and take?"
choice = raw_input("> ")
how_much = int(choice)
too_much = False
while True:
if how_much <= 50 and too_much:
print "Nice! you're not too greedy!"
print "Enjoy the gold you lucky S.O.B!"
exit("Bye!")
elif how_much > 50 and not too_much:
print "You greedy MFKR!"
print "Angered by your greed,"
print "the dragons roar and scare you into taking less."
else:
print "Try again!"
return how_much
def green_dragon():
print "You approach the green dragon."
print "It looks at you warily."
print "What do you do?"
wrong_ans = False
while True:
choice = raw_input("> ")
if choice == "yell at dragon" and wrong_ans:
dead("The Green Dragon incinerates you with it's fire breath!")
elif choice == "approach slowly" and not wrong_ans:
print "It shows you its chained collar."
elif choice == "remove collar"and not wrong_ans:
print "The dragon thanks you by showing you into a new room."
gold_room()
else:
print "Both dragons cook you alive and eat you."
exit()
too_much = False
if <= 50 and too_much
if too_much is set to False, why do you expect the if expression to evaluate to true ? It will never go inside the if.
Move user input inside loop as well.
EDIT:
To stop your while loop:
too_much = True
while too_much:
choice = raw_input("> ")
how_much = int(choice)
if how_much <= 50:
print "Nice! you're not too greedy!"
print "Enjoy the gold you lucky S.O.B!"
too_much = False
else:
print "You greedy MFKR!"
print "Angered by your greed,"
print "the dragons roar and scare you into taking less."

How do I move to different parts of code in this game/story

After the initial question of how much do you take, it works fine. If you type 0 you die, 5 million it says nice take. After it says nice take, it exits the program and forgets the rest of the code.
How do I get python to load the next part of the code and run it.
from sys import exit
def bank_vault():
print "This room is full of money up to 5 million dollars. How much do you take?"
choice = raw_input("> ")
if "0" in choice:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
how_much = int(choice)
if how_much < 5000000:
print "Nice take, now you have to escape!"
escape_route()
def escape_route():
print "There are cops blocking the front door."
print "There are cops blocking the back door."
print "There is no way to get out of there."
print "You see a small opening on the ceiling."
print "Type ceiling to go through it."
print "Or type stay to try your luck."
escaped_cops = False
while True:
choice = raw_input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling" and not escaped_cops:
print "You escaped! Now wash that money and don't go to prison."
escaped_cops = True
def dead(why):
print why, ""
exit(0)
bank_vault()
Cool game. I love games and would like to try to improve your code. Code below works on Python 3. It should work on Python 2:
from sys import exit
try: input = raw_input # To make it work both in Python 2 and 3
except NameError: pass
def bank_vault():
print("This room is full of money up to 5 million dollars. How much do you take?")
how_much = int(input("> ")) # Why not eliminate choice variable here?
if how_much == 0:
dead("You are robbing a bank and took nothing... The cops shot you in the face.")
elif how_much < 5000000: # Changed to else condition
print("Nice take, now you have to escape!")
else: # Added a check
dead("There isn't that much!")
def escape_route():
print("There are cops blocking the front door.")
print("There are cops blocking the back door.")
print("There is no way to get out of there.")
print("You see a small opening on the ceiling.")
print("Type ceiling to go through it.")
print("Or type stay to try your luck.")
escaped_cops = False
while not escaped_cops:
choice = input("> ")
if choice == "stay":
dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
elif choice == "ceiling":
print("You escaped! Now wash that money and don't go to prison.")
escaped_cops = True
def dead(why):
print(why)
exit(0)
bank_vault()
escape_route()
You have to call the function escape_route rather than exit.
Also, when checking for choice you call dead no matter what.
In reply to your comment:
You need to check if it's 0 then call dead, if it's not 0 don't bother with the else, go directly to the if how_much < 5000000 and call escape_route
You need to try and convert the input to an int if it isn't 0!
And what happens if they take more than 5 mil?

Invalid python syntax [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input(">")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False
while True:
next = raw_input("> ")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed of and chews your legs off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head(flee/head)?"
next = raw_input("> ")
if next == "flee":
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print why, "Good job!"
exit(0)
def dog_room():
print "you entered a room and you see a dog sleeping and the door behind you got locked by it self"
print "you see a sign that says this dog got a very good hearing sense, above a normals dog hearing sense."
print "and you see a spear beneath you."
print "and you can see that there is a bridge behind him."
print "what will you do now?try to go to the bridge, pick up the spear, try to sneak your way to the dog and hit him or attack the door."
print "(bridge/spear/sneak and hit/attack the door)"
spear = False
while True:
action = raw_input("Choose what you want to do")
if action == "bridge" and not spear:
death("the dog woke up rushed to you and ate you right after he ate your balls."
elif action == "sneak and attack" and not spear:
death("you sneaked your way to the dog, hit him, and the damage you made to him wasn't strong enough and he ate you right after he ate your ball.")
elif action == "spear" and not spear:
spear = True
print "you took the spear. what now?"
elif action == "spear" and spear
print "you already took the spear..."
elif action == "sneak and attack" and spear:
golden_room("you stabbed the dog and went across the safe bridge with no casualties and you managed to get to the golden room!!!!!!!!")
elif action == "attack the door":
print "you broke the wooden door, the dog woke up, rushed to you, you tried to escape but the dog was faster"
print "and ate you right after he ate your balls."
death()
else:
print "*face palm* come on learn how to type!"
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(left/right/forward)?"
next = raw_input("> ")
if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
elif next = "forward":
dog_room()
else:
dead("You stumble around the room until you starve.")
start()
now for the problem
when i run it in power shell:
>>>python ex35.py
what i get is:
File "ex35.py", line 77
elif action == "sneak and attack" and not spear:
^
SyntaxError: invalid syntax
HELP!!! i tried to figure it out for an hour , hour and 30 minutes.
ty
if you are having problems to find the line
it is located right beneath the if line
which located inside the while loop which located inside the dog_room()
function.
Missing close paren:
death("the dog woke up rushed to you and ate you right after he ate your balls."
Missing trailing colon:
elif action == "spear" and spear
death("the dog woke up rushed to you and ate you right after he ate your balls."
--------------------------------------------------------------------------------^
You're missing a closing bracket )

python program error elif else if [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
def Game():
# Story Background
print "You decide to take a walk outside one night when you come accross a corn field."
print "You notice an omnious sound coming from the other side of the maze."
Enter = raw_input("Do you enter? (yes or no)")
if Enter == "Yes" or "yes":
print "You walk into the maze and the corn is so thick together you cant push through"
print "so you walk down the isle surrounded by corn and you come to an intersection."
turn = raw_input("Which way do you go? (Left, Right, Forward, Leave)")
if turn == "Left" or "left":
print "After you turn left you come accross a dead end and you are forced to turn around."
print "You return to the intersection."
turn2 = raw_input("Which way do you go? (Left, Forward, Leave)")
if turn2 == "Forward" or "forward":
print "you walk on deeper into the maze when you come to a left turn"
print "you turn left and come accross a crossroad."
turn3 = raw_input("Which way do you go? (Left, Right, Leave)")
if turn3 == "Right" or "right":
print "You come to a dead end and are forced to turn around"
turn4 = raw_input("Which way do you go? (Forward, Leave)")
if turn4 == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
elif turn4 == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn3 == "Left" or "left":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn2 == "Left" or "left":
print "you turn Left into the maze when you come by a strange man laying on the ground."
man == raw_input("What do you do? (Help, keep going)")
if man == "Help" or "help":
print "you help the man up and he knocks you out cold"
print "you wake back up in your bed at home"
elif man == "keep going" or "Keep going":
print "You leave the man behing after stealing his wallet."
print "YOU HAVE REACHED THE END OF THE MAZE"
print "You realize the noise was the sound of a old farmer milking a cow."
print "The farmer nags at you for coming on private property."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn2 == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Forward" or "forward":
print "you move forward into the maze when you come by a strange man laying on the ground."
man == raw_input("What do you do? (Help, keep going)")
if man == "Help" or "help":
print "you help the man up and he knocks you out cold"
print "you wake back up in your bed at home"
elif man == "keep going" or "Keep going":
print "You leave the man behing after stealing his wallet."
print "YOU HAVE REACHED THE END OF THE MAZE"
print "You realize the noise was the sound of a old farmer milking a cow."
print "The farmer nags at you for coming on private property."
elif turn == "leave" or "Leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Right" or "right":
print "After you turn right you come into a left turn only path."
print "You turn left and you come to a crossroad."
turn = raw_input("Which way do you go? (Left, Right, Leave)")
if turn == "Right" or "right":
print "You come to a dead end and are forced to turn around"
turn = raw_input("Which way do you go? (Forward, Leave)")
if turn == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Forward" or "forward":
print "You walk to a hole in the ground stopping you from moving any further"
print "the hole seems to be filled with snakes so you cant go through it."
print "you are forced to leave the maze."
else:
print "you walk into a wall and go into an irreversable coma"
elif turn == "Leave" or "leave":
print "you leave the maze and return home."
else:
print "you walk into a wall and go into an irreversable coma"
elif Enter == "No" or "no":
print "You walk on into the depths of the night and are robbed by a couple street thugs."
else:
print "you walk into a wall and go into an irreversable coma"
def main():
Game()
main()
when i use this program, no matter what i enter into the python shell, it says the same thing over and over again.. it wont take the raw_input statements into context and put them into the if statements
if Enter == "Yes" or "yes":
This is not how or works. This is interpreted as if (Enter == "Yes") or "yes":. In python, non-empty strings are always true, so all of the if statements like that will be true. I would suggest something like
if Enter.lower() == "yes":
which takes care of all of the upper/lower case combinations.
Your syntax is wrong here:
if Enter == "Yes" or "yes":
This condition will always be true. Enter == "Yes" is first evaluated. If boolean representation is False, the boolean representation of "yes" will be considered. bool("yes") is always True.
Consider doing something like:
if Enter in ('Yes', 'yes'):
Or:
if Enter.lower() == 'yes':

Categories