Finding the greatest digit in a number using python

This tutorial will help us find the greatest digit in a number in Python. We are going to learn to code this concept in two ways.

Read the entire post to learn both the methods in the easiest way possible.

GREATEST DIGIT IN A NUMBER in Python

First, we will learn the simplest method i.e. using lists. Let us begin:

We will take user input (say num) of the number the user wants to find the greatest digit. Then we will make a list named say ‘l’, and we will store the value of ‘num’ in it. In the next line, we can then use ‘max()’ to get the greatest digit of the number from the list. List comprehension is used to get the string(num) stored in the list.

 

List Comprehension

num=(input("Enter Number: "))
l=list(num)
max(l)

 

Secondly, we will learn the mathematical concept. Let us begin.

We will take user input (say num) of the number the user wants to find the greatest digit. We will then use ‘len()’ function to calculate the length of num. We will store the length in a variable say ‘z’, then we will run a loop till the length of the string. Inside the loop we will check the conditions:

  • num%10 gives the remainder and if it is greater than ‘y’ then the value gets stored in ‘y’.
  • And then we will keep removing the last digit from the number(num) by integral division by 10.
  • Else condition will run when the remainder is not greater than the value stored in y and it will simply deduce the number.
num=(int)(input("Enter Number: "))
z=len(str(num))
y=0
for x in range(z):
    if(num%10>y):
        y=num%10
        num=num//10     
    else:
       num=num//10   
print(y)

I hope you have understood the concept clearly and can apply it in future usage.

Leave a Reply

Your email address will not be published. Required fields are marked *