Multiply numbers from user input in Python

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Multiply numbers from user input in Python #

To multiply numbers from user input:

  1. Use the int() class to convert each value to an integer.
  2. Use the multiplication operator to multiply the integers.
main.py
num_1 = input('Enter a number:') print(num_1) # 👉️ '5' num_2 = input('Enter another number:') print(num_2) # 👉️ '10' num_1 = int(num_1) num_2 = int(num_2) result = num_1 * num_2 print(result) # 👉️ 50

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

The input() function returns a string even if the user entered a number.

main.py
num_1 = input('Enter a number:') print(num_1) # 👉️ '5'

We have to use the int() or float() classes to convert the number to an integer or a float before multiplying.

If the expected value is a number, you can pass the call to the input() function to the int() class.

main.py
num_1 = int(input('Enter a number:')) print(num_1) # 👉️ 5 num_2 = int(input('Enter another number:')) print(num_2) # 👉️ 10 result = num_1 * num_2 print(result) # 👉️ 50

You can also extract the logic into a function which handles the scenario where the user enters a value that is not a valid number.

main.py
def multiply_inputs(): try: num_1 = int(input('Enter a number:')) num_2 = int(input('Enter another number:')) return num_1 * num_2 except ValueError: print('Input expects numbers') result = multiply_inputs() print(result) while result is None: result = multiply_inputs() print(result)

We used a try/except block to handle the possible ValueError that is raised when trying to convert an invalid number to an integer.

The while loop runs and calls the function if the result variable stores a None value (if the except block runs).

Note that you can also multiply a string by an integer to repeat the string N times.

main.py
print('a' * 3) # 👉️ 'aaa'

When we multiply a string by an integer, the string gets repeated N times.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.