-2

Given the example

if row[3] == ' male' & row[5] == 0 & row[6] == 0;

i want to check more than one variable , it keeps on giving me an error can someone politely right an example code of how to accomplish this

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
Mr_Shoryuken
  • 719
  • 3
  • 8
  • 16

3 Answers3

1

By using the and keyword or & character as you have done:-

if row[3] == 'male' and row[5] == 0 and row[6] == 0:
if row[3] == 'male' & row[5] == 0 & row[6] == 0:

However, you've used a semi-colon (;) at the end of your if statement, when it should have been a colon (:) which tells your Python interpreter to expect indented code. A semi colon terminates a statement, only really used in Python when you want to put two statements on one line. In this case it will not execute the intended if "block"

For future reference:

If you are asking questions on StackOverflow about an error, post the error in case you have misunderstood its intention like in this case.

Community
  • 1
  • 1
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
  • Thank you , im just new to python hahaha :D – Mr_Shoryuken Dec 02 '15 at 15:53
  • Never used `&` in Python but fair enough, expanded my answer. – Ross Drew Dec 02 '15 at 15:57
  • 1
    @AyushShanker Be careful - `&` means "bitwise and", which is not equivalent to `and` (i.e. "logical and"). In this case, since each of the conditional statements evaluates to a boolean, `&` will give the same result as `and`, but this is not necessarily true for other types. For example, `(1 and 2) == 2` whereas `(1 & 2) == 0`. – ali_m Dec 02 '15 at 18:41
0

while the other answer is better, you can also use & (bitwise and operator):

if (row[3] == ' male') & (row[5] == 0) & (row[6] == 0):
Ayush
  • 3,695
  • 1
  • 32
  • 42
0

To use multiple conditions use the and keyword

if (row[3] == ' male' and row[5] == 0 and row[6] == 0):

The () make it easier to read. Also you need to use : instead of ;.

NendoTaka
  • 1,224
  • 8
  • 14
  • Personally I would enclose each conditional statement in parentheses, e.g.: `if (row[3] == ' male') and (row[5] == 0) and (row[6] == 0):`, but this is more of a stylistic point. – ali_m Dec 02 '15 at 18:43
  • The format of the the enclosure is up to personal opinion but I do it this way because the format is similar to c based languages which most programmers are familiar with, making it easy to read. – NendoTaka Dec 02 '15 at 19:30
  • I see. My reasoning for having parens around each comparison is that they make the order of operations obvious, e.g. `... (row[5] == 0) and (row[6] == 0) ...` rather than `... row[5]) == (0 and row[6]) == (0 ...`. In this case it's trivial, but for more complex expressions I find that they can help a lot with clarity. – ali_m Dec 02 '15 at 19:51