×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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

By IncludeHelp Last updated : December 07, 2024

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
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement



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