1

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! :)

nosklo
  • 217,122
  • 57
  • 293
  • 297

1 Answers1

1

(1) Referring to this line: if qr == '' or not qr[0].lower() in ['y','n']:

The [0] on qr refers to the first character of the input qr only.

(2) The differences between this two pieces of code is on the same one, the first is

  • if qr == '' or not qr[0].lower() in ['y','n']:
  • if qr == '' or not qr.lower() in ['y','n']:

The second one affects the entire string of qr and keeps all the characters, and makes a difference if you input a string longer than one character.