0

Im practicing with some simple problems and using try and exceptions, I have done one below where I want to raise an exception if an int is entered instead of a str put it never seems to raise the exception. When I do it the other way round and want to raise an exception when a str is entered instead of an int it works fine though, what am I doing wrong here? Is there a different exception I should be raising in the first problem instead of ValueError?

def is_vowel():

    vws = 'aeiou'

    try:
        x = str(raw_input("Please enter a single letter: "))
        for i in vws:
            if x == i:
                print x +" is a vowel"

    except ValueError:
        print "Error message here"


is_vowel()

this one below works as Id expect

def is_int():

    ints = [1,2,3,4]

    try:
        y = int(raw_input("Please enter a single number"))
        for i in ints:
            if y == i:
                print str(y) + " is a number"

    except ValueError:
        print "Please enter a number only"
is_int()
easy_c0mpany80
  • 327
  • 1
  • 7
  • 18
  • 1
    raw_input() always returns a string. So if you enter '1', it will give you the string "1". Which obviously would not fail if you try to cast it to a string. You'll have to write your own function for determining if something is an int, and raise an exception manually. Or raise an exception if casting to an int *doesn't* fail. See http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python for pointers. –  Jan 17 '16 at 03:12
  • Just a tip, why not use if `y in ints` or `x in vws` rather than having to loop over all your items? – Zer0 Jan 17 '16 at 05:07

2 Answers2

1

Think of it this way: the sequence of bytes representing the characters '1' then '2' then '3' can be interpreted as a string ("123") or as an integer (123). So, taking any input that is a valid integer, and treating it as a string, will succeed.

On the other hand, the sequence of bytes "123" can be converted to a number, but the sequence of bytes "xyzzy" cannot. So, if you try to convert "xyzzy" to an integer, you'll get a ValueError.

Chris Jaekl
  • 166
  • 1
1

Because raw_input will return your input as a string to str, which will not cause any error. However, int can only transfer a numeric format string to an integer.

raw_input(...)
raw_input([prompt]) -> string

Read a string from standard input.
YCFlame
  • 1,251
  • 1
  • 15
  • 24