How to divide two numbers in Python

Published on Aug. 22, 2023, 12:16 p.m.

To divide two numbers in Python, you can use the / operator. Here is an example code that divides two numbers and prints the result:

num1 = 10
num2 = 5
result = num1 / num2
print(result)

This will output 2.0, which is the result of dividing num1 by num2.

If you want to divide two numbers entered by the user, you can use the input() function to prompt the user to enter the two numbers, convert the input to integers using the int() function, and then divide them. Here is an example code that does this:

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print(result)

This will prompt the user to enter the two numbers, divide num1 by num2, and print the result.

Note that in Python 2.x, dividing two integers or longs using the slash operator (“/”) uses floor division (applying the floor function after division) and results in an integer value. To perform true division (with floating-point results), you can use the float() function to convert one of the operands to a floating-point number before dividing. For example:

num1 = 10
num2 = 5
result = float(num1) / num2
print(result)

This will output 2.0, which is the result of dividing num1 by num2 using true division with floating-point results. In Python 3.x, the / operator always performs true division by default.

Tags:

related content