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 = 10y = 12345678987654321z = 12_34_56print(x) # 10print(y) # 12345678987654321print(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 = 0o22hexInt = 0xAAprint(octalInt) # 18print(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 = 22y = 5print (x + y) # Prints 27print (x - y) # Prints 17print (x * y) # Prints 110print (x / y) # Prints 4.4print (x // y) # Prints 4print (x % y) # Prints 2print ( divmod(x, y) ) # Prints (4, 2) |
3.2. Increment and decrement
- Increment
(+=x)addsxto the operand. - Decrement
(-=x)subtractsxto the operand.
x = 10y = 10x += 1print (x) # Prints 11x += 5print (x) # Prints 16y -= 1print (y) # Prints 9y -= 5print (y) # Prints 4 |
3.3. Exponent
Exponential calculation is possible using ** operator.
x = 10y = 2print (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 = 10print( isinstance(x, int) ) # Prints True |
5. Convert Integer to String
Use string constructor str().
x = 10valueOfX = str( x ) # '10' |
6. Convert String to Integer
Use integer constructor int().
valueOfX = '10'x = int( valueOfX ) # 10 |
No comments:
Post a Comment
Note: only a member of this blog may post a comment.