Articles

Python program to convert decimal to hexadecimal using while loop

Python program to convert decimal to hexadecimal using while loop


In this python programming guide, we are going to learn

  • program to convert decimal to hexadecimal in python

Program to convert a decimal number to hexadecimal in Python

The python program to convert decimal to hexadecimal using while loop is as follows:

# Owner : TutorialsInhand Author : Devjeet Roy

def decimal_to_hexadecimal(n):
    result = list()
    while n:
        res = n % 16
        n = n // 16
        if res < 10:
            result.append(res)
        else:
            result.append(chr(res+55))
    return result[::-1]


if __name__ == "__main__":
    number = int(input("Enter a number: "))
    ans = decimal_to_hexadecimal(number)
    for i in ans:
        print(i, end="")

The output of python program to convert decimal to hexadecimal using while loop is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter a number: 123
7B

Few important points about this program

1. First we ask the user to enter a number and we convert it to integer data type.

2. Then we call the decimal_to_hexadecimal function which divides the number by 16 and makes it the new number and store the remainders in a list. Finally, we return the list in reversed format.

3. The chr() method is used to get a character,if the provided argument is its ASCII value.

4. In the main body, we have just printed the list elements.

 

Write a python program to convert decimal to hexadecimal snapshot:

write a python program to convert decimal to hexadecimal

 


Python Conversion Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Data Science Enthusiast
Page Views :    Published Date : Mar 30,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!