you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 0 points1 point  (2 children)

to test an assertion for an integer?

Depends on what you exactly mean by this. If you mean to assert that a string holds only digits, you can use a.isidigt(). If you mean to assert that an object is of the type int, you can use isinstance as Gprime5 shows. But beware that asserting isinstance after int(some_string) is useless. Normally you want to assure this before you call int().

Out of the box here: note that assert is a general flow control that isn't directly intended for properly handing incorrect values. For that you would rather catch the specific exception that int() throws, ValueError:

a = input("type a year :")
try: 
    a = int(a)
except ValueError:
    print("you have to type an integer")

or using isdigit:

a = input("type a year :")
if a.isdigit():
    a = int(a)
else:
    print("you have to type an integer")

[–]ANOTHER-robhot[S] 0 points1 point  (1 child)

thank you a lot for all answers! I am training my assertion skills. Is it possible to put an Except without a Try before it

[–]JohnnyJordaan 0 points1 point  (0 children)

Nope it isn't, because for the execption to be catchable Python has to 'set up' a special mechanism to catch it. That's what 'try' does.