PYTHON • INPUT AND OUTPUT

Reading User Input — Read user input with input() and convert to numeric types

Learn how Python programs receive data from users and transform text into numbers for calculations.

Historical Context & Motivation

Every useful program needs a way to communicate with the person using it. In the earliest days of computing, programmers fed instructions into machines using physical media like punch cards — stiff pieces of cardboard with holes punched in specific positions. There was no keyboard, no screen, and certainly no friendly prompt asking "What is your name?" The idea that a running program could pause, wait for a human to type something, and then use that typed text was a significant leap forward in how people and computers interact.

1950s
Batch Processing Era
Programs ran from start to finish using pre-loaded punch cards. There was no way to interact with a program while it was running — all data had to be prepared in advance.
1960s
Interactive Terminals Appear
Time-sharing systems like MULTICS introduced keyboards and text terminals, allowing users to type input and see output in real time for the first time.
1970s
C and scanf()
The C programming language introduced the scanf() function, which could read typed text and convert it to numbers. This pattern of 'read then convert' became a standard approach.
1991
Python's raw_input() and input()
Guido van Rossum created Python with built-in functions for reading user input. Python 2 had two functions: raw_input() for text and input() for evaluated expressions.
2008
Python 3 Simplifies input()
Python 3 unified the approach: input() always returns a string, and programmers explicitly convert to numbers using int() or float(). This design is safer and clearer.

The central question this lesson addresses is straightforward but essential: how does a Python program receive text from a user and turn it into a number it can calculate with? Understanding this unlocks your ability to write programs that respond to real people with real data — from simple calculators to grade-tracking apps.

Core Principles & Definitions

Before you start writing code, it helps to understand a few foundational ideas about how Python handles user input. The process involves two distinct steps: first, capturing what the user types as text, and second, converting that text into the data type your program actually needs. Let's break down the key concepts.

1

The input() Function

Python's built-in input() function pauses the program, displays an optional prompt message, waits for the user to type something and press Enter, then returns whatever was typed as a string.
2

Strings vs. Numbers

The text "42" and the number 42 are completely different in Python. A string is a sequence of characters, while an integer is a numeric value you can do math with. You cannot add "42" + 8 — Python will raise a TypeError.
3

Type Conversion (Casting)

Type conversion is the process of transforming data from one type to another. Use int() to convert a string to an integer, or float() to convert to a decimal number. This is also called casting.
4

The ValueError Exception

If a user types something that cannot be converted — like typing "hello" when your program expects a number — Python raises a ValueError. Robust programs anticipate and handle these errors gracefully.
✦ KEY TAKEAWAY
Think of input() like a text message you receive on your phone — it always arrives as text, even if the message contains a number like "150". Before you can use that number in a math calculation, you need to mentally recognize it as a number. Python needs you to do the same thing explicitly: tell it to treat the text as a number by wrapping it in int() or float().

Visual Explanation — The Input Pipeline

The diagram below illustrates the complete pipeline from the moment a user presses a key on their keyboard to the moment your program has a usable numeric value stored in a variable. Follow the arrows to see how raw keystrokes become a string and then get converted into an integer or a float.

The pipeline flows left to right: the user types characters, input() captures them as a string, and a conversion function like int() or float() transforms the string into a numeric value ready for math operations.

Notice in the diagram that you can combine both steps into a single line by nesting the input() call inside int() or float(). The inner function runs first and its return value becomes the argument to the outer function. This is a very common pattern in Python code, and you will see it frequently. However, when you are first learning, it can be clearer to use two separate lines so you can see exactly what each step does.

How It Works — Syntax & Behavior

Let's look at the exact syntax of each function and understand precisely what happens under the hood when your program asks for and processes user input.

The input() Function Syntax

INPUT SYNTAX
variable = input(prompt_string)
variable — the name where the result is stored; prompt_string — an optional message displayed to the user before they type. The return value is always of type str (string).

Integer Conversion with int()

INT CONVERSION
integer_variable = int(string_value)
Converts a string like "42" into the integer 42. Raises ValueError if the string contains non-numeric characters (including decimal points like "3.14").

Float Conversion with float()

FLOAT CONVERSION
float_variable = float(string_value)
Converts a string like "3.14" into the floating-point number 3.14. Also works on strings without decimal points: float("42") returns 42.0.

The Nested Pattern

ONE-LINE PATTERN
age = int(input("Enter your age: "))
Python evaluates inside-out: input() runs first and returns a string, then int() converts that string to an integer. The final integer value is assigned to age.
⚠️ Common Pitfall
If you try to pass a string with a decimal point to int(), you will get a ValueError. For example, int("3.14") crashes. If you want to accept decimals and then round to a whole number, first convert to float, then to int: int(float("3.14")) gives you 3.

Data Types & What Can Go Wrong

Understanding the difference between Python's data types is critical when working with user input. The diagram below maps out what happens when you try to convert various kinds of user input, showing which conversions succeed and which raise errors.

This chart shows six common user inputs and the result of converting each with int() and float(). Notice that int() fails on decimal strings while float() accepts both whole numbers and decimals. Both fail on non-numeric text.
Summary of what int() and float() accept and reject
Conversion FunctionAcceptsRejects
int()Whole numbers like "42", "-7", " 9 "Decimals like "3.14", words, mixed text
float()Decimals and whole numbers: "3.14", "42", "-7"Words, mixed text like "12abc"
💡 Pro Tip
When in doubt, use float() because it accepts a wider range of numeric strings. You can always convert a float to an int later using int() if you need a whole number.

Worked Example — Temperature Converter

Let's build a small but complete program that asks the user for a temperature in Fahrenheit and converts it to Celsius. This example combines input(), float() conversion, arithmetic, and formatted output — all the skills you have been learning.

Fahrenheit to Celsius Converter
1
Step 1 — Prompt the user for inputUse input() with a clear prompt message so the user knows what to type. Store the result in a variable. At this point, the variable holds a string.
temp_str = input("Enter temperature in °F: ")
2
Step 2 — Convert the string to a floatSince temperatures can have decimal values (like 98.6°F), use float() rather than int(). Now the variable fahrenheit is a numeric value you can do math with.
fahrenheit = float(temp_str)
3
Step 3 — Apply the conversion formulaThe formula for converting Fahrenheit to Celsius is: C = (F − 32) × 5 ÷ 9. Use standard Python arithmetic operators to calculate the result.
celsius = (fahrenheit - 32) * 5 / 9
4
Step 4 — Display the resultUse an f-string to display the result with a nice format. The :.1f inside the curly braces rounds the output to one decimal place.
print(f"{fahrenheit}°F = {celsius:.1f}°C")
5
Step 5 — Test with sample inputIf the user types 212, then temp_str is "212", fahrenheit becomes 212.0, and celsius becomes (212.0 - 32) * 5 / 9 = 100.0.
Output: 212.0°F = 100.0°C
📝 The Complete Program
Here is the full program in just three lines using the nested pattern: fahrenheit = float(input("Enter temperature in °F: ")) celsius = (fahrenheit - 32) * 5 / 9 print(f"{fahrenheit}°F = {celsius:.1f}°C")

Comparing int(), float(), and str()

Python's type conversion functions each serve a specific purpose. Understanding when to use which function — and what trade-offs each involves — is a key skill. The table below compares the three most common conversion functions you will encounter when working with user input.

Comparison of Python's three primary type conversion functions
Featureint()float()str()
PurposeConvert to whole numberConvert to decimal numberConvert to text string
Exampleint("42") → 42float("3.14") → 3.14str(42) → "42"
Handles decimals?No — ValueError on "3.14"YesN/A (outputs text)
Use caseCounting items, ages, menu choicesPrices, measurements, scientific dataCombining numbers with text in output
Truncationint(3.9) → 3 (drops decimal, no rounding)No truncationNo truncation
✦ WHEN TO USE WHICH
Use int() when the input should be a whole number — like someone's age, the number of players on a team, or a menu choice (1, 2, or 3). Use float() when the input might have a decimal — like a price ($19.99), a distance (3.5 miles), or a GPA (3.85). Think of it this way: if you would not write a decimal point when filling out a form field, use int(); if you might, use float().

Connection to Error Handling — try/except

In a real-world program, you cannot trust that users will always type valid numbers. What happens if someone types "abc" when your program expects a number? The program crashes with a ValueError. Python provides a tool to handle this gracefully: the try/except block. While a deep dive into exception handling is a topic for a future lesson, here is a preview of how it works with input conversion.

Comparing input handling with and without error handling
ApproachWithout Error HandlingWith try/except
Codeage = int(input("Age: "))try: age = int(input("Age: ")) except ValueError: print("Please enter a number.")
If user types "abc"Program crashes with a traceback errorPrints a friendly message and continues
User experienceConfusing, looks brokenClear, professional, and helpful

The try block tells Python: "Attempt to run this code." If a ValueError occurs (because the string could not be converted to a number), Python jumps to the except block instead of crashing. This is a powerful pattern you will use extensively as you build more complex programs. For now, just know that it exists and that robust input handling always involves checking for invalid data.

🔮 Looking Ahead
In upcoming lessons on control flow and loops, you will learn to combine try/except with a while loop to keep asking the user until they provide valid input. This is a standard pattern in professional Python code.

Practice Problems

PROBLEM 1 — CONCEPTUAL
A student writes the following code: x = input("Enter a number: ") print(x + 10) When they type 5 and press Enter, the program crashes. Explain why this happens and how to fix it.
PROBLEM 2 — BASIC CALCULATION
Write a Python program that asks the user for the length and width of a rectangle (in meters) and prints the area. The program should accept decimal values. What would the output be if the user enters 4.5 for length and 3.2 for width?
PROBLEM 3 — INTERMEDIATE
Write a program that asks the user for three test scores (integers), calculates the average as a float, and prints the result rounded to two decimal places. Include the proper conversion functions for each step.
PROBLEM 4 — APPLIED
You are building a tip calculator for a restaurant. Write a program that asks the user for the bill amount (a decimal), the tip percentage (a whole number like 18), and the number of people splitting the bill (a whole number). Print how much each person owes, rounded to two decimal places. Choose appropriate conversion functions for each input.
PROBLEM 5 — CRITICAL THINKING
Consider this code: value = int(input("Enter a number: ")). Explain what happens for each of these user inputs: (a) "42", (b) "3.14", (c) " 7 ", (d) an empty string (user just presses Enter). Then redesign the line so that it accepts both whole numbers and decimals, converting to an integer in either case (truncating the decimal portion).

Lesson Summary

Python's input() function pauses a running program, displays a prompt, and returns whatever the user types as a string. Since math operations require numeric types, you must explicitly convert strings using int() for whole numbers or float() for decimal numbers. This two-step process — capture text, then convert — is called type casting and is fundamental to interactive Python programs.

Remember that invalid input causes a ValueError — for example, passing a non-numeric string to int() or float(). You can use the nested pattern like int(input("...")) to combine both steps on a single line. As you advance, you will pair input conversion with try/except blocks to build robust programs that handle unexpected user input gracefully.

Varsity Tutors • Python • Reading User Input — Read user input with input() and convert to numeric types