Content Summary: Getting User Input in Python
This lesson explains how to get input from a user in Python. The most basic way to do this is with the input()
function, which pauses the program and waits for the user to type something on their keyboard and press Enter. The value entered by the user can then be stored in a variable for later use in the program.
user = input()
print("You entered", user)
A crucial characteristic of the input()
function is that it always treats the user's entry as a string of characters. It does not evaluate what is entered. For example, if a user types the expression 123 + 2
, the program will not calculate the sum; instead, it will store the literal string "123 + 2"
. This behavior is important to understand when working with different types of data.
This becomes apparent when trying to build a simple calculator. If you ask the user for two numbers and then try to add them together using the +
operator, the program will not perform mathematical addition. Instead, it will perform string concatenation, which means it joins the two strings together. For example, if the user enters 3
and 4
, the program will output 34
.
number_one = input()
number_two = input()
print("The sum is", number_one + number_two)
To solve this problem, you must convert the input strings into actual numbers before you can perform mathematical operations on them. This process of changing a variable's data type is called "type casting." In this case, since we want to work with whole numbers, we can use the int()
function to cast the string input into an integer.
By wrapping the input()
function with the int()
function, you tell Python to interpret the user's entry as a number. With this change, the simple calculator program now works as expected, correctly adding the two numbers together and producing the correct mathematical sum.
number_one = int(input())
number_two = int(input())
print("The sum is", number_one + number_two)
To make your program more user-friendly, you can provide a prompt that tells the user what they are supposed to enter. You can do this by placing a string inside the parentheses of the input()
function. This text will be displayed to the user before the input field appears, making it clear what kind of information is expected.
number_one = int(input("Enter a number: "))
number_two = int(input("Enter another number: "))
print("The sum is", number_one + number_two)
In summary, the input()
function is used to get data from the user. This data is always returned as a string. If you need to treat the input as a number, you must explicitly type cast it using functions like int()
. Finally, you should always include a clear prompt to guide the user.
Thanks for reading and watching! If you have any questions or comments, feel free to leave them below! — Andy