Unsuccess in comparing strings on a while loop

Question:

So I want to do a function that returns a string with 4 binary digits, representing movement possibilities to West, North, East and South, respectively. This function should ask the user for a direction.

But when I try to compare the str direction with the several first numbers of each str of the possbDir list, I can’t get a expected result.

I tried to make the code work out of the fucntion first, so I gave the string ‘1101’ to the existing function optionsDir that returns a string containing several parts, each formed by a number, followed by a ‘:’, followed by one of the elements of the list DIR.
`

DIR = {1:"West", 2:"North", 3:"East", 4:"South"}
def optionsDir(possibilities):   
    result = [str(i) + ":" + DIR[i] for i in range(1,5) 
                                           if possibilities[i-1] == '1']
    return " ".join(result)

possb = optionsDir('1101')
possbDir = [str(x) for x in possb.split(sep = " ")]
direction = str(input("Choose a direction: " + possb + " (0 to stop)" + "n"))
for i in range(len(possbDir)):
    while direction[0] != possbDir[i][0]:
        print("Wrong choice!")
        direction = str(input("Insert a new direction:" + possb + " (0 to stop)" + "n"))
print(direction)

`
In this case, the possible directions are: [‘1:West’, ‘2:North’, ‘4:South’]. So if I input 1, it would be expected that the while loop stopped and simply printed the chosen direction, but it returns the Wrong choice! for every number I input.

This is my first time posting here, so I’m sorry in advance for poor formating or any info lacking.
Thanks in advance

Asked By: aseenontv

||

Answers:

The problem is the for loop. You want to check if the direction is one of the possible directions you can go in, but the for loop is outside the while loop, so i will never be reassigned. What you could however do, make a list for the possible directions beforehand, and use that as condition in your while loop. That would look like this:

while direction[0] not in [x[0] for x in possbDir]:
    print(direction[0],possbDir)
    print("Wrong choice!")
    direction = str(input("Insert a new direction:" + possb + " (0 to stop)" + "n"))
print(direction)

where

[x[0] for x in possbDir]

is your list of possible directions (in this case: [‘1′,’2′,’4’])

Answered By: Lexpj
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.