Difference Between '/' and '//' in Python.

There are many programmers especially beginners who have started learning Python programming get confused between the '/' and '//' division operators of Python. In this article, we will understand the difference between them and the situation in which they are used.

Different Division Operator of Python

Division Operator in Python.

In Python, there are two types of division operators available that are used for division, but they have different behaviors. These are:

  • True Division (/)
  • Floor Division (//)


True Division Operator (/).

True Division (/) in Python is also known as Floating Point Division. It is used to divide one number by another. The result is always a float, which is a number that can have decimal points.


For example, let's consider the following Python code:

# Python Code Example for True Division
x = 5
y = 2
z = x / y

print(z)
Output:
2.5

In this code, we have divided 5 by 2. Since we used the True Division operator (/), the result is a float. Therefore, z will be 2.5.
Note: It is important to note that True Division was introduced in Python 3. In Python 2, the division operator (/) performs floor division, while the true division operator is not available. This can sometimes lead to confusion and bugs. (alert-warning)

Floor Division Operator (//).

Floor Division is a division operation that rounds the result down to the nearest integer. It discards the fractional part and only returns the integer part of the quotient.

For example, let's consider the following Python code:
# Python code Example for Floor Division
x = 5
y = 2
z = x // y

print(z)
Output:
2

In this code, we have divided 5 by 2. Since we used the Floor Division operator (//), the result is rounded down to the nearest integer. Therefore, z will be 2.


In conclusion, the difference between '/' and '//' in Python is that '/' performs true division, which can handle decimal values and fractions correctly, while '//' performs floor division, which only returns the integer part of the quotient and discards the fractional part. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS