-1

Im trying to understand the possibilities with Booleans in Python.

I don't want to use an If statement.

its_valid = True 

but I want something like this

its_valid = True if taking_stones == 2 or taking_stones == 1

Is it possible in python and just out of curiosity if not in what language is it?

Edit: second question

Is it possible to use a range as well? (from 1 to 2)

its_valid = True if taking_stones 1:2
dev
  • 651
  • 1
  • 6
  • 14
  • 1
    `its_valid = taking_stones == 2 or taking_stones == 1`. A combination of Booleans is still a Boolean. – chepner Apr 29 '20 at 21:50
  • 1
    You can also writ `its_valid = taking_stones in (1, 2)` or `its_valid = taking_stones in range(1, 3)`. – chepner Apr 29 '20 at 21:50
  • does that range take in floats between those numbers as well such as 1.5 etc And is there a way to specify in case of the range if I want only whole numbers? and is there a way to set a stepping? range(1,10, stepping 2) (would take only 2, 4,6,8,10) thank you! – dev Apr 29 '20 at 21:56
  • I don't think this is really a duplicate of [Python ternary operator](https://stackoverflow.com/questions/4103667/python-ternary-operator) but whatever. – mkrieger1 Apr 29 '20 at 21:56
  • That second question is answered in https://stackoverflow.com/questions/13628791/determine-whether-integer-is-between-two-other-integers – mkrieger1 Apr 29 '20 at 21:58
  • @dev No; that highlights the distinction between a range of discrete integers and an *interval* of continuous real numbers. – chepner Apr 29 '20 at 22:13

1 Answers1

2

Equality comparisons return booleans, so there's no need to explicitly write True if {something true}. You can simply write:

its_valid = (taking_stones == 2 or taking_stones == 1)

Or, if you want to check multiple values more succinctly:

its_valid = (taking_stones in (1,2))
water_ghosts
  • 716
  • 5
  • 12
  • Thank you so much! thats exactly it! Is it good practise to chain a boolean like this or is it preferable to set the boolean as True or False in advance? – dev Apr 29 '20 at 21:58
  • If you set the Boolean in advance, it will just get overridden when you check the values you actually care about. There’s no need to add unnecessary steps if you just want to ask whether a or b is true. – water_ghosts Apr 29 '20 at 22:06