I am trying (python) to insert a position of a list from the keyboard and if the position exists then it shows but my sentence is not working correctly
l = ['Poland', 'Spain','France']
variable=int(input('give me the position'))
for i in range(len(l)):
if(i==variable):
print(l[i])
else:
print('the position does not exist')
For example if I choose the position 2 it returns me 'the position does not exist' two times plus France and if I choose a position that it does not exist then it returs me 'the position does not exist' three times
I also tried the next sentence but I insert a position that it is not in the list (for example 4) then it returns me IndexError: list index out of range instead of the print 'does not exist'
if(l[variable]in l):
print(l[variable])
else:
print('does not exist')
Could you help me?
thank you
You don't need to use for loop, you can use try-catch as error handling. This is what you need
l = ['Poland', 'Spain','France']
variable=int(input('give me the position = '))
try:
print(l[variable])
except IndexError:
print("position does not exists")
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.