-4

I am doing a simple program just to the program say if a number is even or not and to when the raw_input isn't a number, the program will complain about it:

def f():
    t = raw_input('Enter a number and we will send an inormation: ')


if t != type(int):
    print 'is this a number?'

elif int(t) % 2 == 0:
    print t
    print 'it is an even number'

elif int(t) % 2 > 0:
     print t
     print 'it is an odd number'

else:
     print '???'

but when the program run it returns ONLY the if condition (when i write 90 or a word it returns 'is this a number?'. it should only return this if I Write a string). And I can't figure out where is the problem.

vaultah
  • 44,105
  • 12
  • 114
  • 143
jfinizolas
  • 23
  • 3

3 Answers3

1

Many errors here.

First, use isintance to test if a variable is an int. Do not use type(t) != int.

Then you do the int(t) operation multiple times.

In addition, it seems that t is a global var, which is not recommended to use, especially for beginners.

Last you have a else at the end but a number is odd or even. There is no other alternatives. To test is a number is odd use if t & 1:.

Julien Goupy
  • 165
  • 6
  • sorry, I am just a noob (I am programing just since the beginning of the month), so i don't know very much about python , I don' even know what's a isintance – jfinizolas Jun 18 '16 at 12:37
  • `isinstance` should not be used to check if input type as `raw_input` will always give a string – formatkaka Jun 18 '16 at 12:39
  • Yes but then the question here is for when we want to check the `raw_input` directly. As the OP says he is newbie I suggested this. – formatkaka Jun 18 '16 at 12:41
0

You can use if t.isdigit():

type(int) returns the type of the object which will never be a value. So it will always be false.

formatkaka
  • 1,278
  • 3
  • 13
  • 27
0

This is caused by the fact that raw_input always returns a string, even if there is only numbers used. You need to type cast it as int and then check if it is odd or even, and catch an exception if it is not able to be converted to int. This is how you should do it:

def f():
    try:
        t  = int(raw_input("Enter a number"))
    except ValueError:
        print "is this an integer?"
    else:
        if t % 2 == 0:
            print t
            print " is even"
        else:
            print t
            print " is odd"

The else after the except block only runs if the exception is not thrown. Also, as @Julien Goupy says, the number is either odd or even, so you don't need the third else statement Edit: It seems that elif after the try...except block does not work, so I have changed it to else

masteryoom
  • 81
  • 6