Godfist
Godfist

Reputation: 3

Pulling from a list

My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:

Body_Type = ['Large', 'Medium', 'Small']

print('Create a Character-')

print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
    if bt == Body_Type[0:]:
        print('Your Body Type is: ' + bt)

else:
        print('Invalid Body Type')

What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.

Thanks in advance!

Upvotes: 0

Views: 85

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).

But it shouldn't be so complex to write some working code.

I would create an infinite loop and break only if choice is in the list:

while True:
    bt = input('Enter your Body Type: ')
    if bt in Body_Type:
        print('Your Body Type is: ' + bt)
        break
    else:
        print('Invalid Body Type')

simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.

The key statement you were looking for was bt in Body_Type which tests if the string is within the list.

Upvotes: 1

Related Questions