Python Hex

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

The hex() function in Python3 is a built-in function that converts a specified integer number into its corresponding hexadecimal form. The function returns a string that contains the prefix '0x' for positive integers and '-0x' for negative integers.

Syntax of hex() Function

Parameters of Python hex() Function

The Python hex() function takes a single argument that must be an integer number.

Return Value of Python hex() Function

The Python hex() function returns a hexadecimal string that contains the prefix '0x' for positive integers, and '-0x' for negative integers.

Errors and Exceptions of Python hex() Function

The hex() function returns TypeError if a non-integer value is passed in place of the parameter.

Working of Python hex() Function

The parameter of the Python hex() function expects an integer value. If the value passed is not a Python int object, it has to define an index() method that returns an integer.

Code

Output

Uses of Python hex() Function

  • The Python hex() function converts an integer number to a lowercase hexadecimal string prefixed with '0x'. Hex() helps in all the standard conversions like
    • decimal to hexadecimal,
    • octal to hexadecimal,
    • binary to hexadecimal, etc.

Code

Output

Examples of Python hex() Function

Implementation of hex() Function

Code

Output

Demonstrating TypeError When Floating Point Values Are Passed as Parameters.

On passing floating point values as parameters, the online Python compiler throws a TypeError. However, this can be modified by using 'float.hex'.

Code

Output

Modified Code

Output

FAQs

Q: What is hex() in Python?

A: The hex() function is an in-built function in Python3 that converts a given number into its hexadecimal value.

Q: How many parameters does the hex() function need?

A: It takes a single argument of integer type.

Q: When does the hex() function throw an error?

A: The hex() function returns TypeError if a non-integer value is passed in place of the parameter.

Q: What do the '0x' and '-0x' indicate?

A: The hexadecimal form of a positive integer and a negative integer has the prefix '0x' and '-0x', respectively.

Conclusion

  • The** hex()** function is an in-built function in Python3 that converts a given number into its hexadecimal value.
  • It takes a single argument and returns a hexadecimal string with '0x' as a prefix for positive integers and '-0x' for negative integers.