When designing a calculator, the top priority task is multiplying numbers. Luckily, Python provides a straightforward process for handling numbers. In this tutorial, we will learn how to multiply numbers in Python with examples. Multiplication is one of the fundamental operations in both mathematics and computer science, so understanding it is crucial. This article covers the basic concepts and examples of how to perform multiplication in Python, providing a step-by-step guide to help you grasp the concept. Here is a list of methods and approaches that will aid you in multiplying numbers in Python, along with some examples to help you get the hang of it.
If you want to learn more about Python Programming, Visit Python Programming Tutorials.
How to multiply in Python?
Python offers various ways to perform multiplication, and the primary method involves using the (*) product or asterisk operator. This operator is used to multiply two numbers together and obtain the result. For instance, if you have two variables, ‘num1’ and ‘num2,’ the multiplication operation can be carried out as ‘num1 * num2,’ and the output will be stored in the ‘product’ variable.
To make the multiplication process more interactive, you can utilize the ‘input()’ method to obtain the values of ‘num1’ and ‘num2’ from the user. Once the values are acquired, you can use the product/asterisk operator to perform the multiplication operation.
input_1=input('enter first number:')
input_2=input('enter second number to be multiplied with:')
input_3=input('enter 3rd number:')
num = int (input_1)*int(input_2)*int(input_3)
print('Multiplication of numbers is: ',num, type(num))
enter first number:3
enter second number to be multiplied with:2
enter 3rd number:3
Multiplication of numbers is: 18 <class 'int'>
Additionally, when working with multiplication, it is crucial to consider the data type of the variables. In Python, you can explicitly declare the data type, such as ‘int’ for integers, to ensure proper calculations. This is particularly important when dealing with various data types to prevent unexpected results or errors.
Multiplying float number
Instead of defining an integer as a data type, define float as a data type to multiply the float numbers. Here is How you multiply in Python using float numbers:
input_1=input('enter first number:')
input_2=input('enter second number to be multiplied with:')
input_3=input('enter 3rd number:')
num = float (input_1)*float(input_2)*float(input_3)
print('Multiplication of numbers is: ',num, type(num))
enter first number:2.3
enter second number to be multiplied with:4.0
enter 3rd number:5.5
Multiplication of numbers is: 50.599999999999994 <class 'float'>
Use the define function keyword ‘def’ to multiply in Python
In Python, you can define a multiplication function using the ‘def’ keyword. This allows you to perform multiplication operations within your code. If you’re creating a calculator and need to implement multiplication functionality, the following example will demonstrate how to do it for different data types such as integers and floats.
The code snippet provided handles user input using the ‘literal_eval’ function. This is important because sometimes the user may enter values that cause a ‘ValueError’ during multiplication. Specifically, if the input value cannot be converted to an integer (e.g., when the user inputs non-numeric characters), Python will raise a ‘ValueError’ with a message like:
ValueError: invalid literal for int() with base 10:
To prevent this issue, we use ‘from ast import literal_eval’ to handle the user input properly and avoid ‘ValueError.’ This way, the calculator can handle various data types as input and provide accurate multiplication results. The ‘literal_eval’ function helps to ensure that the input is interpreted correctly, even if the user enters data in string format.
x=input()
print (type(x))
3
<class 'str'>
We have to convert a number before multiplying it in Python.
#import literal_eval, this allow to print any datype as input
from ast import literal_eval
input_1=literal_eval(input('enter first number:'))
input_2=literal_eval(input('enter 2nd number:'))
input_3=literal_eval(input('enter 3rd number:'))
#the foloowing defined function multiply two numbers
def multiply(input_1, input_2, input_3):
return (input_1)* (input_2)* (input_3)
multiply(input_1, input_2, input_3)
enter first number:3.4
enter 2nd number:5
enter 3rd number:66
1122.0
Use for…in structure to multiply in Python.
For…in structure allows us to print the minutes of the clock conveniently. For…in structure checks the iterable with the range() function. Wherever the iteration executes with the iterable, it multiplies with the number 5. And iteration executes unless the last iterable iterates and multiplies up to the defined range of 13.
#display minutes in Python
# Iterate in range from 1-->13
for i in range(1, 13):
print('clock at', i, '=', 5*i, 'min')
clock at 1 = 5 min
clock at 2 = 10 min
clock at 3 = 15 min
clock at 4 = 20 min
clock at 5 = 25 min
clock at 6 = 30 min
clock at 7 = 35 min
clock at 8 = 40 min
clock at 9 = 45 min
clock at 10 = 50 min
clock at 11 = 55 min
clock at 12 = 60 min
Using the zip() function to Multiply lists Python.
The zip() method in Python is used to add two equal-length lists together. The new list will be appended to the old list after it has been multiplied together.
Here is how you can multiply two equal-length lists in Python.
- The below example clearly shows how the list multiplies and is appended using zip () function while iterating. The list iterates until the last list element is multiplied and appended in the final list product = [].
list1 = [2.3, 4, 2.3]
list2 = [1, 2.5, 3.1]
product = [] #element multiplied and appended and saved in this empty list.
for num1, num2 in zip(list1, list2):
product.append(num1 * num2)
print("product:", product)
product: [2.3]
product: [2.3, 10.0]
product: [2.3, 10.0, 7.13]
Using math.prod() in python to multiply all values in the list
The Math module has a function named math.prod() that multiplies all elements present in a list with one another. The product of the list will be computed using import math.
import math
list1 = [2, 4, 2]
list2 = [1, 2.5, 3.1]
#import math.prod() from math module
l1 = math.prod(list1) # 2*4*2=16
l2 = math.prod(list2) # 1*2.5*3.1
print("The multiplication of list1 is: ",l1)
print("The multiplication of list2 is: ",l2)
The multiplication of list1 is: 16
The multiplication of list2 is: 7.75
Using traversal in Python to multiply all values in the list
Before you use traversal to multiply all items in the list, we must first introduce a defined constant value. The traversal will multiply each item by the defined constant value one by one and return a final product of all elements in the list after multiplying each with the fixed constant value.
Here is how it executes:
- Using for…in structure to traverse over a list in Python.
- Whenever the for loop iterates, it will multiply each element in the list by the defined number.
- Here in the following example, the first element in the list is 2, which is multiplied by the constant number 2, which gives 4, same is the case followed by the rest ones, and the final value they return is 32.
- The same is the case followed by list2, which returns 15.5
def multiplylistelement(multiply_all_list_element):
constant = 2
for i in multiply_all_list_element:
constant = constant * i
return constant
list1 = [2, 4, 2]
list2 = [1, 2.5, 3.1]
print("The multiplication of list1 element is: ",multiplylistelement(list1))
print("The multiplication of list2 element is: ",multiplylistelement(list2))
The multiplication of list1 element is: 32
The multiplication of list2 element is: 15.5
BY TRAVERSAL OVER A LIST USING INDEXING
During iteration, the function argument iterates over a list element by indexing using the range() function execution executes. The element traverses until the last element in the list is multiplied by the previous results. The constant=1, demonstrates that every element in the list index-wise is multiplied by this constant number and returns the result.
# use traversal over a list
def multiplylistelement(multiply_all_list_element):
constant = 1
for i in range(0,len(multiply_all_list_element)):
constant = constant * multiply_all_list_element[i]
return constant
list1 = [2, 4, 2]
list2 = [1.2, 2.1, 3.1]
print("The multiplication of list1 element is: ",multiplylistelement(list1))
print("The multiplication of list2 element is: ",multiplylistelement(list2))
The multiplication of list1 element is: 16
The multiplication of list2 element is: 7.812
Using numpy to multiply element-wise in Python
Importing numpy in Python allows you to do element-wise multiplication. We will use np.multiply() to multiply two equal-length list elements by element.
import numpy as np
l1 = [3,5.4,1]
l2 = [5,4,2]
print(np.multiply(l1, l2))
[15. 21.6 2. ]
Using numpy.prod() function to multiply all elements in lists in Python
The NumPy module has a function named numpy.prod() that multiplies all values present in a list with one another. The product of the list will be computed using import numpy in your Python script.
# numpy.prod()
import numpy
list1 = [2, 4, 2]
list2 = [1, 2.5, 3.1]
# using numpy.prod() to multiply in Python
multiply_list1 = numpy.prod(list1)
multiply_list2 = numpy.prod(list2)
print(multiply_list1)
print(multiply_list2)
16
7.75
Use lambda expression to multiply in Python
In the following example, lambda expression in aggregation with reduce() function is used to multiply every element in the list together. To perform the multiplication a product operator (*) is used in Python script.
# using lambda function in aggregation with reduce()
#import reduce function from functools library
from functools import reduce
l1 = [3.3, 2.1, 2,4]
l2 = [5, 2, 2]
multiply_list1 = reduce((lambda x, y: x * y), l1)
multiply_list2 = reduce((lambda x, y: x * y), l2)
print(multiply_list1)
print(multiply_list2)
55.44
20
Using mul() function of the operator module
Python allows us to multiply every element in the list using mul() function from the operator module. Here is how it executes:
# multiply the list elements by importing operator module
from operator import*
l1 = [3, 2, 2]
c=3
for i in l1:
# using mul function of operator module
c = mul(i,c) # 3*2*2=12 -->12*3=36
# printing the result
print(c)
36
Using accumulate() function with lambda to multiply in Python
The built-in accumulation function with lambda expression allows us to multiply two equal-length lists in Python. The procedure is straightforward.
- Convert the accumulate() function results in a List data type using list keyword.
- Then with print command, call the object with square brackets. Afterward, within square brackets, define the order of the multiplication by considering the element index location. The index slicing could be from left to right or right to left(negative slicing)
# using lambda function in aggregation with accumulate()
from itertools import accumulate
list1 = [2, 4, 2]
list2 = [1, 2, 3]
#using accumulate () function taking list and lambda as argument.
multiplylist_1 = list(accumulate(list1, (lambda x, y: x * y)))
multiplylist_2 = list(accumulate(list2, (lambda x, y: x * y)))
print("The multiplication of list1 element is: ",multiplylist_1[2]) #or [-1] -ve indexing approach
print("The multiplication of list2 element is: ",multiplylist_2[2])
The multiplication of list1 element is: 16
The multiplication of list2 element is: 6
Complex numbers multiplication in Python
The complex (imaginary part plus real part) number is multiplied in Python using the built-in function complex(). Invoking complex numbers within its argument and applying the product (*) operator results in the multiplication of two numbers.
#using complex() function to multiply complex numbers
complex_number_1 = complex(1, 2)
complex_number_2 = complex(0, 3)
complex_number_3 = complex(5, 4)
complex_number_product = complex_number_1 * complex_number_2 * complex_number_3
print('Multiplication of complex numbers: ', complex_number_product)
Multiplication of complex numbers: (-42-9j)
Conclusion
This page demonstrates different approaches to multiplying in Python with examples. However, there are different scenarios where you need to multiply a number. However, Python allows us to multiply different numbers in Python quickly. Use the one that best fits your operation.