In this article, we will learn about python program to divide two integers with examples.
Getting Started
The task is to divide two integers in python. For example,
If a = 20 and b = 4, then output is 20 / 4 = 5
We can do so in multiple ways –
- Simple Approach
- Using User Input
- Using User Input(Command Line Arguments)
- Using Lambda
- Using Function
Simple Approach
Using division operator (i.e. / operator) in python, we can divide two numbers as shown below –
b1 = 8 b2 = 4 result = b1 / b2 # Divide using / operator print("Result:", result)
Output:
Result: 2.0
Using User Input
- Take input from user using input() method.
- Then, convert them to integer using int() method.
- After that, use / operator to divide those integers.
b1 = int(input("Enter an integer")) b2 = int(input("Enter another integer")) result = b1 / b2 print("{0} / {1} is {2}" .format(b1, b2, result))
Output:
Enter an integer 20 Enter another integer 4 20 / 4 is 5.0
Using User Input (Command Line Arguments)
Command line arguments can be taken using sys.argv present in sys module in python.
After that, convert those value into integer using int() method.
-
Method 1
import sys b1, b2 = sys.argv[1:3] print("Result:", int(b1) / int(b2))
Output:
Result: 8.125
Run above code with command line arguments as 65 and 8.
-
Method 2
import sys b1, b2 = sys.argv[1:] print("Result:", int(b1) / int(b2))
Output:
Result: 8.125
Run above code with command line arguments as 65 and 8.
Using Lambda
We can wrap logic to divide two integers in python inside lambda function as shown below –
if __name__ == "__main__" : b1 = 768 b2 = 24 # Divide two integers divide_twoInt = lambda b1, b2 : b1 / b2 print("Result:", divide_twoInt(b1, b2))
Output:
Result: 32.0
Using Function
If we want to write a function in python that returns division of two integers, we can do so as shown below –
def divideIntegers(b1, b2): return b1 / b2 print("Result:", divideIntegers(105, 8))
Output:
Result: 13.125
That’s how we can write python program to divide two integers with examples.
Reference: Division
Learn about more python examples at – https://tutorialwing.com/python-tutorial/