Python 3 has a built-in method for accepting user input. Let’s take a look at how to implement this. We want to accept two numbers from a user then return the product of both
number1 = input("What is the first number? ") number2 = input("What is the second number? ")
The output of the input method is always a string so we would have to convert this to an int or a float ( if we expect such values from the user ), so let’s revise the block of code above to this
number1 = int(input("What is the first number? ")) number2 = int(input("What is the second number? ")) product = number1 * number2 print("The product of {} and {} is {}".format( number1, number2, product ))
Now that those are integers we can multiply them and print the results
The results look as follows:
What is the first number? 5 What is the second number? 6 The product of 5 and 6 is 30
If you’re using Python 2 ( which you shouldn’t since it is currently EOL ), the input method becomes raw_input
number1 = int(raw_input("What is the first number? ")) number2 = int(raw_input("What is the second number? ")) product = number1 * number2 print("The product of {} and {} is {}".format( number1, number2, product ))
What to learn more about Python, take our Python for Beginners course.