Computer Programming 1 (Python) • Python Fundamentals

Reading User Input — I can read user input with input() and convert it to the correct type safely at my level.

Learn how to capture keyboard input, convert it to the right data type, and handle mistakes gracefully.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 10 figures

SECTION 1

Historical Context & Motivation

Almost every useful program needs to communicate with the person using it. Think about the apps on your phone—they ask for your username, your search query, or your age before they do anything meaningful. This two-way conversation between a human and a program is called user input, and it has been a core challenge since computers were first invented.

In the earliest days of computing, programs did not interact with users in real time at all. Instead, instructions and data were fed into a machine on physical media like punched cards. Over time, the desire for real-time interaction drove the creation of interactive terminals, command-line prompts, and eventually the graphical interfaces we use today. Python's input() function descends directly from this long history of making programs responsive to human beings.

1950s • Batch Processing Era

Programs received all data on punched cards before execution. There was no way to interact with a running program.

1960s • Interactive Terminals Emerge

Time-sharing systems like CTSS allowed users to type commands and see results on a screen in real time, creating the concept of interactive prompts.

1991 • Python 0.9 Released

Guido van Rossum released Python with built-in functions for reading keyboard input, making interactive programs easy to write from day one.

2008 • Python 3 Simplifies input()

Python 3 unified the input mechanism into a single input() function that always returns a string, making type conversion explicit and safer.

The central question this lesson addresses is straightforward but surprisingly important: when a user types something at the keyboard, how does your program receive that data, and how do you ensure the data is in the right format for your calculations? Mastering this skill is the gateway to writing truly interactive programs.

SECTION 2

Core Principles & Definitions

Before you start writing code, you need to understand a few foundational ideas about how Python handles user input. These principles will guide every decision you make when reading and converting data from the keyboard.

1

input() Always Returns a String

No matter what the user types—a name, a number, or even True—Python's input() function returns it as a string (str). You must convert it yourself if you need a different type.
2

Type Conversion (Casting)

To turn a string into a number, you use type casting functions like int() or float(). These tell Python to interpret the string as a number.
3

Invalid Input Causes Errors

If the user types "hello" and you try int("hello"), Python raises a ValueError and the program crashes—unless you handle it.
4

try / except Provides Safety

The try/except block lets you attempt a risky operation and catch errors gracefully, so your program can ask the user to try again instead of crashing.
5

Prompt Strings Guide the User

The string you pass to input() is called the prompt. A clear prompt (e.g., "Enter your age: ") helps the user know exactly what to type.
✦

KEY TAKEAWAY

Think of input() like a mailbox: everything that arrives is in an envelope (a string). If you ordered a number, you have to open the envelope and convert the contents yourself with int() or float(). And if someone put junk mail in the mailbox, you need a plan (try/except) so you don't accidentally treat it as a real letter.

SECTION 3

Visual Explanation — The Flow of User Input

The diagram below traces the complete journey of user input from the keyboard to a usable variable in your program. Follow the arrows from left to right to see how raw text becomes typed data, and notice where errors can occur.

How input() Works: From Keyboard to Variable⌨ KeyboardUser types: 17input()returns "17"(always a string)Type Castingint("17")float("17")(conversion step)✓ Successage = 17What Happens When the User Types "hello" Instead?⌨ KeyboardUser types: helloinput()returns "hello"(still a string)int("hello")💥 Cannot convert!✗ ValueErrorProgram crashes!🛡 try/except Catches the Errorexcept ValueError:print("Please enter a number")
Top row: the happy path where "17" converts successfully to the integer 17. Bottom row: the error path where "hello" cannot be converted, causing a ValueError. The dashed green box shows how try/except catches the error before it crashes the program.

Notice that the input() function itself never fails—it always returns a string. The danger comes in the type casting step, where you ask Python to interpret that string as a number. That is exactly the point where you need error handling to protect your program.

SECTION 4

How It Works — Syntax Deep Dive

Now let's look at the exact Python syntax for reading input, converting types, and handling errors. Each piece builds on the one before it, so follow the progression carefully.

Basic input() Syntax

BASIC INPUT

variable=input("promptstring")variable = input("prompt string")

variable — the name you choose to store the result. "prompt string" — the message displayed to the user before they type. The result stored in variable is always of type str.

Type Conversion Syntax

INTEGER CONVERSION

age=int(input("Enteryourage:"))age = int(input("Enter your age: "))

The int() function wraps input() to convert the returned string to an integer in one line. Works only if the user enters a valid whole number like 17.

FLOAT CONVERSION

price=float(input("Enterprice:$"))price = float(input("Enter price: \$"))

The float() function converts the string to a decimal number. It accepts both "3.99" and "4" as valid inputs.

Safe Conversion with try/except

TRY/EXCEPT PATTERN

try:value=int(input("Enteranumber:"))exceptValueError:print("Thatisnotavalidnumber.")try: value = int(input("Enter a number: ")) except ValueError: print("That is not a valid number.")

The try block attempts the risky conversion. If it fails, Python jumps to the except ValueError block instead of crashing. You can put any recovery logic inside the except block.

⚠

Why Not Just Catch All Errors?

You might wonder why we write except ValueError instead of just except. A bare except catches every possible error, which can hide bugs you actually need to see. Being specific—catching only ValueError—means you'll still be alerted if something unexpected goes wrong elsewhere in your code.

SECTION 5

Type Conversion Reference & Input Validation Loop

Different situations call for different types. The table below summarizes the most common conversions you will use and the kinds of input they accept.

FunctionReturnsValid Input ExamplesInvalid Input Examples
str()String (no conversion needed)Anything—input() already returns strNothing is invalid
int()Integer (whole number)"42", "-7", "0""3.5", "abc", ""
float()Floating-point (decimal)"3.14", "42", "-0.5""abc", ""
bool()Boolean (True/False)Any non-empty string → TrueEmpty string "" → False (not intuitive!)

Common type conversion functions and their behavior

A common pattern in real programs is the input validation loop. Instead of asking just once and crashing or giving up, you keep asking until the user provides valid input. The diagram below shows this loop pattern.

Input Validation Loop PatternSTARTwhile True:(keep looping until break)text = input("Enter a number: ")Can int(text)succeed?YESnum = int(text)break✓ Use numNOprint("Invalid, try again.")Loop back
This flowchart shows the input validation loop. The program keeps asking for input until the conversion succeeds. When it does, break exits the loop, and the program continues with the valid number.

In Python code, the validation loop pattern looks like this:

VALIDATION LOOP CODE

whileTrue:try:num=int(input("Enteranumber:"))breakexceptValueError:print("Invalidinput.Pleaseenterawholenumber.")while True: try: num = int(input("Enter a number: ")) break except ValueError: print("Invalid input. Please enter a whole number.")

The while True creates an infinite loop. The break statement exits the loop only when the conversion succeeds. If it fails, the except block runs, prints a message, and the loop repeats.

SECTION 6

Worked Example — A Temperature Converter

Let's build a small program that asks the user for a temperature in Fahrenheit, converts it to Celsius, and handles bad input gracefully. This example combines every concept from the lesson.

Temperature Converter with Safe Input

  1. 1

    Step 1 — Plan the Program

    We need to: (1) ask for a temperature in Fahrenheit, (2) convert the input string to a float, (3) apply the formula Celsius = (F − 32) × 5 ÷ 9, and (4) display the result. We also need to handle the case where the user types something that is not a number.
  2. 2

    Step 2 — Write the Input with Validation

    We use the validation loop pattern. Inside a while True loop, we attempt float(input(...)) inside a try block. If it works, we break out of the loop.
    while True: try: fahrenheit = float(input("Enter temp in °F: ")) break except ValueError: print("Please enter a valid number.")
  3. 3

    Step 3 — Perform the Conversion

    Now that fahrenheit is guaranteed to be a valid float, we can safely do math with it. We apply the standard conversion formula.
    celsius = (fahrenheit - 32) * 5 / 9
  4. 4

    Step 4 — Display the Result

    We use an f-string to format the output neatly, rounding to one decimal place with :.1f.
    print(f"{fahrenheit}°F = {celsius:.1f}°C")
  5. 5

    Step 5 — Test with Valid and Invalid Input

    If the user types 212, the program outputs 212.0°F = 100.0°C. If they type hot, they see "Please enter a valid number." and get another chance to type. The program never crashes.
    Sample run: Enter temp in °F: hot Please enter a valid number. Enter temp in °F: 212 212.0°F = 100.0°C

SECTION 7

Approaches to Input Handling — Strengths & Limitations

There are several ways you might handle user input in Python. Each approach has trade-offs in terms of safety, code complexity, and user experience. Understanding these differences will help you choose the right approach for your programs.

ApproachStrengthsLimitations
No conversion — use raw stringSimplest code; never crashes on input. Perfect when you genuinely need text (names, messages).Cannot do math with the result. "5" + "3" gives "53", not 8.
Inline conversion — int(input(...))Quick and concise for simple scripts or when you trust the input source.Crashes immediately on invalid input. Unsuitable for user-facing programs.
try/except once — single attemptPrevents crashes. You can provide an error message or a default value.Only gives the user one chance. You must decide on a fallback value.
Validation loop — while + try/exceptMost robust. Keeps asking until input is valid. Best user experience.More lines of code. Slightly more complex logic to learn.
.isdigit() check — pre-validationAvoids try/except entirely. Easy to understand.Only works for positive integers. Fails on negatives, decimals, and floats.

Comparison of input handling approaches

💡

WHICH APPROACH SHOULD I USE?

For most school assignments and real-world scripts, the validation loop with try/except is the gold standard. It is like a patient teacher who says "try again" instead of walking away when a student gives the wrong answer. Use the simpler approaches only when you are writing quick test scripts or when the input is guaranteed to be valid (like reading from a file you control).

SECTION 8

Connection to Advanced Topics

The skills you learn here—reading input, converting types, and handling errors—are the foundation for much more advanced programming concepts. The table below shows how each fundamental idea connects to topics you will encounter as you continue learning.

What You Learned NowWhere It Leads
input() reads from keyboardFile I/O reads data from files; web APIs receive data from the internet. The concept of reading external data is the same.
Type casting with int() / float()Data parsing and serialization (JSON, CSV) require converting strings to structured data types on a larger scale.
try/except for ValueErrorFull exception handling covers dozens of error types (FileNotFoundError, TypeError, KeyError) and lets you build resilient applications.
Validation loopGUI input validation, form validation in web development, and defensive programming patterns all build on the same loop-until-valid idea.

From fundamentals to advanced programming

As you advance, you will also learn to write your own custom functions that encapsulate the validation loop, so you can reuse safe input logic throughout your programs without rewriting it every time. For example, you might create a function called get_int(prompt) that handles all the looping and error checking internally. This is a stepping stone toward writing clean, reusable, professional-quality code.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

A student writes age = input("How old are you? ") and then tries print(age + 1). The program crashes with a TypeError. Explain why this happens and how to fix it.
Show answer
The input() function always returns a string, so age holds a value like "16" (a string), not the integer 16. Python cannot add a string and an integer together, which is why it raises a TypeError. To fix this, the student should convert the input to an integer by writing age = int(input("How old are you? ")). After this change, age will hold the integer 16, and age + 1 will correctly evaluate to 17.

Question 2: BASIC CALCULATION

Write a Python program that asks the user for two numbers (as floats) and prints their sum. Do not worry about error handling for this problem—just focus on correct type conversion.
Show answer
The solution uses float() to convert each input to a decimal number before adding them. Here is the code: num1 = float(input("Enter first number: ")) followed by num2 = float(input("Enter second number: ")) and then print("Sum:", num1 + num2). We use float() instead of int() because the problem says "as floats," and float() also accepts whole numbers, making it more flexible.

Question 3: INTERMEDIATE

Write a program that asks the user for their test score (an integer between 0 and 100). Use a try/except block so the program does not crash if the user types a non-number. If the input is valid, print whether the score is a passing grade (60 or above). If invalid, print an error message.
Show answer
This problem requires combining type conversion with a conditional check. The code structure is: try: score = int(input("Enter your test score: ")) if score >= 60: print("You passed!") else: print("You did not pass.") except ValueError: print("Error: Please enter a whole number.") The try block attempts the int() conversion first. If the user types something like "ninety," the conversion fails and the except block runs. If conversion succeeds, the if/else check determines the grade result.

Question 4: APPLIED

You are building a tip calculator for a restaurant. Write a program that: (1) asks for the bill total as a float, (2) asks for the tip percentage as a float, (3) calculates the tip amount and the total with tip, and (4) uses a validation loop so the user keeps getting asked until they provide valid numbers for each input.
Show answer
This requires two separate validation loops—one for each input. For the bill: while True: try: bill = float(input("Enter bill total: $")) break except ValueError: print("Please enter a valid dollar amount.") Then a similar loop for the tip percentage: while True: try: tip_pct = float(input("Enter tip percentage: ")) break except ValueError: print("Please enter a valid percentage.") Finally, compute and display: tip = bill * tip_pct / 100 print(f"Tip: ${tip:.2f}") print(f"Total: ${bill + tip:.2f}") Each loop ensures the user cannot proceed until they give a valid number, making the program robust.

Question 5: CRITICAL THINKING

A programmer writes a function get_positive_int(prompt) that should keep asking the user until they enter a positive integer. The function should reject negative numbers, zero, decimals, and non-numeric input. Write this function and explain how it handles each type of bad input differently from how int() alone would.
Show answer
This problem requires layering two types of validation: type validation (is it an integer?) and range validation (is it positive?). Here is the function: def get_positive_int(prompt): while True: try: value = int(input(prompt)) if value > 0: return value else: print("Please enter a positive number.") except ValueError: print("That is not a valid integer.") The int() function alone only checks whether the string can become an integer—it happily accepts −5 or 0. It also raises a ValueError on decimals like "3.5" because int("3.5") is not valid in Python. The ValueError except block catches both non-numeric strings and decimal strings. The if value > 0 check adds a second layer that rejects zero and negative numbers with a different message, giving the user clear feedback about what went wrong.

SUMMARY

Lesson Summary

Summary

In this lesson, you learned that Python's input() function reads text from the keyboard and always returns a string. To work with numbers, you must perform type casting using int() for whole numbers or float() for decimals. When a user enters data that cannot be converted, Python raises a ValueError, which will crash your program if it is not handled.

To prevent crashes, you wrap risky conversions in a try/except block. For the best user experience, you can combine try/except with a while True validation loop that keeps asking until the user provides valid input. These patterns—reading, converting, and validating—form the foundation for all interactive Python programs and extend directly to file reading, web forms, and data processing in advanced courses.

Varsity Tutors • Computer Programming 1 (Python) • Reading User Input