-1

The below will only print 'try again' or follow the exit path. How do I meet the two word criteria (IE 'go' and 'north' for the if statement) on the first two statements, while also being able to meet the single word criteria of the 'exit' elif statement.

proceed = ['go', 'walk', 'travel', 'move']
direction = ['north', 'east', 'south', 'west']

while True:
    choice = input("> ").lower()
    # result = choice.split()


    if choice in proceed and choice == direction[0]:
        print("you proceed north")
    elif choice in proceed and choice == direction[1]:
        print("you proceed east")
    elif choice == 'exit':
        exit(0)
    else:
        print("try again")

2 Answers2

0

you use python operation wrong here is the fixed code

proceed = ['go', 'walk', 'travel', 'move']
direction = ['north', 'east', 'south', 'west']
action = ['check', 'take']
item = ['bag', 'ball', 'knob']

while True:
    choice = input("> ").lower()
    part1 = choice.split()[0]
    part2 = choice.split()[1]


    if part1 == proceed[0] and part2 == direction[0]:
        print("go north")
    elif part1 == proceed[0] and part2 == direction[1]: # works if i type 'go', not 'go east'
        print("go east")
    elif part1 == action[1] and part2 == item[0]: # works if i type 'take', not 'take bag'
        print("take bag")
    elif part1 == action[1] and part2 == item[2]:
        print("take knob")
    elif part1 == 'exit':
        exit(0)
    else:
        print("try again")

some of the mistakes are elif choice == action[1] and item[2]: item[2] will always be true so second check will always be true, you must specify exact condition to check for example part2 == item[2].

Also, use == instead of is to check if a string is same as another. is in Cpython implementation check if both point to same memory location, It works since python use String interning

KMG
  • 1,433
  • 1
  • 8
  • 19
  • @pythonNoob9000 yes which i think is what you wanted since you always make 2 checks which I think correspond to 2 parts. – KMG Jun 25 '21 at 00:38
  • @ Khaled No, I don't want it to break if they enter less than two words. I changed my original question and code to be more clear as to what I am trying to achieve. I had successfully done what you suggested already, but as stated it breaks and I was trying to avoid it. – pythonNoob9000 Jun 25 '21 at 00:51
0

You have to do it like this. Just an example. Correct way of doing it:

if condition == 2 and condition2 == 2: 
      #code 

Incorrect way of doing it: (How you're doing it)


if condition == 2 and condition: 
      #code 

python won't understand what you're trying to do, so you have to be more specific.