22

In JavaScript, one could do this:

if (integer > 3 && integer < 34){
    document.write("Something")
}

Is this possible in Python?

please delete me
  • 819
  • 2
  • 14
  • 29

6 Answers6

57

Python indeed allows you to do such a thing

if integer > 3 and integer < 34

Python is also smart enough to handle:

if 3 < integer < 34:
    # do your stuff
Nico
  • 1,328
  • 8
  • 7
13

Python replaces the usual C-style boolean operators (&&, ||, !) with words: and, or, and not respectively.

So you can do things like:

if (isLarge and isHappy) or (isSmall and not isBlue):

which makes things more readable.

andronikus
  • 4,125
  • 2
  • 29
  • 46
11

Just on formatting. If you have very long conditions, I like this way of formatting

if (isLarge and isHappy) \
or (isSmall and not isBlue):
     pass

It fits in nicely with Python's comb formatting

Nickle
  • 367
  • 3
  • 5
  • 1
    Yes, that is a good way to split things up. – andronikus Oct 18 '11 at 16:59
  • 3
    Using \ can be dangerous. I'd wrap the conditions in an outer set of parens – foosion Oct 18 '11 at 17:50
  • 1
    foosion's right, it's better to use an extra set of parentheses and break the line while that extra set is open than to use a backslash. See "Maximum Line Length" at [PEP 8: Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/). – Kurt McKee Nov 13 '11 at 18:50
  • @foosion why using \ can be dangerous ? – Tokci Oct 03 '22 at 04:14
5
if integer > 3 and integer < 34:
    # do work
taskinoor
  • 45,586
  • 12
  • 116
  • 142
3

yes like this:

if 3 < integer < 34:
    pass
mouad
  • 67,571
  • 18
  • 114
  • 106
1

Yes, it is:

if integer > 3 and integer < 34:
   document.write("something")
Constantinius
  • 34,183
  • 8
  • 77
  • 85