0

Sorry for the wordy title, but I couldn't think of a better way to phrase it. I am comparing 2 values within an if statement. While I would normally do something like this

val = 1

work = input('1 or 2' )
if work == '1':
  #must compare value of val
  if val == 1:
    print('Val is equal to  1')
elif work == '2':
  if val == 2:
   print('val is equal to 2 ')
   #also also compare value of val

All the tutorials say that nesting ifs is a bad practice and will come back to bite you. Is there a better way to do this?

the popo
  • 49
  • 3
  • 1
    why would you need to have `if val...` when val is always 1? Anyways. You can easily do this by adding `and` condition, `if work == '1' and work == val` however you need to change the type of val or work, since one is integer, and the other is string – Alvi15 Nov 26 '20 at 04:43
  • @Alvi15 they could try ```if str(work) == '1' and work = val``` – SophomoreNumberN Nov 26 '20 at 04:51
  • 1
    @SophomoreNumberN work is already of a string type, you would need to do `if work == '1' and work == str(val):` – VoidTwo Nov 26 '20 at 04:53
  • Does this answer your question? [How to have multiple conditions for one if statement in python](https://stackoverflow.com/questions/36757965/how-to-have-multiple-conditions-for-one-if-statement-in-python) – Gino Mempin Nov 26 '20 at 05:05
  • It does. Thanks! – the popo Nov 26 '20 at 06:23

2 Answers2

1

You can put multiple conditions in a single if/elif statement, like so:

if( work == '1') and (val == 1))
     #print
elif ( work == '2') and (val == 2))
     #print
  • 2
    I would also like to add on to this and say that the parenthesis are not required due to Python's operator precedence (https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html). You can simply use `if work == '1' and val == 1:` – VoidTwo Nov 26 '20 at 04:48
1

I believe what you are looking for is the and operator:

val = 1
work = input('1 or 2')

if work == '1' and val == 1:
    # do stuff
elif work == '2' and val == 2:
    # do stuff
VoidTwo
  • 569
  • 1
  • 7
  • 26