0

I am new at Python and in this below function i am trying to do some validation process.

def countUpToTen(counter):
    if type(counter) is not int or counter == None:
        print("Invalid parameter!")
    if counter > 10:
        print("Counter can not be greater than 10!")
        return False
    else:
        count = 1
        while (count <= counter):
           print 'The count is:', count
           count = count + 1
        print("Done counting !")

countUpToTen("0s")

But when i call it like countUpToTen("0s") it prints Invalid parameter! and Counter can not be greater than 10! but i expect just Invalid parameter!. I dont know how it compares a string with a number in second if statement. Any help would be appriciated.

Tartar
  • 5,149
  • 16
  • 63
  • 104

2 Answers2

2

You are not exiting the function after printing the first error message.

In Python 2, you can still compare strings and integers, with numbers always lower than anything else (except None), so the second if statement also matches:

>>> '0s' > 10
True

Python 3 does away with supporting comparisons between arbitrary types and comparing int with str raises an exception instead.

In this case, you should use return to exit the function early when the parameter is invalid:

if type(counter) is not int or counter == None:
    print("Invalid parameter!")
    return

Note that the Pythonic way to test for a type is to use isinstance(). You should test for None using the is identity test as None is a singleton object, but the test is redundant here; if counter is None it is not an instance of int either. The following suffices:

if not isinstance(counter, int):
    print("Invalid parameter!")
    return

Instead of returning early, consider using elif for the next test:

if not isinstance(counter, int):
    print("Invalid parameter!")
elif counter > 10:
    print("Counter can not be greater than 10!")
else:
    # etc.

Note that you are almost certainly using Python 2 and thus using too many parentheses. print in Python 2 is a statement, not a function, and using parentheses anyway can lead to you trying to print tuples:

>>> print('This is a tuple', 'with two values')
('This is a tuple', 'with two values')
>>> print 'This is just', 'two values'
This is just two values

You probably already discovered this because you are using print with two arguments and no parentheses in one location already.

The test for your while loop also doesn't need to use parentheses:

while count <= counter:

Instead of using while and incrementing count manually, just use a for loop and range():

if not isinstance(counter, int):
    print "Invalid parameter!"
elif counter > 10:
    print "Counter can not be greater than 10!"
else:
    for count in range(1, counter + 1):
       print 'The count is:', count

The latter loop can also be written as:

for count in range(counter):
   print 'The count is:', count + 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You could rewrite the if/else statements slightly to make it an if/elif/else construct:

def countUpToTen(counter):
    if type(counter) is not int or counter == None:
        print("Invalid parameter!")
    elif counter > 10:
        print("Counter can not be greater than 10!")
        return False
    else:
        count = 1
        while (count <= counter):
            print 'The count is:', count
            count = count + 1
        print("Done counting !")

countUpToTen("0s")

This would also give the output you expect.

Mike Driscoll
  • 32,629
  • 8
  • 45
  • 88