adriaanbd adriaanbd - 2 days ago 5
Python Question

Why doesn't the second part of this loop work?

The user should insert a name as an input and then confirm with a yes or no (or any of its derivatives) if the 3 worded name includes a middle name or not. So far, I've gotten the loop to work if the answer is yes; however it keeps looping the question if the answer is no.

The purpose: if the answer is yes, the program will understand its a 3 worded name with a middle name and therefore execute naming combinations with the middle name; if its no, the program will understand its a 3 worded name with a second last name instead of a middle name and therefore execute naming combinations accordingly.

Please note I have exluded a lot of the code for sharing purposes.

What I'm I doing wrong? My question is in regards to the elif part of the loop.

print ('enter name')
providedname = input ()
while providedname != 'quit':
if len(providedname.split())==4:
pass

elif len(providedname.split())==3:
print ('Does the name include a middle name or middle initial? Please type yes or no:')
userinput = input()

if userinput.startswith ('ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'):
firstname, middlename, lastname = providedname.split()

elif userinput.startswith ('no' or 'No' or 'NO' or 'na' or 'Na' or 'NA'):
firstname, lastname, secondlastname = providedname.split()

else:
pass

print ('enter name or type quit or q to exit')
providedname=input()
continue

Answer

So, just run this in the interpreter

>>> 'ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'
'ye'

Your startswith isn't working the way you think it does.

Other than that, you can shorten that statement up if you lowercase your strings.

Runnable example

while True:
  providedname = input ('enter name or type quit or q to exit: ')

  if providedname in {'quit', 'q'}:
    break

  names = providedname.split()

  if len(names) == 4:
    pass
  elif len(names) == 3:
    userinput = input('Does the name include a middle name or middle initial? Please type yes or no:')

    if userinput[:2].lower() in {'ye', 'ya'}:
      firstname, middlename, lastname = names
    elif userinput[:2].lower() in {'no' , 'na'}:
      firstname, lastname, secondlastname = names
    else:
      pass

    print(firstname, lastname)
Comments