1. Python integer values
In Python, an int
or integer is:
- a whole number without decimal
- positive, negative or zero
- of unlimited length
- may contain underscores to improve readability
x = 10 y = 12345678987654321 z = 12_34_56 print(x) # 10 print(y) # 12345678987654321 print(z) # 123456
2. Integers can be octal and hex
In python, we can represent the integers in the octal or hexadecimal representation also.
- Octal and hexadecimal numbers can be negative, but cannot be written in the exponential form.
- Octals are prefixed with
'0o'
(zero followed by the letter “o”) and contains digits from 0 to 7. - Hexadecimals prefixed with
'0x'
(zero followed by the letter “x” – uppercase or lowercase) and contains digits from 0 to 9 or letters from A to F (uppercase or lowercase).
octalInt = 0o22 hexInt = 0xAA print(octalInt) # 18 print(hexInt) # 170
3. Arithmetic operations
3.1. Addition, subtraction, multiplication and devision
These operations are pretty much similar to other languages.
The standard operation of division, which is performed by the
/
operator, generally returns a floating-point result. Use the floor division operator//
to remove the digits after the decimal point.
x / y
: returns quotient of x and yx // y
: returns (floored) quotient of x and yx % y
: remainder of x / ydivmod(x, y)
: the pair (x // y, x % y)
x = 22 y = 5 print (x + y) # Prints 27 print (x - y) # Prints 17 print (x * y) # Prints 110 print (x / y) # Prints 4.4 print (x // y) # Prints 4 print (x % y) # Prints 2 print ( divmod(x, y) ) # Prints (4, 2)
3.2. Increment and decrement
- Increment
(+=x)
addsx
to the operand. - Decrement
(-=x)
subtractsx
to the operand.
x = 10 y = 10 x += 1 print (x) # Prints 11 x += 5 print (x) # Prints 16 y -= 1 print (y) # Prints 9 y -= 5 print (y) # Prints 4
3.3. Exponent
Exponential calculation is possible using **
operator.
x = 10 y = 2 print (x ** y) # Prints 100
4. isinstance to check type
If you want to verify if an integer belongs to the class int you can use isinstance
.
x = 10 print( isinstance(x, int) ) # Prints True
5. Convert Integer to String
Use string constructor str()
.
x = 10 valueOfX = str( x ) # '10'
6. Convert String to Integer
Use integer constructor int()
.
valueOfX = '10' x = int( valueOfX ) # 10
Happy Learning !!
Leave a Reply