Python Basic #2 - Accepting User Input

This post shows how to prompt a user for input.  In this program, you will ask the user for two numbers and then print the sum of those two numbers.

The concept of integers and strings are also discussed.

When asking for input from a user, the input command is used.  For example, if you want to create an object, x, that is assigned the value that the user enters, the command is as follows:

x = input("Enter first number: ")

In this example, we ask for two numbers.  In addition to the object x, we also create an object y.

y = input("Enter second number: ")

We can then perform computations on these values as follows:

sum = x+y

If you print the sum as follows (giving x a value of 1 and y a value of 2):

print("The sum is ",sum)

You get the following:

The sum is 12.

Obviously, we know that the sum of 1+2=3; however, Python is seeing the input as a string so it is simply combining the 1 and the 2 to give 12.  To overcome this, we need to tell Python that the objects are integers.  We do this as follows:

x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

This will now give us the correct sum of 3.

This coding is detailed in the following video:

https://youtu.be/0UbyZg3dCqs

Comments