Write A Python Function That Accepts A String And Calculate The Number Of Digits And Letters

Hi, in this article let's learn a Python program that accepts a string and calculates the number of digits and letters present in the string.  This task you have to perform using a python function and print the count of digits and letters present in the string.

Let's use basic  python for loops and if statements to solve this.

 

Write A Python Function That Accepts A String And Calculate The Number Of Digits And Letters

 

 
Write A Python Function That Accepts A String And Calculate The Number Of Digits And Letters

Let's define a function named calculate() and pass string as an input argument to the Python function.  Now let's declare two counter variables to count the number of digits as well as letters present in a string and initialize it to zero.

Use the for loop to iterate all the letters present in the string,  and use the if statement to check if the letter is between 0 to 9 then increment the  digit count.

In the else if block check if the letter is between a to z/ or between A to Z, If so increment the letter count.  Once the for loop complete print the digit count and letter count

def calculate(data):
   digit_count, letter_count = 0, 0
   for letter in data:
       if "0" <= letter <= "9":
           digit_count += 1
       elif "a" <= letter <= "z" or "A" <= letter <= "Z":
           letter_count += 1
   print("Digit Count is : ", digit_count)
   print("Letter Count is : ", letter_count)





In the main program take a string variable named as text and ask a user to enter a string using the input function call.  then call the calculate function by passing the given  input string  and print the result.

text = input("Enter a string : ")
calculate(text)





Python Code
==================

def calculate(data):
   digit_count, letter_count = 0, 0
   for letter in data:
       if "0" <= letter <= "9":
           digit_count += 1
       elif "a" <= letter <= "z" or "A" <= letter <= "Z":
           letter_count += 1
   print("Digit Count is : ", digit_count)
   print("Letter Count is : ", letter_count)


text = input("Enter a string : ")
calculate(text)





Output
============
Enter a string : 98765
Digit Count is :  5
Letter Count is :  0





Output
================
Enter a string : Hello
Digit Count is :  0
Letter Count is :  5





Output
=================
Enter a string : Call@123
Digit Count is :  3
Letter Count is :  4





Conclusion
=====================
Execute the above python script by providing the random string as an input during the run time,  not down the results.

comment it down below if you have any suggestions to improve the above Python program

Post a Comment

0 Comments