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.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 9 figures

SECTION 1

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.

SECTION 2

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().

SECTION 3

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 input() Pipeline: From Keystrokes to NumbersUser Types7 5 ↵input() returns"75"(type: str)Convert withint("75")orfloat("75")Result75(type: int)Complete Code Examples# Integer conversiontext = input("Enter age: ")age = int(text)print(age + 1)# Float conversiontext = input("Enter GPA: ")gpa = float(text)print(gpa * 25)One-Line Shortcut (Nested Calls)age = int( input("Enter age: ") )input() runs first → returns str → int() converts it → result stored in age
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.

SECTION 4

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(promptstring)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

integervariable=int(stringvalue)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

floatvariable=float(stringvalue)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("Enteryourage:"))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.

SECTION 5

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.

Conversion Results: What Succeeds ✓ and What Fails ✗Green arrows = success, Red arrows = ValueErrorUser Input (str)"42""3.14""-7""hello""12abc"" 9 "int() Result42 ✓ValueError ✗-7 ✓ValueError ✗ValueError ✗9 ✓float() Result42.0 ✓3.14 ✓-7.0 ✓ValueError ✗ValueError ✗9.0 ✓Note: int() and float() both strip leading/trailing whitespace automatically
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.
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"

Summary of what int() and float() accept and reject

💡

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.

SECTION 6

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. 1

    Step 1 — Prompt the user for input

    Use 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. 2

    Step 2 — Convert the string to a float

    Since 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. 3

    Step 3 — Apply the conversion formula

    The 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. 4

    Step 4 — Display the result

    Use 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. 5

    Step 5 — Test with sample input

    If 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")

SECTION 7

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.

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

Comparison of Python's three primary type conversion functions

✦

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().

SECTION 8

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.

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

Comparing input handling with and without error handling

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.

SECTION 9

Practice Problems

Question 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.
Show answer
The input() function always returns a string, so x holds the string "5", not the integer 5. Python cannot add a string and an integer together, so it raises a TypeError. To fix this, the student should convert the input to an integer before adding: x = int(input("Enter a number: ")). Now x would be the integer 5, and x + 10 would correctly produce 15.

Question 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?
Show answer
The program should use float() because the values may have decimals. The code is: length = float(input("Enter length in meters: ")) followed by width = float(input("Enter width in meters: ")) and then area = length * width and finally print(f"Area: {area} square meters"). With inputs 4.5 and 3.2, the area is 4.5 × 3.2 = 14.4, so the output would be: Area: 14.4 square meters.

Question 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.
Show answer
The program needs three separate input() calls, each wrapped in int() since scores are whole numbers. The code: s1 = int(input("Score 1: ")), s2 = int(input("Score 2: ")), s3 = int(input("Score 3: ")), then average = (s1 + s2 + s3) / 3. The division operator / automatically produces a float in Python 3. Finally, print(f"Average: {average:.2f}") rounds to two decimal places. For scores 85, 92, and 78, the average is (85 + 92 + 78) / 3 = 85.0, displayed as 85.00.

Question 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.
Show answer
The bill amount needs float() because prices have decimals. The tip percentage and number of people should use int() since they are whole numbers. Code: bill = float(input("Bill amount: $")), tip_pct = int(input("Tip percentage: ")), people = int(input("Number of people: ")). Then calculate: total = bill + bill * tip_pct / 100 and per_person = total / people. Finally: print(f"Each person owes: ${per_person:.2f}"). For a $85.50 bill, 20% tip, and 3 people: total = 85.50 + 17.10 = 102.60, per person = 102.60 / 3 = 34.20.

Question 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).
Show answer
(a) "42" converts successfully to 42. (b) "3.14" raises a ValueError because int() cannot directly convert a string with a decimal point. (c) " 7 " converts successfully to 7 because int() strips whitespace automatically. (d) An empty string raises a ValueError because there is nothing to convert. To accept both whole numbers and decimals, use a two-step conversion: value = int(float(input("Enter a number: "))). Here, float() first converts the string to a decimal number (works for both "42" and "3.14"), and then int() truncates it to a whole number. So "3.14" becomes 3.14 then 3, and "42" becomes 42.0 then 42. The empty string case would still raise an error and would need try/except to handle.

SUMMARY

Lesson Summary

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