Skip to content
PythonVariables and Basic Databeginner30 min read

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

Read a name and display a greeting
python
name = input("Enter your name: ")
print("Hello,", name)
Output
Enter your name: Hello, Asha

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

If standard input reaches end-of-file before a complete line is read, input() raises EOFError. Ordinary interactive input and end-of-file are different situations.

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

Print several values
python
name = "Asha"
age = 22
print("Name:", name, "Age:", age)
Output
Name: Asha Age: 22

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

Use print() when you want to display information. If you need to store a textual representation for later processing, use str() or another appropriate conversion explicitly.

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

Use a custom separator
python
print("2026", "10", "11", sep="-")
print("red", "green", "blue", sep=", ")
Output
2026-10-11 red, green, blue

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

Remember the distinction: sep controls what goes between arguments; end controls what goes after the complete print() call.

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

Insert a newline
python
print("First line\nSecond line")
Output
First line Second line

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

In source code, \n is two typed characters that represent a newline escape sequence inside an ordinary string literal. The resulting string contains the newline character.

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

Add two entered integers
python
first = int(input("First number: "))
second = int(input("Second number: "))
print("Sum:", first + second)
Output
First number: Second number: Sum: 20

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

Conversion can fail. When input comes from a user, consider what should happen if the entered text is empty, contains letters, or otherwise does not represent the expected number.

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

Distinguish empty and whitespace-only input
python
raw = " "
print(len(raw))
cleaned = raw.strip()
print(repr(cleaned))
print(len(cleaned))
Output
3 '' 0

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

Calling strip() does not automatically validate the meaning of input. It only removes surrounding whitespace. Your program must still check whether the resulting value is acceptable.

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

Handle an invalid integer
python
raw = input("Enter a whole number: ").strip()
try:
number = int(raw)
except ValueError:
print("Please enter a valid whole number.")
else:
print("Double:", number * 2)
Output
Enter a whole number: Please enter a valid whole number.

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

Catch the exception you expect, such as ValueError for invalid numeric conversion. Avoid catching every possible exception without a specific reason, because doing so can hide programming errors.

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

Read numbers and safely divide
python
try:
numerator = float(input("Numerator: "))
denominator = float(input("Denominator: "))
result = numerator / denominator
except ValueError:
print("Please enter valid numbers.")
except ZeroDivisionError:
print("The denominator cannot be zero.")
else:
print("Result:", result)
Output
Numerator: Denominator: The denominator cannot be zero.

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

The examples assume that standard input remains available. In production programs, end-of-file and other external input failures may need separate handling if they are part of the expected environment.

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

Trace a total calculation
python
price_text = input("Price: ")
quantity_text = input("Quantity: ")
price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print("Total:", total)
Output
Price: Quantity: Total: 50.0

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

A reliable dry run tracks the type of each value as well as its contents. For example, the text "4" and the integer 4 may look similar when printed, but they behave differently in expressions.

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.

Incorrect Approach
script.py
python
Assuming input() automatically converts digits into a number.
Correct Solution
script.py
python
input() returns a string. Convert it explicitly with int() or float() when numeric arithmetic is required.

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.

Incorrect Approach
script.py
python
Adding two input() results and expecting numeric addition.
Correct Solution
script.py
python
Two strings joined with + are concatenated. Convert valid numeric input before adding numbers.

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.

Incorrect Approach
script.py
python
Assuming the prompt is the value returned by input().
Correct Solution
script.py
python
The prompt is displayed to the user. input() returns the entered line of text, without its trailing newline.

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.

Incorrect Approach
script.py
python
Assuming print() always places every call on a new line.
Correct Solution
script.py
python
print() uses a newline by default, but end can change the text written after a call.

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.

Incorrect Approach
script.py
python
Thinking sep is placed before the first argument or after the last argument.
Correct Solution
script.py
python
sep is inserted only between arguments. end controls what is written after all arguments.

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.

Incorrect Approach
script.py
python
Confusing the escape sequence \n with the two visible characters backslash and n.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Assuming strip() modifies a string in place.
Correct Solution
script.py
python
Strings are immutable. strip() returns a new string, so assign its result if you need the cleaned value.

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.

Incorrect Approach
script.py
python
Assuming int() rounds a floating-point number.
Correct Solution
script.py
python
int() truncates toward zero. Use round() when rounding is the intended operation.

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.

Incorrect Approach
script.py
python
Catching ValueError and assuming it also handles division by zero.
Correct Solution
script.py
python
Invalid numeric conversion typically raises ValueError; division by zero raises ZeroDivisionError. Handle the expected exceptions separately.

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.

Incorrect Approach
script.py
python
Ignoring empty or whitespace-only input.
Correct Solution
script.py
python
Check the input after appropriate normalization, such as strip(), when a non-empty value is required.

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.

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()?
Answer:
input() reads a line from standard input and returns the entered text as a string. print() displays the string representations of supplied objects on standard output. input() is used to receive information; print() is used to communicate information.
Q2:Why does input() return a string even when the user enters digits?
Answer:
input() reads text and does not infer a desired numeric type. The program must explicitly convert that text using int() or float() before numeric arithmetic. Conversion can fail if the entered text is not valid for the requested type.
Q3:What are sep and end in print()?
Answer:
sep specifies the string inserted between multiple arguments and defaults to a single space. end specifies what is written after all arguments and defaults to a newline. They control output formatting rather than changing the types of the values.
Q4:How would you handle invalid numeric input?
Answer:
Place the conversion inside a try block and catch ValueError in an except block. Display a useful message, or use a loop to request input again. If the program performs additional operations, handle their expected exceptions separately.
Q5:What is the difference between an empty string and whitespace-only input?
Answer:
An empty string contains no characters, while a whitespace-only string contains spaces or other whitespace characters. input() returns an empty string when the user submits a blank line, but spaces remain in the returned string. strip() removes surrounding whitespace and turns whitespace-only input into an empty string.
Q6:What is the difference between ValueError and ZeroDivisionError in an input program?
Answer:
ValueError commonly occurs when a conversion function such as int() or float() receives invalid numeric text. ZeroDivisionError occurs when an operation attempts to divide by zero. A program can use separate except clauses to provide an appropriate message for each case.
Q7:Does strip() modify the original string?
Answer:
No. Strings are immutable, so strip() returns a new string with leading and trailing whitespace removed. Assign the returned string to a name if the cleaned value needs to be used later.
Q8:What does the else clause do in a try statement?
Answer:
The else block executes when the try block completes without raising an exception handled by the associated except clauses. It is useful for separating successful-operation logic from exception-handling logic.
Q9:How can a program repeatedly request valid integer input?
Answer:
Use a loop to read input and attempt int() conversion inside a try block. If ValueError occurs, display an error message and continue the loop. When conversion succeeds, process the number and exit the loop using break or another suitable condition.
Q10:What is the difference between displaying a value and converting it to a string?
Answer:
print() displays an object using its textual representation, but it does not rebind the original variable or permanently convert the object to str. str(value) explicitly returns a string representation that can be stored, concatenated, or processed as text.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: