Q. Write a program that:
(a). Prompt the user for a string.
(b). Extract all the digit from the string.
(c). If there are digits:
(i). Sum the collected digits together.
(ii). Print out:
(1). The original string
(2). The digits
(3). The sum of the digits
(d). If there are no digits: Print the original string and massage "has no digit".
You can understand by Watching video :-
Answer :-
a = input("Enter a string = ") sum = 0 digit = "" for i in a : if i.isdigit() : sum += int(i) digit += i if sum == 0 and len(digit) == 0: print(a, "has no digit") else : print("Original string = ", a) print("Digits are ", digit) print("Sum of all digit = ", sum)
Output :-
Enter a string = abc000
Original string = abc000
Digits are 000
Sum of all digit = 0
>>>
Enter a string = Path058 Walla93
Original string = Path058 Walla93
Digits are 05893
Sum of all digit = 25
>>>
If we give input as abc00, then it will give string has no digit but we have digit zero. In that case program will not give correct output.
ReplyDeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )