I was just wondering why when I take an integer of a string like int('string') why you recieve a value error in python 3.2 and not a type error. I see the definition of a type error is defined on the python site as the follows: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
isn't int the operator and the string is the inappropriate type? When I do this I receive a ValueError and do not understand the reason for this.
Here is the code So when i instantiate the class with a rank that has a string to try and purposely get an error I receive a valueerror and not a type as I would expect.
class Card:
#attributes
list_rank= ["","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
list_suit={"d":"diamonds","c":"clubs","h":"hearts","s":"spades"}
#initialize rank and suit
def __init__(self,rank,suit):
self.rank=int(rank)
self.suit=suit
#return the rank of the card
def getRank(self):
return(self.list_rank[self.rank])
#return the suit of the card
def getSuit(self):
return(self.list_suit[self.suit])
#value of the cards
def bjValue(self):
if(self.rank<10):
return(self.rank)
else:
return(10)
#return the rank and suit of the card
def __str__(self):
return (self.list_rank[self.rank]+" of "+self.list_suit[self.suit])
To understand the difference you must understand the difference between type and value. The type of "abc" is string, which you can check by running
type("abc") # -> string
The value of the literal "abc" is simply the value itself. If you had an expression like "ab" + "c" the value would also be "abc".
That's why you get the ValueError and not a TypeError; int expects a string, which you gave it - so it's the correct type - but the value has to be something that can be interpreted as an integer and "abc" is not an integer obviously.
To try this out, see the difference between:
int('abc')
# throws:
# ValueError: invalid literal for int() with base 10: 'abc'
and
int(None)
# throws:
# TypeError: int() argument must be a string or a number, not 'NoneType'
The fact that "abc" doesn't immediately look like an integer doesn't stop us from interpreting it as one, however. In a different base it could still be interpreted as a number.
For example: binary numbers, as you probably know, only use 0s and 1s, and hexadecimal numbers are usually represented using the digits 0 - 9 and the letters a - f. The int function takes an optional argument that tells it which base to use, so if we try interpreting "abc" again but as a hexadecimal number, we get:
int('abc', base=16)
# returns 2748
because int() accepts a string as a parameter for example int('1') will ouptut 1. so '1' is an appropriat value but 'a' is not
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With