-1

I have a function that receives a string argument and condition inside this function that checks if this argument is int or float. Although the outcome of this condition is false, the following line is still executed.

I use PyCharm IDE and Python 3.8

Here is the code.

number1 = 17
number2 = 17.1
testStr = "Test string"


def define_type(argument01):
    if type(argument01) == str:
        print(argument01 + " - string")
    if type(argument01) == int or float:
        print(str(argument01) + " - int or float")


define_type(testStr)

The output:

Test string - string
Test string - int or float

Process finished with exit code 0
Seeker001
  • 99
  • 1

1 Answers1

1
if type(argument01) == int or float:

can be rewritten

if (type(argument01) == int) or float:

so even argument01 is not an int the test is always true, in a way your test is

if float:

You want :

if type(argument01) == int or type(argument01) == float:
bruno
  • 32,421
  • 7
  • 25
  • 37
  • 1
    It works! Thank you. But why "if float:" is a valid conditional? It doesn't mean anything. Does it? – Seeker001 Apr 18 '20 at 07:26
  • @Seeker001 yes, and because *float* is not *false* then it is true. An empty string is considered false, a non empty is considered true, same for set and array, etc. Python is very practical and follow 'common sense' – bruno Apr 18 '20 at 07:27
  • 1
    @Seeker001 Hope this helps: [What are the true and false criteria for a python object?](https://stackoverflow.com/a/43692661/1589191) – Emil M George Apr 18 '20 at 08:03
  • @EmilMGeorge for sure it is a good link – bruno Apr 18 '20 at 08:33