Python Numbers

Table of Contents

Python Number Datatype

In Python number data type objects store numeric data
Python supports the following numeric data types

  • int (signed integers, binary, octal and hexadecimal) - whole number, positive or negative, without decimals, of unlimited length
  • float (floating point values ) - positive or negative, containing one or more decimals
  • complex (complex numbers) - written with a "j" as the imaginary part

Numeric types are created by assigning numeric values to the variables
Examples

x = 10  # int
y = 7.5 # float
z = 2j  # complex


 

More Examples

# Decimal literals
x = 400
z = 2652565188198713537826762234234234 # very long numbers are integers
k = -30 # negative numbers

# Binary literals
bin1 = 0b1101   # starts with 0b (zero b)

# Octal literals
oct1 = 0o234    # starts with 0o (zero and "o" )

#   Hexadecimal literals
hex1 = 0x14b     # starts with 0x (zero and ex )

#   Floats
float_literal1 = 34.12
float_literal_neg = -46.09
#   Float can also be scientific numbers with an "e" to indicate the power of 10.
float_literal2 = 65e3
float_literal3 = 23E4

#   Complex Number
c = 5.23j

print(x, type(x))
print(bin1, type(bin1))
print(oct1, type(oct1))
print(hex1, type(hex1))
print(float_literal1, type(float_literal1))
print(c, type(c))
400 <class 'int'>
13 <class 'int'>
156 <class 'int'>
331 <class 'int'>
34.12 <class 'float'>
5.23j <class 'complex'>

The Binary, Octal and Hexadecimal literals are converted to integer type when printed

 

Numeric Operations

The operators +, -, * and / can be used to do various operations on the numbers

>>> 3 + 3
6
>>> 60 - 5*6
30
>>> (60 - 5*6) / 4
7.5
>>> 18 / 5  # division always returns a floating point number
3.6

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description