Computer Science
Grade 9
20 min
Getting User Input
Getting User Input
Tutorial Preview
1
Introduction & Learning Objectives
Learning Objectives
Validate that user input is the correct data type (e.g., an integer).
Implement a loop to repeatedly ask for input until it meets specific criteria (e.g., a number within a range).
Use error handling (try-except blocks) to prevent the program from crashing due to invalid input.
Parse a single line of input into multiple variables using string splitting.
Convert string input into numerical data types like integers and floats for calculations.
Design clear and effective input prompts for the user.
Ever played a game that crashed because you typed 'ten' instead of '10'? 💥 Let's learn how to build smarter programs that don't break so easily!
We've learned the basics of getting input, but in the real world, users make mista...
2
Key Concepts & Vocabulary
TermDefinitionExample
Input ValidationThe process of checking if data provided by the user meets certain requirements before the program uses it.If asking for an age, the program checks if the input is a positive number and not text like 'fifteen'.
Type CastingConverting a value from one data type to another. User input is always a string, so we must cast it to a number for calculations.The code `age = int(input('Enter age: '))` converts the string '14' entered by the user into the integer 14.
Error HandlingA programming practice for anticipating and managing errors that might occur while a program is running, preventing it from crashing.Using a `try-except` block to catch a `ValueError` if a user types 'hello' when the program expects a number.
Inp...
3
Core Syntax & Patterns
The Input-to-String Rule
The `input()` function always returns a string, regardless of what the user types.
Always remember this fundamental rule. If you need a number for math, you must explicitly convert (cast) the string result from `input()` to an integer (`int()`) or a float (`float()`).
The Safe Casting Pattern (Try-Except)
try:
numeric_variable = int(string_variable)
except ValueError:
print('Invalid input! Please enter a number.')
Use this pattern to attempt a type cast. If the cast fails (e.g., trying to convert 'abc' to an integer), the code in the `except` block runs instead of the program crashing.
The Validation Loop Pattern (While Loop)
while condition_is_not_met:
# Ask for input
# Check if the input is now valid
# If valid,...
4 more steps in this tutorial
Sign up free to access the complete tutorial with worked examples and practice.
Sign Up Free to ContinueSample Practice Questions
Challenging
A program asks for coordinates 'X,Y'. Which code block is the MOST robust, correctly handling a `ValueError` (e.g., 'a,b') AND an `IndexError` (e.g., the user just enters '15')?
A.`try:
coords = input().split(',')
x = int(coords[0])
y = int(coords[1])
except ValueError:
print('Invalid number format.')`
B.`coords = input().split(',')
try:
x = int(coords[0])
y = int(coords[1])
except (ValueError, IndexError):
print('Invalid format. Use X,Y.')`
C.`try:
x_str, y_str = input().split(',')
x = int(x_str)
y = int(y_str)
except ValueError:
print('Invalid format. Use X,Y.')`
D.`try:
coords = input().split(',')
if len(coords) == 2:
x = int(coords[0])
y = int(coords[1])
else:
print('Please enter two coordinates.')
except ValueError:
print('Please enter numbers only.')`
Challenging
You need to get a list of scores from a single line of input, like '88 92 75 100'. The code should handle cases where the user might accidentally type a non-numeric value, like '88 92 abc 100'. Which approach correctly builds a list of only the valid integers?
A.`scores_str = input().split()
scores_int = [int(s) for s in scores_str]`
B.`scores_str = input().split()
scores_int = []
for s in scores_str:
try:
scores_int.append(int(s))
except ValueError:
continue`
C.`try:
scores_int = [int(s) for s in input().split()]
except ValueError:
scores_int = []`
D.`scores_int = list(map(int, input().split()))`
Challenging
A program validates a user's age. It correctly handles non-numeric input and out-of-range numbers. However, it crashes when the user simply presses Enter without typing anything. What is the most likely cause of the crash?
A.The `input()` function returns `None` for an empty input, which `int()` cannot handle.
B.The code tries to access `coords[0]` after splitting an empty string, causing an `IndexError`.
C.The `int()` function receives an empty string (`''`) which causes a `ValueError` that was not anticipated.
D.The `while` loop condition becomes an infinite loop with empty input.
Want to practice and check your answers?
Sign up to access all questions with instant feedback, explanations, and progress tracking.
Start Practicing Free