简体   繁体   中英

Comparative operation of a variable to an element of a list

I am a beginner in Python and have just started to learn it. I am just creating a simple code script which should display the name of the candidate who has secured the rank, entered by the user. But when I execute the code it is running the print statement under the else command and doesn't make the comparisons when I enter the number that is a part of the list. Kindly help me with your suggestions.

print('Enter the Rank:')
x = input()
if x is list[0]:
    print('Jack has secured First rank')    
elif x is list[1]:
    print('Brown has secured Second rank')   
elif x is list[2]:
    print('Martin has secured Third rank')  
else:
    print('Sorry you have failed')```

is operator checks whether both the operands refer to the same object or not while == compares the values of both the operands.

I guess that you want to compare the values of x and list members so change the is operator you use into == :

print('Enter the Rank:')
x = input()
if x == list[0]:
    print('Jack has secured First rank')    
elif x == list[1]:
    print('Brown has secured Second rank')   
elif x == list[2]:
    print('Martin has secured Third rank')  
else:
    print('Sorry you have failed')```

As a side note, try to avoid naming your variables with built-in names like list .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM