In Python, numbers are a core data-type essential for performing arithmetic operations and calculations. Python supports three types of numbers, including integers, floating-point numbers and complex numbers. Here’s an overview of each:
Python
a = 4 # integer
b = 4.5 # float
c = 4j # complex number
print(type(a))
print(type(b))
print(type(c))
Output<class 'int'>
<class 'float'>
<class 'complex'>
Let’s understand python number and it’s types in detail:
Python Integer
Python int is the whole number, including negative numbers but not fractions. In Python, there is no limit to how long an integer value can be.
Example:
Python
x = 5 # A positive integer
y = -23 # A negative integer
z = 0 # Zero is also considered an integer
Performing arithmetic Operations on int type:
To check the result of arithmetic operations we can simply print the output using print(res). To check the type of the object, we can use print(type(res)).
Python
# Addition
res = 5 + 3 # Output: 8
# Subtraction
res = 10 - 4 # Output: 6
# Multiplication
res = 7 * 6 # Output: 42
# Division
res = 15 / 4 # Output: 3.75
# Floor Division
res = 15 // 4 # Output: 3
# Modulus (%)
res = 15 % 4 # Output: 3 (because 15 divided by 4 gives remainder 3)
# Exponentiation (**)
res = 2 ** 3 # Output: 8 (because 2 raised to the power of 3 is 8)
# Absolute Value (abs)
res = abs(-10) # Output: 10 (absolute value of -10)
# Round (round)
res = round(3.14159, 2) # Output: 3.14 (rounds to 2 decimal places)
Python Float
This is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. . Some examples of numbers that are represented as floats are 0.5 and -7.823457.
They can be created directly by entering a number with a decimal point, or by using operations such as division on integers. Extra zeros present at the number’s end are ignored automatically.
Examples:
Python
a = 3.14 # A positive float
b = -0.99 # A negative float
c = 0.0 # A float value that represents zero
Performing arithmetic Operations on float type:
To check the result of arithmetic operations, we can simply print the output using print(res). To check the type of the object, we can use print(type(res)).
Python
# Addition (float)
res = 3.5 + 2.2 # Output: 5.7
# Subtraction (float)
res = 7.8 - 4.3 # Output: 3.5
# Multiplication (float)
res = 5.5 * 2.0 # Output: 11.0
# Division (float)
res = 9.0 / 4.5 # Output: 2.0
# Floor Division (float)
res = 9.0 // 4.5 # Output: 2.0 (it returns the truncated quotient)
# Modulus (%) (float)
res = 9.0 % 4.5 # Output: 0.0 (remainder when divided)
# Exponentiation (float)
res = 2.5 ** 2 # Output: 6.25 (2.5 raised to the power of 2)
# Absolute Value (float)
res = abs(-7.4) # Output: 7.4 (absolute value)
# Round (float)
res = round(3.14159, 2) # Output: 3.14 (rounds to 2 decimal places)
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place can be inaccurate.
Python Complex
A complex number is a number that consists of real and imaginary parts. For example, 2 + 3j is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary part.
Performing arithmetic operations on complex type:
To check the result of arithmetic operations, we can simply print the output using print(res). To check the type of the object, we can use print(type(res)).
Python
# Addition (complex)
res = (3 + 4j) + (1 + 2j) # Output: (4 + 6j)
# Subtraction (complex)
res = (5 + 6j) - (2 + 3j) # Output: (3 + 3j)
# Multiplication (complex)
res = (2 + 3j) * (1 + 4j) # Output: (-10 + 11j)
# Division (complex)
res = (8 + 6j) / (2 + 3j) # Output: (2.0 + 0.0j)
# Exponentiation (complex)
res = (1 + 1j) ** 2 # Output: (0 + 2j) (raises the complex number to the power of 2)
# Absolute Value (complex)
res = abs(3 + 4j) # Output: 5.0 (absolute value of a complex number, which is sqrt(3^2 + 4^2))
# Conjugate of a complex number
res = (3 + 4j).conjugate() # Output: (3 - 4j) (negates the imaginary part)
# Real and Imaginary parts of a complex number
real = (3 + 4j).real # Output: 3.0
imag = (3 + 4j).imag # Output: 4.0
Type Conversion in Python
We can convert one number into the other form by two methods:
Using built-in functions and Arithmetic Operations
We can also use built-in functions like int(), float() and complex() to convert into different types explicitly. We can also use operations like addition and subtraction to change the type of number implicitly(automatically), if one of the operands is float. This method is not working for complex numbers.
Python
#Using Built-In Function
a = 2
print(float(a))
b = 5.6
print(int(b))
c = '3'
print(type(int(c)))
d = '5.6'
print(type(float(c)))
e = 5
print(complex(e))
f = 6.5
print(complex(f))
#Using Arithmetic Operations:Â
a = 1.6
b = 5
c = a + b
print(c)
Output2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
6.6
When we convert float to int, the decimal part is truncated.
Note:
- We can’t convert a complex data type number into int data type and float data type numbers.
- We can’t apply complex built-in functions on strings.
Random Numbers
Python also provides functionality to generate random numbers using the random module. This is especially useful for applications that require unpredictable values like games, simulations or cryptographic operations.
The random.randint(a, b) function generates a random integer between the specified a and b (both inclusive).
Generating Random Integers and Random Floating Point Numbers:
Python
# Generating Random Integer
import random
x = random.randint(1, 100)
print(x)
# Generating Random FLoating Point Integer
x = random.uniform(1.0, 10.0)
print(x)
Output67
4.433749029664113
Special Numbers in Python
Python has some special numeric values that you can encounter, especially when working with scientific computations or handling edge cases.
NaN (Not a Number): NaN stands for “Not a Number” and is used to represent undefined or unrepresentable values such as the result of dividing 0 by 0.
Infinity and -Infinity: Python also supports positive and negative infinity, represented by float(‘inf’) and float(‘-inf’), respectively. These are useful in various situations, such as when setting bounds for algorithms or detecting overflow conditions.
Python
# NaN Example
import math
n = math.nan
print(n)
# Infinity and -Infinity Example
x = float('inf')
y = float('-inf')
print(x)
print(y)
Suggested Quiz
10 Questions
What is the output of the following code?
print(type(5))
Explanation:
The type() function returns the data type of the passed value. Since 5 is an integer, it is recognized as <class 'int'>.
What type of number is 3.14 in Python?
Explanation:
Numbers with a decimal point in Python are floating-point numbers, also known as float.
How to express the number 5 as an exponent in Python?
Explanation:
The ** operator is used for exponentiation in Python. 5 ** 2 means 5 raised to the power of 2.
What will be the result of the operation (1 + 2j) * (3 + 4j)?
Explanation:
The operation (1+2j)×(3+4j) involves two complex numbers. When multiplying complex numbers, you multiply the real parts and imaginary parts in a manner similar to using the FOIL method for binomials. Adding all these together:
3 + 4j + 6j − 8 = −5 + 10j
Which function in Python can convert the string '123' to the integer 123?
Explanation:
The int() function is used to convert a string or another number type into an integer.
What is the result of 10 % 3?
Explanation:
The % operator returns the remainder of the division of the left operand by the right. 10 % 3 returns 1.
How can you express one million as a literal in Python?
Explanation:
Python allows the use of underscores to enhance readability in numeric literals.
Which function will you use to find the absolute value of a number in Python?
Explanation:
The abs() function returns the absolute value of the given number.
Which of the following is used to represent infinity in Python?
Explanation:
float('inf') creates a floating-point number representing positive infinity.
How to find the base-2 logarithm of 16 in Python?
Explanation:
Both math.log2(16) and math.log(16, 2) calculate the base-2 logarithm of 16.
Quiz Completed Successfully
Your Score : 2/10
Accuracy : 0%
Login to View Explanation
1/10
1/10
< Previous
Next >
Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity and extensive features. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks makes it perfect for developers. A high-level, interpreted la
9 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Numbers
In Python, numbers are a core data-type essential for performing arithmetic operations and calculations. Python supports three types of numbers, including integers, floating-point numbers and complex numbers. Here's an overview of each: [GFGTABS] Python a = 4 # integer b = 4.5 # float c = 4j # compl
6 min read
Python Boolean
Python Boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions. Python Boolean TypeBoolean value can be of two types only i.e. either True or False. The output
7 min read
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
5 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
5 min read
Python Arrays
In Python, array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Unlike Python lists (can store elements of mixed types), arrays must have all elements of same type. Having only homogeneous elements makes it memory-effici
7 min read
Python Tuples
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
7 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Python Sets
Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change. Creating a Set in PythonIn Python, the most basic and efficient method for creatin
11 min read