In this article, we will learn about python program to divide two numbers with examples.
Getting Started
The task is to divide one number by another number in python. For example,
If a = 10 and b = 2, then output is 10 / 2 = 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
We can simply use division operator (i.e. / operator) in python to divide two numbers in python. For example,
y1 = 10.2 y2 = 2 result = y1 / y2 # Divide using / operator print("Result:", result)
Output:
Result: 5.1
Using User Input
If we need to take input from user and then divide two numbers, we can do so as below –
y1 = int(input("Enter a number")) y2 = float(input("Enter another number")) result = y1 / y2 print("{0} / {1} is {2}" .format(y1, y2, result))
Output:
Enter a number 15 Enter another number 3.0 15 / 3.0 is 5.0
Using User Input (Command Line Arguments)
If we need to take input from command line arguments and then find out division between two numbers in python, we can do as shown below –
-
Method 1
import sys y1, y2 = sys.argv[1:3] result = float(y1) / int(y2) print("Result:", result)
Output:
4.1
Run above code with command line arguments as 12.3 and 3.
-
Method 2
import sys y1, y2 = sys.argv[1:] result = float(y1) / int(y2) print("Result:", result)
Output:
4.1
Run above code with command line arguments as 12.3 and 3.
Using Lambda
We can wrap logic to divide two numbers in a lambda function in python as shown below –
if __name__ == "__main__" : y1 = 76.82 y2 = 2.49 # Divide two numbers divide_twoNumbers = lambda y1, y2 : y1 / y2 print("Result:", divide_twoNumbers(y1, y2))
Output:
Result: 30.85
Using Function
If we want to write logic to divide two numbers in a function, we can do so as shown below –
def divideNumbers(y1, y2): return y1 / y2 print("Result:", divideNumbers(142, 28))
Output:
Result: 5.07
That’s how we can write python program to divide two numbers with examples.
Reference: Division
Learn about more python examples at – https://tutorialwing.com/python-tutorial/