Python hex()

Python hex() builtin function takes an integer and returns its hexadecimal representation in string type.

The hexadecimal representation is in lowercase prefixed with 0x, for example, integer 55 would be returned as 0x37.

In this tutorial, we will learn about the syntax of Python hex() function, and learn how to use this function with the help of examples.

Syntax

The syntax of hex() function is

hex()

where

ParameterRequired/OptionalDescription
xMandatoryAn integer value.

If we do not pass an integer to hex() function, then the function throws TypeError.

Returns

The function returns object of type string.

ADVERTISEMENT

Examples

In this example, we will take an integer value of 55 in x, and pass this integer to hex() function. The function should return the hexadecimal representation of 55 in string format.

Python Program

x = 55
result = hex(x)
print(f'Return value : {result}')
Try Online

Output

Return value : 0x37

Let us now call hex() function, with no integer passed to hex() function.

Python Program

result = hex()
print(f'Return value : {result}')
Try Online

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 1, in <module>
    result = hex()
TypeError: hex() takes exactly one argument (0 given)

Conclusion

In this Python Tutorial, we have learnt the syntax of Python hex() builtin function, and also learned how to use this function, with the help of Python example programs.