1

I'm attempting to make a program that loops if the user inputs a particular phrase. Currently the program ends the loop no matter what the user inputs.

umlist = ['um', 'UM' , 'Um' ]
while True:
    phrase = input('Say something. ')
    umcheck=phrase.split()
    if umcheck in umlist:
        print("You said um, try again")
    else:
        break
print("Well done, you didn't say um.")

What do I need to change to have the program detect and loop if a user inputs "um"

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
SirSpiffy
  • 23
  • 5
  • with `if umcheck in umlist:`, you are checking if the whole list coming from `phrase.split()` is in `umlist`. you want to check each word – PRMoureu Mar 16 '19 at 08:20

3 Answers3

3

You can achieve that with a simpler solution:

Make your input lowercase, and then just check for 'um' in that:

while True:
    phrase = input('Say something. ')
    umcheck=phrase.lower().split()

    if 'um' in umcheck:
        print("You said um, try again")
    else:
        break
print("Well done, you didn't say um.")
Amir
  • 1,885
  • 3
  • 19
  • 36
2

in looks for the occurrence of the list in the other list. It doesn't perform the intersection test as you think it does.

Just to illustrate, the only way you could make your condition match would be to put a list in a list, like this:

umlist = ['um', 'UM' , 'Um', ["my","sentence"] ]
umcheck = ["my","sentence"]
>>> umcheck in umlist
True

There are ways with any and other (Test if lists share any items in python). My approach would be to work with set. Create a set of words you don't want to see, and see if the set of words the user inputted intersects:

umlist = {'um', 'UM' , 'Um' }
while True:
    phrase = input('Say something. ')
    umcheck=set(phrase.split())
    if not umcheck.isdisjoint(umlist):
        print("You said um, try again")
    else:
        break
print("Well done, you didn't say um.")

umcheck.isdisjoint(umlist) returns True if both sets have no element in common. Negate that for your test (or inverse the if branches for more clarity)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

At first, umcheck is a list! not a word.

exp:

phrase = "this is an um test"

then:

umcheck => ['this', 'is', 'an', 'um', 'test']

You can't find any list in umlist.

You can do this:

umlist = ['um', 'UM' , 'Um' ]
end = False
while True:
    phrase = input('Say something. ')
    umcheck=phrase.split()
    for item in umcheck:
        if item in umlist:
          print("You said um, try again")
        else:
          end = True
    if end:
        break
print("Well done, you didn't say um.")
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34