Python: how to make this code simpler? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have some codes below, the choice takes only integer input but prints out something special if the input is not an integer. However, the codes below to treat this issue seems a little bit lengthy. Anyway to fix it?
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if "0" in choice or "1" in choice or "2" in choice or "3" in choice or "4" in choice or "5" in choice or "6" in choice or "7" in choice or "8" in choice or "9" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You're greedy!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()

Try something like:
try:
how_much = int(choice)
except ValueError:
dead('Man, learn to type a number.')
and look up Easier to ask for forgiveness than permission for the rationale.

You can use the str.isdigit() to check if its a number, using try...except statement for this is not recommended because it makes your code messy and could cause errors in the long run. But if it's only that it'll work too.
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("> ")
if choice.isdigit(): #Checks if it's a number
how_much = int(choice)
else:
dead("Man, learn to type a number.")
return
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(1)
else:
dead("You greedy bastard!")
def dead(why):
print why, "Good job!"
exit(0)
gold_room()

Related

Building a mini text-based python game as homework of learn python the hard way

I'm new to this website so please bear with my questioning problems on the website. I need some help to finish off this mini text-based game as homeowork of learning python the hard way book. This is the code I wrote. and I don't know the missing links and what I've done wrong. Help would be appreciated!
from sys import exit
def start():
print "You are in an old temple."
print "There is a door to your right and left or you can walk forwad."
print "Which one do you take?"
choice = raw_input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
start()
def monster_room():
print "you're in a room with a monster. what you gonna do?"
choice = raw_input("> ")
if "left" in choice:
print "you are going to the gold room"
gold_room()
elif "right" in choice:
print "you are going to the trap room"
trap_room()
else:
dead("couldnt understand what did you say so you are dead!")
def gold_room():
print "you chose the left room. now you are in a room with a pot of gold!"
print "you can take the pot."
print "or you can just rob the money in it."
print "or you go go to other rooms."
choice = raw_input("> ")
if choice == "take the pot":
print "you are a millionaire from now on!!!"
elif choice == "rob the money":
dead("you will never rest in piece!")
else choice == "another room":
monster_room()
def trap_room():
print "you are now in a trap room."
print "there is a hidden trap in this room."
print "be careful!"
print "you can go back to the monster room"
print "or you can find the trap"
choice = raw_input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print why, "rekt!"
exit(0)
Ok, I've fixed it. Your code has several indentation mistakes, Python requires four spaces or one tab indentation after a def statement.
Another thing is, that you used else with a condition test (else choice == "another room":). That is wrong, it should be elif choice == "another room": or just else.
You also may have noticed, that I changed raw_input() to input(). This converts all inputs to strings (input() will interpret intergers as integers, lists as lists and so on...), and is also more secure.
The last thing is, you run your program (start()) before definign all called functions, this cannot work!
Your code (fixed):
from sys import exit
def start():
print("You are in an old temple.")
print("There is a door to your right and left or you can walk forwad.")
print("Which one do you take?")
choice = input("> ")
if choice == "left":
gold_room()
elif choice == "right":
trap_room()
elif choice == "forward":
monster_room()
else:
dead("you got caught by the ancient gods and you must be killed.")
def monster_room():
print("you're in a room with a monster. what you gonna do?")
choice = input("> ")
if "left" in choice:
print("you are going to the gold room")
gold_room()
elif "right" in choice:
print("you are going to the trap room")
trap_room()
else:
dead("couldn't understand what did you say so you are dead!")
def gold_room():
print("you chose the left room. now you are in a room with a pot of gold!")
print("you can take the pot.")
print("or you can just rob the money in it.")
print("or you go go to other rooms.")
choice = input("> ")
if choice == "take the pot":
print("you are a millionaire from now on!!!")
elif choice == "rob the money":
dead("you will never rest in piece!")
elif choice == "another room":
monster_room()
def trap_room():
print("you are now in a trap room.")
print("there is a hidden trap in this room.")
print("be careful!")
print("you can go back to the monster room")
print("or you can find the trap")
choice = input("> ")
if "find" in choice:
start()
elif "back" in choice:
gold_room()
def dead(why):
print(why, "rekt!")
exit(0)
start()
I would call the start() function at the end, after all the functions you defined. A usual way to write that is to write the following code at the end:
if __name__ == "__main__":
start()
This basically means that the programm runs the start() function at the end, if you're executing the file.
Furthermore you have to leave spaces after defining a function. You wrote:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
but it should be:
def monster_room():
print "you're in a room with a monster. what you gonna do?"
If that didnt help, specify the problem

How do I get this function to read the input properly?

I am having trouble with my monster_room function. No matter what the input is, it will always choose the elif choice (elif choice > 5:...). Here is the function:
def monster_room():
print "This is the monster room! How many monsters do you see?"
choice = raw_input("> ")
if choice < 5:
dead("More than that idiot!")
elif choice > 5:
print "More than you thought right?!"
print "Do you go to the Alien room or Frankenstien room?"
choice_one = raw_input("> ")
if choice_one == "alien":
alien_room()
elif choice_one == "frankenstien":
frankenstien_room()
else:
print "Type alien or frankenstien, DUMMY!"
monster_room()
else:
print "Type a number!"
monster_room()
How do I get it to read the input? Also this is my first project and I know it's very basic and probably looks rough so other tips I am open to as well. If you need the full code (99 lines) just let me know! Thanks!
You need to parse your input data to a number type using int() because raw_input() returns a string.
choice = int(raw_input("> "))
As #Joran Beasley metniioned to be on the save side you shuld use a try except block:
try:
choice = int(raw_input("> "))
except ValueError:
print "Type a number!"
monster_room()
you'll get to the "type a number!" section even if you input 5 since you're not allowing a >= or <= scenario.
I do agree, though, you have to convert the input to an int or float.
Casting the input to int will solve it (it's a string when you use it). Do this:
choice = int(raw_input("> "))

Learn Python The Hard way 36 code efficiency

Hello I'm studying the book "Learn Python The Hard Way" by Zed Shaw and I have reached exercise 36 where we right our own game from scratch using loops and if statements.
My game is finished and it's running however the code itself looks so messy and inefficient. The main problem is with trying to get the user's choice and having to rewrite the same code for the same word but with a capital letter, example:
def puzzle1():
print "\"A cat had three kittens: January,March and May. What was the mother's name.\""
choice = raw_input("Mother's name?: ")
if "What" in choice:
print "You are correct, the door opens."
door2()
elif "what" in choice:
print "You are correct, the door opens."
door2()
elif "WHAT" in choice:
print "You are correct, the door opens."
door2()
elif "mother" in choice:
print "Haha funny... but wrong."
puzzle1()
else:
print "You are not correct, try again."
puzzle1()
I wonder if there is a way to have all these choices in one line, also if there is anything else I can make more efficient please let me know. Sorry for the silly question I'm new to programming.
Use str.lower and remove the multiple if/elif's for what.
choice = raw_input("Mother's name?: ").lower()
if "what" in choice:
print "You are correct, the door opens."
door2()
elif "mother" in choice:
print "Haha funny... but wrong."
puzzle1()
else:
print "You are not correct, try again."
puzzle1()
I would also loop instead of repeatedly calling puzzle1, something like:
while True:
choice = raw_input("Mother's name?: ").lower()
if "what" in choice:
print "You are correct, the door opens."
return door2()
elif "mother" in choice:
print "Haha funny... but wrong."
else:
print "You are not correct, try again."

Learn python the hard way - exercise 36 function problems

I'm learning to code through learn python the hard way, and I've recently gotten stuck for the first time. For this exercise we're supposed to write our own game. I did so, but for some reason whenever I run it the right_room() function exits after I put in an answer, instead of proceeding to the next room. Any help would be greatly appreciated. Here's my code:
from sys import exit
def bear_room():
print "You are in a room with a bear."
print "You have two choices. left or right?"
next = raw_input("> ")
if next == "left":
left_room()
elif next == "right":
right_room()
else:
print "No idea what that means..."
def left_room():
print "You went left."
print "There are two doors. right or straight"
next = raw_input("> ")
if next == "right":
bear_room()
elif next == "straight":
second_left()
else:
print "What are you saying, bro?"
def second_left():
print "You went straight."
print "You again have two choices. straight or right?"
next = raw_input("> ")
if next == "straight":
print "You won! Congrats."
exit(0)
elif next == "right":
dead("You opened the door and walked off a cliff. Goodbye!")
else:
print "I didn't quite catch that."
def right_room():
print "You went right."
print "There are two doors. straight or right?"
next == raw_input("> ")
if next == "right":
dead("Oops, a tiger just ate you")
elif next == "straight":
second_right()
else:
"What?!?!?!"
def second_right():
print "You went straight"
print "Nice choice."
print "You have two choices: left or straight"
next == raw_input("> ")
if next == "left":
dead("You just fell 1 million feet to your death.")
elif next == "straight":
print "You made it out alive!"
exit(0)
else:
"WTF?"
def dead(reason):
print reason, "good job!"
exit(0)
def start():
print "You are about to enter a room."
bear_room()
start()
It looks like you're trying to assign to the next variable, but you used the equality check operator (==).

Flow control in a simple Python script

I am trying to make a simple game.
The logic is like this: "There are five doors, each numbered 1 to 5. Users will be asked to input any one number. For example, if they enter "1", the GoldRoom will be opened (and the associated class will be processed)."
Now, I have defined one class, GoldRoom(), and for testing, entered "1". The processing happens as expected. However, when I enter "2" as my choice, the processing still happens, instead of the print statement, i.e the else statement is not getting executed.
Where am I going wrong?
#################################
# Learning to make a game#
#################################
# An attempt to make a game
# Each room will be described by a class, whose base class will be Room
# The user will be prompted to enter a number, each number will be assigned with a Room in return
from sys import exit
print "Enter your choice:"
room_chosen = int(raw_input("> "))
if room_chosen == 1:
goldroom = GoldRoom()
goldroom.gold_room()
def dead(why):
print "why, Good Job!"
exit(0)
#class Room(object): #the other room will be derived of this
# pass
class Room(object):
pass
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
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)
print how_much
else:
dead("Man, learn to type some number")
if how_much < 50:
print "Nice, you are not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
#class KoiPondRoom(Room):
# in this room, the user will be made to relax
#class Cthulhu_Room(Room):
# sort of puzzle to get out
#class Bear_Room(Room):
# bear room
#class Dark_Room(Room):
# Dark Room, will be turned into Zombie
#class Dead_Room(Room):
# Those who enter here would be dead
if room_chosen == 1:
goldroom = GoldRoom()
goldroom.gold_room()
else:
print "YOU SUCK!"
the problem is here:
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
print"This room is full of gold. How much do you take!"
as the whole source loaded into python vm, this piece of code is executed, and it print some thing, you should change it to:
class GoldRoom(Room):
# here the user will be asked with question on how much Gold he wants
def gold_room(self):
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)
print how_much
else:
dead("Man, learn to type some number")
if how_much < 50:
print "Nice, you are not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")

Categories

Resources