Number to Hex

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can easily convert a decimal number to its hexadecimal equivalent using the hex() function. In this challenge, you will be asked to write a function that takes a decimal number as an argument and returns its hexadecimal representation.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13732{{"`Number to Hex`"}} python/function_definition -.-> lab-13732{{"`Number to Hex`"}} python/build_in_functions -.-> lab-13732{{"`Number to Hex`"}} end

Number to Hex

Write a function to_hex(dec) that takes a decimal number as an argument and returns its hexadecimal representation. Your function should perform the following steps:

  1. Use hex() to convert the decimal number to its hexadecimal equivalent.
  2. Return the hexadecimal representation.
def to_hex(dec):
  return hex(dec)
to_hex(41) ## 0x29
to_hex(332) ## 0x14c

Summary

In this challenge, you learned how to convert a decimal number to its hexadecimal equivalent using the hex() function in Python. You also wrote a function that performs this conversion.

Other Python Tutorials you may like