Home > database >  "if string in" returning False
"if string in" returning False

Time:11-24

I am creating a text based game for a Python class.

I created a dictionary for my rooms and created a list for my directions:

rooms = {
    'Great Hall': {
        'name': 'Great Hall',
        'South': 'Bedroom'
    },
    'Bedroom': {
        'name': 'Bedroom',
        'North': 'Great Hall',
        'East': 'Cellar'
    },
    'Cellar': {
        'name': 'Cellar',
        'West': 'Bedroom'
    }
}

directions = [
    'North',
    'South',
    'East',
    'West'
]

Here is the code snippet with my if statement:

current_room = rooms['Great Hall']

while True:
    print('You are in', current_room['name'])
    command = input('What would you like to do? ')

    if command in directions:
        if command in current_room:
            current_room = rooms[current_room[command]]
        else:
            print('Nothing happened')
    elif command == 'Quit':
        print('Goodbye')
        break

The if statement returns True if the user inputs the command something like South, but does not return True if the user inputs the command Go South. If the string South is in the string Go South, why wouldn't this return True? What can I change for it to return True?

CodePudding user response:

Let's reduce your problem down some more:

It seems to me this is all the code that is necessary to describe your problem:

   directions = ['South', 'North', 'East', 'West']
   command = 'South'
   if command in directions:
     print('This works as LaLoba expects')
   
   command = 'Go South'
   if command in directions:
     print('This line of code does not execute, but LaLoba would like it to.')

What's happening:

Let's think of the in operator as a function:

def is_element_in_container(thing_im_searching_for, container):
  for element in container:
    if element == thing_im_searching_for:
      return True
  return False

Given this, the string 'Go South' is clearly not in the container, so it would fail to match.

CodePudding user response:

Note that when asking if command in directions: you actually searching if the command is an element of the list directions.

Your intention is to ask if command is a part (substring) of one of the element in the direction list.

So, something like:

if any(single_direction in command for single_direction in directions)

would return true.(Since now you ask, for any direction, if its in what the user has inputed)

However, take into consideration you should also treat the various options for the user input also in your rooms map.

  • Related