Python Tutorial @ Home

# Python If Condition Programs | Set 6

## Write a python script to take for a 2 digit number , calculate and print sum of the digits?

### Sol:

```n=int(input("Enter a 2 digit no "))
if(n>=10 and n<=99):
d1=n%10
n=n//10
d2=n%10
s=d1+d2
print("Sum = ",s)
else:
print("Invalid number, enter 2 digit no")```

## Output:

Enter any no 25
Sum = 7
>>>
Enter any no 256
Invalid number, enter 2 digit no
>>>

## Write a python script to take for a 3 digit number , calculate and print sum of the digits?

### Sol:

```n=int(input("Enter a 3 digit no "))
if(n>=100 and n<=999):
d1=n%10
n=n//10
d2=n%10
n=n//10
d3=n%10
s=d1+d2+d3
print("Sum = ",s)
else:
print("Invalid number, enter 3 digit no")```

## Output:

Enter any no 123
Sum = 6
>>>
Enter any no 25
Invalid number, enter 3 digit no
>>>
Enter any no 1452
Invalid number, enter 3 digit no
>>>
Enter any no 652
Sum = 13
>>>

## Sol:

```n=int(input("Enter a 3 digit no "))
if(n>=100 and n<=999):
d1=n%10
n=n//10
d2=n%10
n=n//10
d3=n%10
s=d1+d3
print("Sum of 1st and last digits = ",s)
else:
print("Invalid number, enter 3 digit no")```

## Output:

Enter any no 25
Invalid number, enter 3 digit no
>>>
Enter a 3 digit no 123
Sum = 4
>>>

## Sol:

```n=int(input("Enter a 4 digit no "))
if(n>=1000 and n<=9999):
d1=n%10
n=n//10
d2=n%10
n=n//10
d3=n%10
n=n//10
d4=n%10
s=d1+d2+d3+d4
print("Sum = ",s)
else:
print("Invalid number, enter 4 digit no")```

## Output:

Enter a 4 digit no 1234
Sum = 10
>>>
Enter a 4 digit no 125
Invalid number, enter 4 digit no
>>>
Enter a 4 digit no 25
Invalid number, enter 4 digit no
>>>
Enter a 4 digit no 2541
Sum = 12
>>>

## Sol:

```n=int(input("Enter a 4 digit no "))
if(n>=1000 and n<=9999):
d1=n%10
n=n//1000
d2=n%10
s=d1+d2
print("Sum of 1st and last digits = ",s)
else:
print("Invalid number, enter 4 digit no")```

Output:

Enter a 4 digit no 1234
Sum of 1st and last digits = 5
>>>
Enter a 4 digit no 14
Invalid number, enter 4 digit no
>>>
Enter a 4 digit no 25
Invalid number, enter 4 digit no
>>>
Enter a 4 digit no 125
Invalid number, enter 4 digit no
>>>
Enter a 4 digit no 4523
Sum of 1st and last digits = 7
>>>

Important Pages