Remember
hex() returns a string with an integer’s hexadecimal representation, including a 0x prefix.
hex() returns a string with an integer’s hexadecimal representation, including a 0x prefix.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
number = 15
print(hex(number))Top-level scope
15hex() returns a string with an integer’s hexadecimal representation, including a 0x prefix.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
number = 15
print(hex(number))
|
v
DISPLAYED RESULT
0xf
FINAL BINDINGS
number --> object 1 (int)
object 1: 15Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
number = 15
print(hex(number))Top-level scope
15The example has finished. Compare the final output with the values and references above.
0xf
What do you expect this program to print?
number = 15
print(hex(number))hex() FunctionThe hex() function in Python is used to convert an integer number to a hexadecimal string (base 16), prefixed with 0x.
This is useful when working with colors, memory addresses, or binary data formats.
hex(number)
number – A valid integer (positive or negative)'0x' followed by the hexadecimal equivalent of the integer.print(hex(255))
0xff
print(hex(-42))
-0x2a
Each color component in an RGB color code is often represented in hexadecimal:
r = 255
g = 165
b = 0
hex_color = f"#{hex(r)[2:]}{hex(g)[2:]}{hex(b)[2:]}"
print(hex_color)
#ffa500
Note: [2:] is used to remove the '0x' prefix.
hex(3.14) will raise TypeErrorhex("10") is invalidint() if neededIn interviews, hex() is often used in bit manipulation or encoding problems. Know how to combine it with int(), bin(), or ord().
hex() converts an integer to a base-16 (hexadecimal) string'0x' for positive or '-0x' for negativeWrite a program that reads an integer from the user and prints its hexadecimal equivalent.
num = int(input("Enter an integer: "))
print("Hexadecimal:", hex(num))
Connect what you noticed in the example with the idea below.
hex() returns a string with an integer’s hexadecimal representation, including a 0x prefix.
hex() modifies the integer into text in place.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.