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"
4 Answers
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...")