Python hex() Function: Use, Syntax, and Examples

Python hex() function: In this tutorial, we will learn about the hex() function in Python with its use, syntax, parameters, returns type, and examples. By IncludeHelp Last updated : June 23, 2023

Python hex() function

The hex() function is a library function in Python, it is used to get the hexadecimal value of a given number, it accepts a number and returns a hexadecimal value (string format). It can be used to convert an integer number to a hexadecimal value.

Syntax

The following is the syntax of hex() function:

hex(number)

Parameter(s):

The following are the parameter(s):

  • number – a valid number to be converted into hexadecimal.

Return Value

The return type of hex() function is <class 'str'>, it returns hexadecimal value in string format of given number.

Python hex() Function: Example 1

# python code to demonstrate example
# of hex() function

num = 0
print("hex value of ", num, " is = ", hex(num))

num = 10
print("hex value of ", num, " is = ", hex(num))

num = 12345
print("hex value of ", num, " is = ", hex(num))

num = -12345
print("hex value of ", num, " is = ", hex(num))

Output

hex value of  0  is =  0x0
hex value of  10  is =  0xa
hex value of  12345  is =  0x3039
hex value of  -12345  is =  -0x3039

Python hex() Function: Example 2

If the value is not a valid integer, the program will return a TypeError. Consider the below program:

# Example to demonstrate the TypeError

x = 10.20
print(hex(x))

Output

Traceback (most recent call last):
  File "/home/main.py", line 5, in <module>
    print(hex(x))
TypeError: 'float' object cannot be interpreted as an integer


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.