Input and Output
Read user input, display results, format output, convert entered values, and handle invalid input safely.
In this lesson, you will learn
- ✓Read a line of user input with input() and explain its return value.
- ✓Display values with print() and understand its default behavior.
- ✓Customize output using the sep and end parameters.
- ✓Use newline and tab escape sequences in strings.
- ✓Convert numeric input using int() and float() before performing arithmetic.
- ✓Distinguish empty input from whitespace-only input.
- ✓Handle invalid numeric input with try and except.
- ✓Recognize and handle division by zero separately from invalid numeric input.
1. Reading User Input with input()
The built-in input() function reads one line from standard input. You can provide an optional prompt as a string. Python displays that prompt, waits for the user to enter a line, removes the trailing newline from the returned text, and returns the remaining input as a string.
For example, if the user types Asha and presses Enter, input() returns the string "Asha". If the user types 25, input() returns the string "25", not the integer 25.
The prompt is displayed before the user enters a value. It is not included in the value returned by input(). In an interactive terminal, the characters typed by the user commonly appear on the same line as the prompt.
Read a name and display a greeting
input("Enter your name: ") displays the prompt and waits for a line of input. The example assumes that the user types Asha and presses Enter. The name variable then refers to the string "Asha". print() displays Hello, and Asha with a space between its two arguments. The combined output represents a typical interactive terminal where the typed input appears after the prompt. The program itself prints the greeting on the next line.
Note
2. Displaying Information with print()
The built-in print() function displays the string representation of one or more objects. You can print strings, integers, floating-point numbers, Boolean values, and other objects.
By default, print() places a single space between multiple arguments and writes a newline after the final argument. This is why separate print() calls normally display their results on separate lines.
A string and a number are different types, but print() can display both in one call because it converts the arguments to text for output. This does not mean that the original objects change their types.
Print several values
The print() call receives four arguments: "Name:", name, "Age:", and age. Python displays the values in the order supplied. The default separator is one space, so a space appears between adjacent arguments. The final newline moves subsequent terminal output to the next line.
Note
3. Customizing Output with sep and end
The sep parameter controls the text inserted between multiple arguments passed to print(). Its default value is a single space. You can supply another string, such as a comma, a hyphen, or an empty string.
The end parameter controls the text written after all arguments have been displayed. Its default value is a newline character, so each ordinary print() call finishes on a new line.
Changing sep or end affects the formatting of the output, not the underlying values. Both parameters accept strings.
Use a custom separator
The first call inserts a hyphen between its three arguments. The second call inserts a comma followed by a space between its arguments. The separator is inserted between arguments, not before the first argument or after the last one.
Note
4. Escape Sequences and Readable Output
Escape sequences allow strings to represent special characters. In ordinary Python string literals, a backslash followed by a recognized character can represent a newline, a tab, or a backslash itself.
The escape sequence \n represents a newline, which moves subsequent text to the next line. The sequence \t represents a horizontal tab. The sequence \\ represents a literal backslash.
A tab is not necessarily a fixed number of spaces. Its visual width depends on the environment and the current tab position. When precise alignment matters, use an appropriate formatting technique rather than relying on tab width.
Insert a newline
The string contains a newline character between First line and Second line. print() displays the first part, moves to the next line, and displays the second part. One print() call can therefore produce multiple lines of output.
Note
5. Converting Numeric Input
Because input() returns a string, convert the value before performing numeric calculations. Use int() for valid integer text and float() for text representing a floating-point number.
For example, int("25") returns the integer 25, while float("2.75") returns the floating-point value 2.75. These conversions do not change the original string variable unless you assign the converted result back to that name.
The conversion must match the input. int("2.75") raises ValueError because the text is not a valid integer literal. If decimal input is allowed, float() may be the appropriate choice.
Invalid numeric text causes a conversion error rather than automatically becoming zero. Your program should decide how to handle such input.
Add two entered integers
The first input() call reads the text 12. int() converts it to the integer 12. The second input() call reads the text 8. int() converts it to the integer 8. The + operator performs integer addition, producing 20. The combined output represents a typical terminal session with the user’s typed input omitted from the displayed transcript after the prompts.
Note
6. Empty Input, Whitespace, and strip()
If a user presses Enter without typing any characters, input() returns an empty string, written as "". If the user enters only spaces, the returned string contains those spaces and is not initially empty.
The string method strip() returns a new string with leading and trailing whitespace removed. It does not modify the original string in place because strings are immutable.
After calling strip(), whitespace-only input becomes an empty string. This is useful when validating required text or preparing numeric input for conversion.
Distinguish empty and whitespace-only input
The string raw contains three spaces, so len(raw) returns 3. strip() removes the leading and trailing spaces and returns an empty string. repr(cleaned) displays the empty string representation, including its quotation marks. The cleaned string has length zero.
Note
7. Handling Invalid Input with try and except
A program should not unexpectedly terminate just because a user enters text that cannot be converted to the expected type. Python provides try and except to handle anticipated exceptions.
When int() receives text that is not a valid integer, it raises ValueError. Put the conversion inside a try block and handle ValueError in an except block when you want to display a helpful message instead of allowing that error to propagate.
An else block can contain code that should run only if the try block completes without raising an exception handled by the corresponding except clauses.
For programs that should keep asking until valid input is supplied, use a loop and stop when conversion succeeds. The appropriate behavior depends on the requirements of the program.
Handle an invalid integer
strip() removes leading and trailing whitespace from the returned input string. int("twelve") raises ValueError because the text does not represent a valid integer. The except block handles that exception and displays a helpful message. The else block does not run because the conversion failed.
Note
8. Handling Division by Zero
Invalid numeric text and division by zero are different errors. A conversion such as float("abc") raises ValueError, while dividing a number by a zero denominator raises ZeroDivisionError.
If a program accepts two numbers and divides one by the other, validate both cases appropriately. Separate except clauses can provide clear messages for each problem.
The numeric value 0.0 is zero for this purpose, just as 0 is. A successful conversion does not guarantee that every later arithmetic operation is valid.
Read numbers and safely divide
The text 10 converts to the float 10.0. The text 0 converts to the float 0.0; the conversion itself succeeds. The division raises ZeroDivisionError because the denominator is zero. The matching except block displays a specific error message. The else block does not run.
Note
9. Dry Run: Follow Input, Conversion, and Output
A dry run means tracing a program statement by statement without guessing what a value becomes. Record the text returned by input(), the result of any conversion, the arithmetic result, and the output produced by each print() call.
This is particularly useful for input and output because the prompt, the user-entered text, and the program’s printed result are separate parts of an interactive session.
Trace a total calculation
Step 1: The program displays Price: and reads the text 12.5. price_text refers to a string. Step 2: The program displays Quantity: and reads the text 4. quantity_text refers to a string. Step 3: float(price_text) produces the floating-point value 12.5, which is assigned to price. Step 4: int(quantity_text) produces the integer 4, which is assigned to quantity. Step 5: price * quantity evaluates to 50.0 because one operand is a float. Step 6: print("Total:", total) displays Total: followed by a space and 50.0.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming input() automatically converts digits into a number.
Why it happens: input() returns text from the user; the program must explicitly convert that text when a numeric value is needed.
Key takeaway: input() returns a string. Convert it explicitly with int() or float() when numeric arithmetic is required.
#2 Adding two input() results and expecting numeric addition.
Why it happens: Because both input() results are strings, the + operator concatenates their text instead of adding numeric values.
Key takeaway: Two strings joined with + are concatenated. Convert valid numeric input before adding numbers.
#3 Assuming the prompt is the value returned by input().
Why it happens: The prompt is displayed to the user, while input() returns the text entered after the prompt.
Key takeaway: The prompt is displayed to the user. input() returns the entered line of text, without its trailing newline.
#4 Assuming print() always places every call on a new line.
Why it happens: print() ends with a newline by default, but its end parameter can change that behavior.
Key takeaway: print() uses a newline by default, but end can change the text written after a call.
#5 Thinking sep is placed before the first argument or after the last argument.
Why it happens: sep is inserted only between positional arguments, not before the first or after the last argument.
Key takeaway: sep is inserted only between arguments. end controls what is written after all arguments.
#6 Confusing the escape sequence \n with the two visible characters backslash and n.
Why it happens: The escape sequence \n represents a newline in a string; writing an escaped backslash can instead display the literal characters.
Key takeaway: Inside an ordinary string literal, \n represents a newline. To display a literal backslash followed by n, escape the backslash or use an appropriate raw string.
#7 Assuming strip() modifies a string in place.
Why it happens: Strings are immutable, so strip() returns a new string with surrounding whitespace removed rather than changing the original string.
Key takeaway: Strings are immutable. strip() returns a new string, so assign its result if you need the cleaned value.
#8 Assuming int() rounds a floating-point number.
Why it happens: int() truncates a float toward zero; it does not round to the nearest integer.
Key takeaway: int() truncates toward zero. Use round() when rounding is the intended operation.
#9 Catching ValueError and assuming it also handles division by zero.
Why it happens: ValueError commonly covers invalid numeric conversion, while division by zero raises ZeroDivisionError; these are different failure cases.
Key takeaway: Invalid numeric conversion typically raises ValueError; division by zero raises ZeroDivisionError. Handle the expected exceptions separately.
#10 Ignoring empty or whitespace-only input.
Why it happens: An empty string or whitespace-only string can pass unnoticed unless the program checks and normalizes user input.
Key takeaway: Check the input after appropriate normalization, such as strip(), when a non-empty value is required.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is the difference between input() and print()?
Q2:Why does input() return a string even when the user enters digits?
Q3:What are sep and end in print()?
Q4:How would you handle invalid numeric input?
Q5:What is the difference between an empty string and whitespace-only input?
Q6:What is the difference between ValueError and ZeroDivisionError in an input program?
Q7:Does strip() modify the original string?
Q8:What does the else clause do in a try statement?
Q9:How can a program repeatedly request valid integer input?
Q10:What is the difference between displaying a value and converting it to a string?
Key takeaways
- input() reads a line of text and returns a string.
- print() displays values, separating multiple arguments with a space and ending with a newline by default.
- Use sep to customize separators and end to customize the ending of printed output.
- Use \n for a newline, \t for a tab, and \\ for a literal backslash inside ordinary string literals.
- Convert numeric input with int() or float() before performing arithmetic.
- strip() returns a new string with surrounding whitespace removed.
- Handle invalid numeric conversions with ValueError and division by zero with ZeroDivisionError.
- Use loops when a program must keep asking for valid input.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: