Int object not subscriptable?

Viewed 50

enter image description here

Hi there,

I'm having problem with a coding practice question where I have to create a function that adds the first digit of two numbers. In this function, I try to do num1[0] and num2[0] to get the first digit of each number and then convert it into an integer, but I always get told that int is not subscriptable. What's wrong here?

def get_funny_sum(num1, num2):
 num1 = int(num1[0])
 num2 = int(num2[0])
 sum = num1 + num2
 return sum

For this exercise, I do not to do the get_funny_sum() part, just the def get_funny_sum() part.

enter image description here

1 Answers

Subscriptable means that the object implements the __getitem__() method. In other words, it is for objects that are "containers" of other objects; such as strings, lists, tuples, or dictionaries.

A number cannot be accessed this way, you can try to convert it to a string, then access the first location and then convert it back to int for the sum operation, which is a little overcomplicated:

def get_funny_sum(num1, num2):
    num1 = str(num1)
    num2 = str(num2)
    acc = int(num1[0]) + int(num2[0])
    return acc

print(get_funny_sum(23, 45))

Or try to execute a division by powers of ten to get the proper digit that you want

Related