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
1960s • Interactive Terminals Appear
1970s • C and scanf()
1991 • Python's raw_input() and input()
2008 • Python 3 Simplifies input()
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.
The input() Function
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.Strings vs. Numbers
"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.Type Conversion (Casting)
int() to convert a string to an integer, or float() to convert to a decimal number. This is also called casting.The ValueError Exception
"hello" when your program expects a number — Python raises a ValueError. Robust programs anticipate and handle these errors gracefully.KEY TAKEAWAY
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.
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 — 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
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
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
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
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.
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 Function | Accepts | Rejects |
|---|---|---|
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
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
Step 1 — Prompt the user for input
Useinput()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 float
Since temperatures can have decimal values (like 98.6°F), usefloat()rather thanint(). Now the variablefahrenheitis a numeric value you can do math with.fahrenheit = float(temp_str) - 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
Step 4 — Display the result
Use an f-string to display the result with a nice format. The:.1finside the curly braces rounds the output to one decimal place.print(f"{fahrenheit}°F = {celsius:.1f}°C") - 5
Step 5 — Test with sample input
If the user types212, thentemp_stris"212",fahrenheitbecomes212.0, andcelsiusbecomes(212.0 - 32) * 5 / 9 = 100.0.Output:212.0°F = 100.0°C
The Complete Program
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.
| Feature | int() | float() | str() |
|---|---|---|---|
| Purpose | Convert to whole number | Convert to decimal number | Convert to text string |
| Example | int("42") → 42 | float("3.14") → 3.14 | str(42) → "42" |
| Handles decimals? | No — ValueError on "3.14" | Yes | N/A (outputs text) |
| Use case | Counting items, ages, menu choices | Prices, measurements, scientific data | Combining numbers with text in output |
| Truncation | int(3.9) → 3 (drops decimal, no rounding) | No truncation | No truncation |
Comparison of Python's three primary type conversion functions
WHEN TO USE WHICH
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.
| Approach | Without Error Handling | With try/except |
|---|---|---|
| Code | age = int(input("Age: ")) | try:
age = int(input("Age: "))
except ValueError:
print("Please enter a number.") |
| If user types "abc" | Program crashes with a traceback error | Prints a friendly message and continues |
| User experience | Confusing, looks broken | Clear, 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
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
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
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
4.5 for length and 3.2 for width?Show answer
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
Show answer
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
Show answer
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
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
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.