Python Forum

Full Version: int(variable) not changing variable to an integer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
For whatever reason the below code runs the command int(ans), but ans is not an integer when checked.
def intCheck(num):
    try:
        int(num)
        return True
    except:
        return False

def redo():
    ans = input('Input an integer: ')

    if intCheck(ans) == True:
        int(ans)
        print('Answer has been turned into an integer')
    else:
        print('You did not input an integer')

    if isinstance(ans, int):
        print('\nIt worked')
        redo()
    else:
        print("\nIt didn't work")
        redo()

redo()
This code also doesn't work, so the check can't be the problem.
ans = '1'
int(ans)

if ans == 1:
    print('It worked')
else:
    print("It didn't work")
The only other thing I can think of is ans might be a prohibited variable name, but I've changed it and the code still doesn't work.
I'm using python 3.6.3. Would appreciate any help if you know what's wrong, thanks. Smile
If you want to turn ans into an integer, you need to write
ans = int(ans)
However, why not simply write
try:
    ans = int(ans)
except TypeError:
    print("You didn't enter an integer.")
else:
    print("You entered an integer.")
? This avoid a type-checking function.
Thank you, completely forgot about that.

(Jan-11-2018, 10:28 AM)Gribouillis Wrote: [ -> ]However, why not simply write
try:
    ans = int(ans)
except TypeError:
    print("You didn't enter an integer.")
else:
    print("You entered an integer.")
? This avoid a type-checking function.

That works just as well, I've gotten into the habit of making a function in case I want to check multiple times. I just find it easier.