3

I've been trying to understand if it is possible to use an if statement similar to the likes of what I have demonstrated here below. It is my understand that it is not?

for i in range(10):
  if i == (3 or 5) or math.sqrt(i) == (3 or 5):
    numbers.append(i)

With this block of code I only get the numbers 3 & 9, while I should be getting 3, 5, 9. Is there another way of doing so without listing the code below?

for i in range(10):
  if i == 3 or i == 5 or math.sqrt(i) == 3 or math.sqrt(i) == 5:
    numbers.append(i)
Georgy
  • 12,464
  • 7
  • 65
  • 73
Revaliz
  • 33
  • 3

5 Answers5

6

You can use in operator:

for i in range(10):
  if i in (3, 5) or math.sqrt(i) in (3, 5):
    numbers.append(i)

or in case you expect each of the calculations to be in the same group of results, you can use any()

results = [1, 2, ..., too long list for single line]
expected = (3, 5)

if any([result in expected for result in results]):
    print("Found!")

Just a minor nitpick, sqrt will most likely return a float sooner or later and this approach will be silly in the future, therefore math.isclose() or others will help you not to encounter float "bugs" such as:

2.99999999999999 in (3, 5)  # False

which will cause your condition to fail.

Peter Badida
  • 11,310
  • 10
  • 44
  • 90
4
if i == (3 or 5) or math.sqrt(i) == (3 or 5):

is equivalent to

if i == 3 or math.sqrt(i) == 3:

leading to 3 and 9 as results.
This because 3 or 5 is evaluated as 3 by being 3 the first non-zero number (nonzero numbers are considered True). For instance, 0 or 5 would be evaluated as 5.

abc
  • 11,579
  • 2
  • 26
  • 51
2

What I would recommend is instead of using "==" here, that you use "in". Here is that code:

for i in range(10):
  if i in [3,5] or math.sqrt(i) in [3,5]:
    numbers.append(i)
Keith Galli
  • 161
  • 2
0

You can do it using list comprehension like this.

import math as mt
a=list(range(10))
filtered_list=[x for x in a if x in [3,5] or mt.sqrt(x) in [3,5]]
print(filtered_list)
Kaustubh Lohani
  • 635
  • 5
  • 15
0

There is one:

if i in (3,5) or math.sqrt(i) in (3,5):
Adnan Temur
  • 333
  • 1
  • 10
  • 1
    This would be a better answer if you explained how the code you provided answers the question. – pppery Jun 17 '20 at 00:51