Number to Hex

Beginner

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.

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.