22. Python User Input
Python User Input
Most programs are not static; they require interaction with the user. Python allows for command-line input, meaning we can pause the program, ask the user for information, and then use that information in our code.
In Python 3.6 and later, this is handled using the built-in input() function. Mastering user input is the first step toward building dynamic, interactive applications.
The input() Function
The input() function pauses the program's execution and waits for the user to type something and press Enter. You can pass a string into the function to act as a prompt for the user.
Input Data Types
This is a critical concept: the input() function always returns a string (str), regardless of what the user types. Even if they type a number, Python stores it as text.
Because it is a string, if you try to do math with it directly, your program will crash or produce unexpected results.
Casting User Input
To perform calculations on user input, you must cast (convert) the string into the appropriate numeric data type, such as an int or a float.
Handling Floats
If you expect the user to enter a decimal number (like a price, a weight, or a temperature), you must cast the input using float().
Handling Invalid Input (Try/Except)
What happens if you ask for an integer, but the user types "twenty" or leaves it blank? The int() cast will fail and crash the program with a ValueError. You must handle this using a try/except block.
While Loops for Robust Input
In professional applications, if a user makes a mistake, you don't just crash or end the program. You use a while loop to continually ask them until they provide valid data.
Knowledge Check
Ready to test your understanding of 22. Python User Input?