direction = input("enter a direction: ")
if direction != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction != "look":
print ("please enter in the following format, go (north,east,south,west,up,down)")
elif direction == "quit":
print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh) ... the game should then end.")
elif direction == "look":
print ("You see nothing but endless void stretching off in all directions ...")
else:
print ("You wander of in the direction of " + direction)
i need to know how to do this in python.
i need to scan user inputs first 2 letters
for example
i = user_input
#user inputs go ayisgfdygasdf
i need it to be able to scan the user input, check if the first 2 letters are go, and if they are go but it doesnt recognise the second word which in this case is "ayisgfdygasdf" then to print "sorry, i cant do that"
He could also try using:
directions.split()
But it may require to use try/except in some cases.
For more information about split and methods try using:
dir(directions)
to see what methods object directions have
or:
help(directions.split)
to see help about a specific method (in this case method split of object directions)
You can access characters of a string in python by index using the [] notation. You can check the first two character in a string by typing user_input[:2]. This code will include all characters up to, but not including the index typed. So this notation will include user_input[0] and user_input[1]. You can then check if user_input[:2] is equal to 'go' or not, and continue from there.
Hope this helped.
Instead try using:
direction = sys.stdin.readlines()
It may require you to ctrl+D after you are done but you will be able to capture so much more.
Also, to get the subarray you can then you can even check:
direction[:2] != "go"
or alternatively, for more readable code:
if not direction.startswith("go"):
Also I'd recommend, for making your code more readable,
defined_direction = frozenset(["quit", "go north", "go south"])
if( direction not in defined_direction):
print "please enter...."
You can index the individual characters of your input:
if direction[:2] == "go":
print "Sorry, I can't do that."
However, trying assign an if-else branch to each possible input is typically a bad choice... It becomes difficult to maintain very quickly.
A cleaner approach in this case might be to define a dictionary with valid input as follows:
input_response = {"quit":"OK ... but", "go north": "You wander off north", \
"go south": "You wander off south"} # etc
You could then re-write your code to something like:
try:
print input_response[direction]
except KeyError:
if direction[:2] == "go":
print "Sorry, I can't do that."
else:
print ("please enter in the following format...")
Related
I am new to python and trying to learn by doing small projects.
I am trying to write a program that displays the names of the four properties and
asks the user to identify the property that is not a railroad. The user should be informed if the selection is correct or not.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) **Short Line**
if properties == "Short Line":
print("correct")
else:
print("incorrect")
However, my final output shows as "incorrect", what am i doing wrong?
The four railroad properties
are Reading, Pennsylvania,
B & O, and Short Line.
Which is not a railroad? Short Line
Correct.
Short Line is a bus company.
Couple things I see with this code you have posted.
First, not sure if you actually have **Short Line** in your actual code but if you are trying to comment use # That way it won't be interpreted at run time.
Second as mentioned in other answers you are checking against properties which is pulling in your array. You should be checking against your input which is stored at question.
properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) # **Short Line**
if question == "Short Line": # replaced properties with question
print("correct")
else:
print("incorrect")
print(properties)
print(question)
I find that when I am having troubles understanding why something is not working I throw some print statements in to see what the variables are doing.
You may want to catch the user in a loop, otherwise you would have to constantly have to run the code to find the correct answer(unless that is the desired behavior, then you can leave it as you have it). Also, be aware that you may want to uppercase or lowercase because a user may provide the answer as "Short line" (lower case "L"), and the code will return as incorrect. Of course, that depends on what you will accept as an answer.
Sample
print ("Reading,Pennsylvania,B & O, or Short Line. Which is not a railroad?")
user_input = input("Please provide an answer: ")
# != the loop will close once the user inputs short line in any form
# The upper.() will convert a user_input string to all caps
while user_input.upper() != "SHORT LINE":
print ("Incorrect, Please try again.")
user_input = input("Which one is not a railroad? ")
print ("Correct")
Prettied it up for you
print( "Reading, Pennsylvania, B & O, and Short Line. Which is not a railroad?" )
print("Which is not a railroad?")
answer = input()
if answer == "Short Line":
print("correct")
else:
print("incorrect")
I looked on stackoverflow to solve my problem but from all explanations about loops and checks I don't understand why my code isn't working.
So I want to build a dictionary (totally new to Python btw) and I read that I can also check if the input is in the dicitonary module but that is actually not what I want to do here. I just want to see if the raw_input contains at least one number in the string (not if the string only contains numbers) and if the length of the input string is at least 2.
If the input passes those checks it should move on (the rest of this dictionary will come later. For now I only want to understand what I did wrong with my check)
Here's my code, help would be very much appreciated!
def check():
if any(char.isdigit() for char in original):
print ("Please avoid entering numbers. Try a word!")
enter_word()
elif len(original)<1:
print ("Oops, you didn't enter anything. Try again!")
enter_word()
else:
print ("Alright, trying to translate:")
print ("%s") %(original)
def enter_word():
original = raw_input("Enter a word:").lower()
check()
enter_word()
Edit: Works now perfectly with the following code:
def check(original):
if any(char.isdigit() for char in original):
print "Please avoid entering numbers. Try a word!"
enter_word()
elif len(original) < 1:
print "Oops, you didn't enter anything. Try again!"
enter_word()
else:
print "Alright, trying to translate:"
print "{}".format(original)
def enter_word():
original = raw_input("Enter a word:").lower()
check(original)
enter_word()
You need to pass the input original to your check() function:
def check(original):
if any(char.isdigit() for char in original):
print("Please avoid entering numbers. Try a word!")
enter_word()
elif len(original) < 1:
print("Oops, you didn't enter anything. Try again!")
enter_word()
else:
print("Alright, trying to translate:")
print("{}".format(original))
def enter_word():
original = input("Enter a word:").lower()
check(original)
enter_word()
In addition to this, you had some syntax errors in your code. Since you used print() instead of print I assume you are using Python3. However, to read user input you used raw_input() which was the way to do in Python2 and became input() in Python3. I fixed this. Another thing I fixed was the string formatting of the print() statement in the else branch. You might take a look at the string format mini-language.
Hi so I am working on a game and my game at the start asks the user if they want the rules to the game (y/n). I'm using if statements and else for this, so if user puts in y print rules and if user puts in n start game etc...it works fine, until the user puts in an integer or a word or something python doesn't recognize and it just goes and uses the else statement. My game is a math game so I used try statements before that if the user punched in something that's not a number it tells the user "Invalid, try again". The problem I'm having now is how to tell python to try multiple things...
I tried using try x = 'y' or x = 'n' but it says you can't give try multiple operations or something
Please help,
Cheers
You might want to use the following:
if inp=="Option1":
...
elif inp=="Option2":
...
elif inp=="Option3":
...
else:
print "Not known command"
You need a while loop that will keep taking input until the user inputs either y or n
while True:
inp = raw_input("Add intruction here")
if inp == "y":
# code here
elif inp == "n":
# code here
else:
print "Invalid input"
So, I'm working my way through Learn Python the Hard Way, and I am on Lesson 36, where I make my own BBS-text-style game based on the one he did in lesson 35.
http://learnpythonthehardway.org/book/ex36.html
http://learnpythonthehardway.org/book/ex35.html
So, I did a decent job, but I noticed that when I mimicked his eternal while-loop, where the player can't ever leave the room under anything but very specific circumstances, the loop always gives the same response for the else...unless they say the right thing, they're stuck forever.
Here's my code:
def sleeping_giant():
print "There is a single door, with a giant sleeping in front of it."
print "How can you get the giant to move?"
print "Should you wake him?"
giant_moved = False
while True:
choice = raw_input("> ")
if choice == "Yes":
dead("The giant rips you into four pieces and uses your quartered body as a stack of pillows.")
elif choice == "No" and not giant_moved:
print "The giant rolls in his sleep, clearing an easy path to the door."
giant_moved = True
elif "Open" or "Go" in choice and giant_moved:
treasure_room()
else:
print "I have no idea what the fuck you are trying to say to me. English. Do you speak it?!"
Apologies if that format doesn't translate well.
Anyway, anytime the user types something that doesn't satisfy an if or an elif, they will receive that same else response.
How would I change this? As in, make it more dynamic, so that if they keep screwing up the response, the else response changes?
I can't figure out how to get the code to say (in non-literal terms, I mean, I can't get the logic to say), 'If the else has been used, the response should be a new else, and once that one has been used, it should be yet another else response'.
If this doesn't make sense, please let me know.
Here's the incremental version of Greg's answer using a counter so you can get a predictable order of responses:
global responses = [ "Nice try. Try again.",
"Sorry, what was that?",
"I don't know what that means."]
def sleeping_giant():
counter = 0
print "There is a single door, with a giant sleeping in front of it."
print "How can you get the giant to move?"
print "Should you wake him?"
giant_moved = False
while True:
choice = raw_input("> ")
if choice == "Yes":
dead("The giant rips you into four pieces and uses your quartered body as a stack of pillows.")
elif choice == "No" and not giant_moved:
print "The giant rolls in his sleep, clearing an easy path to the door."
giant_moved = True
elif ("Open" in choice or "Go" in choice) and giant_moved:
treasure_room()
else:
print responses[counter]
if counter < 2:
counter += 1
This condition:
elif "Open" or "Go" in choice and giant_moved:
parses as the following (according to operator precedence):
elif "Open" or (("Go" in choice) and giant_moved):
Since "Open" is considered True, this condition will always match. It sounds like you might instead want:
elif ("Open" in choice or "Go" in choice) and giant_moved:
To choose a different response, try something like:
else:
responses = [
"Nice try. Try again.",
"Sorry, what was that?",
"I don't know what that means.",
]
print random.choice(responses)
I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).
If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.
def miles():
print "How many miles do you walk?"
miles_choice = raw_input("> ")
how_much = int(miles_choice)
if how_much >= 10:
right_dest()
elif how_much < 10:
turn()
else:
print "You can't just stand here..."
miles()
Ok so here's two questions:
How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().
Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?
I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.
You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:
distances = {
'right': 7,
'left': 17,
'forward': 4
}
direction_choice = raw_input("> ")
miles_choice = raw_input("> ")
if how_much >= distances['direction_choice']:
right_dest()
elif how_much < distances['direction_choice']:
turn()
else:
print "You can't just stand here..."
miles()
Be sure to properly validate and cast the user input, which I have not addressed. Good luck!
I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).
For example:
#!/usr/bin/env python
# ...
def miles(max_miles=10):
print "How many miles do you walk?"
while True:
miles_choice = raw_input("> ")
try:
how_much = int(miles_choice)
except ValueError, e:
print >> sys.stderr, "That wasn't a valid entry: %s" % e
continue
if max_miles > how_much > 0:
break
else:
print "That's either too far or makes no sense"
return how_much
... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.
It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.
Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.
(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).
#Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.
#Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.
class MyGame:
def __init__(self):
self.current_miles = 0
self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}
def miles(self,pos):
print "How many miles do you walk?"
miles_choice = raw_input("> ")
self.current_miles += int(miles_choice)
if self.current_miles >= self.dest.get(pos):
self.miles("Right")
elif self.current_miles < self.dest.get(pos):
print "you went "+ str(self.current_miles) + " miles"
else:
print "You can't just stand here..."
self.miles(pos)
mg = MyGame()
mg.miles('Into the jungle')