Capturing User Input with the Input Function
In this lesson, you will learn how to pause your program’s execution to capture text typed by a user on their keyboard and store it in a variable.
How it Works
Up until now, your programs have been static—the data was already written into the code. To make your programs interactive, you can use the built-in input() function.
When Python reaches the input() function, it stops everything. It waits for the user to type something on their keyboard and press the Enter key. Once the user presses Enter, Python captures everything they typed as a string and assigns that value to a variable so you can use it later.
A Practical Example
You can even provide a "prompt" inside the parentheses to tell the user what they should type.
# Ask the user for their name
user_name = input("Please enter your name: ")
# Use the captured input in an f-string
print(f"Hello, {user_name}! It is nice to meet you.")
Here is what happens step-by-step:
- Python encounters
input("Please enter your name: "). - It displays the text inside the parentheses to the console.
- The program pauses. It sits idle, waiting for the user to type.
- Once the user types "Alice" and hits Enter, the string
"Alice"is stored in the variableuser_name. - The program resumes, moving to the
print()statement, which now has access to the stored input.
Important Note
Remember that input() always treats whatever the user types as a string (text), even if they type a number like "42". If you need to perform calculations with that input later, you will need to use your knowledge of type conversion (like int() or float()) to change the string into a numeric type before using it in math.
Key Takeaway: The input() function pauses your program, prompts the user for text, and captures their response as a string variable for you to use in your code.