Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if 'x' and 'y' in 'z':

I'm making sort of a Q&A script in python. It gets raw_input, and sets it as theQuestion. I tried if 'var1' and 'var2' in theQuestion:, but it looks for either string, not both. Is there a way I can make this work in one 'if' statement? (not 'if x: if y: then z).

like image 320
tkbx Avatar asked Nov 07 '11 20:11

tkbx


Video Answer


2 Answers

and is a logical AND, not a natural-language one. Therefore, your code gets interpreted as:

'var1' and 'var2' in theQuestion
True   and 'var2' in theQuestion # Since bool('var1') == True
           'var2' in theQuestion

You want to connect the two tests with a logical AND:

if 'var1' in theQuestion and 'var2' in theQuestion:

Alternatively, for large numbers of tests:

if all(k in theQuestion for k in ('var1', 'var2')):
like image 186
phihag Avatar answered Sep 30 '22 21:09

phihag


How about:

if 'x' in z and 'y' in z:
  ... do something ...
like image 32
Matt Fenwick Avatar answered Sep 30 '22 21:09

Matt Fenwick