2

I have multiple quantity input fields, which only allows positive integer values, on a web page.

My first code looks like this:

quantities = []
for form in forms:
    qty= form.cleaned_data['qty']
    if qty:
        quantities.append(qty)
if not quantities:
    raise forms.ValidationError("You didn't choose any books")

After reviewing my code, I found a shorter version:

if not any([form.cleaned_data['qty'] for form in forms]):
    raise forms.ValidationError("You didn't choose any books")

Will this always work? Does every integer evaluate to True except 0?

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Nepo Znat
  • 3,000
  • 5
  • 28
  • 49
  • 1
    What happened when you tested it? What did you find when you researched the truth values of numbers? – Prune Jun 14 '18 at 20:42
  • It worked after testing it, I've searched for this type of question but I couldn't find a specific answer to my question because this also relates to the any() function of python. – Nepo Znat Jun 14 '18 at 20:44
  • Specifically see [this answer](https://stackoverflow.com/a/39984051/5858851) (the upvoted one, rather than the accepted one). – pault Jun 14 '18 at 20:45
  • Keep in mind that "nonzero" and "positive" are completely different things. – user2357112 Jun 14 '18 at 20:48

2 Answers2

4

Generally, yes.

Unless specially defined, most objects in python are considered True.

See source & exceptions below:

4. Built-in Types (Python 3 documentation)

4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

Constants defined to be false:

None and False.

zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated.

(Important exception: the Boolean operations or and and always return one of their operands.)

Community
  • 1
  • 1
Alex Ulyanov
  • 329
  • 3
  • 8
0

Given integers (ints) as your domain, the answer is yes. The only falsy integer value in Python is 0. All other integers are True when evaluated as a bool.

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
  • Although everything you said true, Alex answer is better: a) it directs to documentation, b) it answers "Why the only falsy integer value in Python is 0". And you just state it as Holy Truth – Alex Yu Jun 14 '18 at 20:51