See if an item in a list is in another item in Python -


i'm new programming, , have started learning python. wanted create small program detects if enter in "bad word" in entry.

name = input ('please enter name. ') badword=['foo', 'bar'] if name in badword:     print ('no.') else:     print ('yes') 

this way doesn't work it's taking entirety of entered , searching list entry. , if try us:

if badword in name: 

then error. call each part of list, that's lot of code if you're entering in different types of bad words, , lengthy know can in less code. little lost here, , google searches have come dry.

you need loop on badword list test each word:

for word in badword:     if word in name:         print('no.')         break else:     print('yes.') 

the else clause part of for statement; executed when loop not interrupted break statement, in case if none of values badword matched.

this can shortened any() function , generator expression:

if any(word in name word in badword):     print('no.') else:     print('yes.') 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -