Printing and displaying things to the user is great. However, we want the user to be able to talk back to us and give us information. This is known as input!
To get input from the user we can use the keyword "input". This will allow for the user to input some text and hit the enter key when they are done. Since we typically want to store what the user inputted we declare a variable to hold that input (see below).
Inside the brackets after the input keyword we can actually put what is known as a prompt. This will be printed on the same line that the user is typing on. It's typically a good idea to end your prompt with a colon or a space so the users input doesn't appear to be squeezed together with the programs output.
More About Print
The print function is capable of printing multiple things on the same line. If we separate things that we want to print by a comma all of them will appear on the same line. The print function even includes a space before and after each item so they don't appear squeezed together.
In python there are operators that we can use on certain data types. Typically when we use operators we must make sure that the items we are doing the operations on are of them same data type. For example, trying to add a str to an int will result in a error.
The main operators in python are:
We can use all of these operators on int's and floats's but not on the other data types. The only exception is that we are able to use the + and * operator on str's in a special way.
Order of Operations
Python follows the standard order of operations (BEDMAS).
Operations on Strings
Python allows for the use of the addition (+) operator and multiplication (*) operator on strings.
Adding two strings is known as concatenation.
Adding one string to another will simply add it to the end.
Multiplying a string by an integer n will repeat that string n times.
Bringing it All Together
To apply everything we've just learned we want to create a program that asks the user for two numbers and outputs their sum. To do this we try the following:
But when we run the program we get output that looks like this:
When we added the two numbers together we were actually adding two strings! This is because whenever we get input from the user it comes in as a string. So when the user typed 3 and 4 our program saw it as "3" and "4", instead of adding them mathematically it concatenated them.
To fix this we must convert each of our inputs into an integer first. We can convert a string into an integer by using the function "int()".
So our program should now look like this:
And now we should be getting the correct output of 7!