0

So, the problem is write a void function which takes a 4 digit number and add the square of first two digit and last two digit.

and my solution is

def add():
print("Enter a 4 Digit number")
num = int(input())
if 999 < num < 10000:
    c = int(num[0:2])
    d = int(num[2:4])
    e = (c ** 2) + (d ** 2)
    print(e)
else:
    print("Enter a valid number")

add()

#it shows error: 'int' object is not subscriptable

  • Quick n Dirty answer - you need to convert int to a string then slice it before converting back to int. As per https://stackoverflow.com/questions/41271299/how-can-i-get-the-first-two-digits-of-a-number/41271341 – jimi2shoes Apr 15 '21 at 06:32

2 Answers2

0

This should work

def add():
    print("Enter a 4 Digit number")
    num = int(input())
    if 999 < num < 10000:
        c = int(str(num)[0:2]) #You first need to convert it into str
        d = int(str(num)[2:4]) #Same here
        e = (c ** 2) + (d ** 2)
        print(e)
    else:
        print("Enter a valid number")
add()
CopyrightC
  • 857
  • 2
  • 7
  • 15
0

You must know integer cannot be sliced. So, you need to convert it into string again like below code

def add():
print("Enter a 4 Digit number")
num = int(input())
if 999 < num < 10000:
    num = str(num)    # change made to your existing code
    c = int(num[0:2])
    d = int(num[2:4])
    e = (c ** 2) + (d ** 2)
    print(e)
else:
    print("Enter a valid number")
Msvstl
  • 1,116
  • 5
  • 21