Python If Condition Programs | Set 6

Set 1    Set 2    Set 3    Set 4   Set 5  Set 6  Set 7  Set 8  Set 9

Question:26

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
>>>

Question:27

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
>>>

Question:28

Write a python script to take for a 3 digit number , calculate and print sum of 1st and last 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+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
>>>

Question:29

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

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
>>>

Question:30

Write a python script to take for a 4 digit number , calculate and print sum 1st and last digits?

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
>>>

Set 1    Set 2    Set 3    Set 4   Set 5  Set 6  Set 7  Set 8  Set 9