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