Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this variable declaration works in python?

i = 0x0800

What I understand here is that 0x0800 is a hexadecimal number where '0x' denotes the hex type and the following number '0800' is a 2 byte hexadecimal number. On assigning it to a variable 'i', when its type is checked I got this error

>>> type(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Here I make out that 'i' is suppose to be an int object. I got more confused when I tried this

>>> print i
2048

What is '2048' exactly .. Can anyone throw some light here ?

like image 443
harveyD Avatar asked Feb 22 '26 09:02

harveyD


1 Answers

i is an integer, but you redefined type:

>>> i = 0x0800
>>> i
2048
>>> type(i)
<type 'int'>
>>> type = 42
>>> type(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(i)
<type 'int'>

Note the type = 42 line; I created a new global name type and that is found before the built-in. You could also use import __builtin__; __builtin__.type(i) in Python 2, or import builtins; builtins.type(i) in Python 3 to access the original built-in type() function:

>>> import __builtin__
>>> type = 42
>>> __builtin__.type(type)
<type 'int'>
>>> type(type)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del type
>>> type(type)
<type 'type'>

The 0x notation is just one of several ways of specifying an integer literal. You are still producing a regular integer, only the syntax for how you define the value differs here. All of the following notations produce the exact same integer value:

0x0800          # hexadecimal
0o04000         # octal, Python 2 also accepts 0400
0b100000000000  # binary
2048            # decimal

See the Integer Literals reference documentation.

like image 188
Martijn Pieters Avatar answered Feb 23 '26 22:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!