I'm learning Python, and I wanted to do a simple yes/no question.
I stumbled with this code on the internet:
qr = input('Do you love cute owls?')
while True:
if qr == '' or not qr[0].lower() in ['y','n']: # This line in question
print('Please answer with yes or no!')
else:
break
if qr[0].lower() == 'y': #Do something
if qr[0].lower() == 'n': #Do something else
and this allows the code to detect any word starting with y or n, so it looks more "smart".
I really want to know whats the difference between that code and just writing:
qr = input('Do you love cute owls?')
while True:
if qr == '' or not qr.lower() in ['y','n']: # Difference
print('Please answer with yes or no!')
else:
break
if qr.lower() == 'y': #Do something
if qr.lower() == 'n': #Do something else
Why the second code doesn't work? What's the purpose of that [0]
and why without it the code doesn't detect the words starting with y
or n
? I really want to know! :)