Input and Output
Read user input, display results, control print formatting, and handle common input cases safely.
- Read keyboard input with input().
- Explain why input() returns a string.
- Display values with print().
- Use sep and end to control formatting.
- Convert numeric input and handle invalid entries.
1. Reading input with input()
input() displays an optional prompt, waits for a line of input, removes the trailing newline, and returns the entered text as a string. It does not automatically convert digits into an integer or float.
If a user types 25, the returned value is the string "25". You must convert it before using it in numeric arithmetic.
Read a name
name = input("Enter your name: ")
print("Hello,", name)The prompt is written without an automatic newline, so the user types on that same line. After the user enters Asha and presses Enter, name refers to the string "Asha". print displays Hello, and the name separated by a space.
2. Displaying output with print()
print() displays one or more objects as text. By default, it places a single space between multiple arguments and ends with a newline. You can pass strings, numbers, Boolean values, and other printable objects.
Print multiple values
name = "Asha"
age = 22
print("Name:", name, "Age:", age)print receives four arguments. The default separator is one space, so a space appears between each argument.
3. The sep and end parameters
The sep parameter controls the text placed between multiple arguments. The end parameter controls what is written after all arguments. Both default to a single space for sep and a newline for end.
These parameters affect formatting only; they do not change the underlying values.
Choose a separator
print("2026", "10", "10", sep="-")The hyphen is placed between the three arguments instead of spaces.
Keep output on one line
print("Loading", end="...")
print("done")The first print ends with three dots instead of a newline. The second print continues on the same line and then ends with its default newline.
4. Escape sequences and readable output
Inside ordinary quoted strings, escape sequences represent characters that are awkward to type directly. For example, \n represents a newline and \t represents a tab. A backslash can also be escaped as \\.
The exact visual width of a tab can depend on the environment, so use spaces when precise alignment is important.
Newline and tab
print("First line\nSecond line")
print("Name\tScore")\n starts a new output line. \t inserts a tab character between Name and Score.
5. Numeric input and conversion
Convert input to the intended type before doing arithmetic. int(text) works for valid integer strings such as "25"; float(text) works for strings representing floating-point numbers such as "2.75". Invalid text raises ValueError.
Whitespace surrounding a number is accepted by int() and float(), but empty text or text that is not a valid number cannot be converted successfully.
Add two entered integers
first = int(input("First number: "))
second = int(input("Second number: "))
print("Sum:", first + second)Each input() returns text. int() converts the text to an integer or raises ValueError if it is invalid. The program adds the two integers and displays 20.
6. Empty input, whitespace, and invalid input
Pressing Enter without typing anything makes input() return an empty string. Typing only spaces returns a string containing those spaces; it is not automatically empty. Use strip() when leading and trailing whitespace should be removed.
When converting user input, handle ValueError if invalid input should not terminate the program unexpectedly. A loop can ask again until the user enters a valid number.
Validate integer input
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)strip() removes whitespace from the beginning and end of the input string. int(raw) raises ValueError for the text twelve. The except block handles that error and prints a helpful message.
Common Pitfalls & Mistakes to Avoid
#1 Adding two input() results directly and expecting numeric addition.
Explanation: Convert each value with int() or float() first; otherwise strings may concatenate.
#2 Expecting input() to return the prompt or automatically convert input.
Explanation: The prompt is displayed, but input() returns the entered line as a string.
#3 Assuming print() always ends with a newline.
Explanation: print() uses newline by default, but its end parameter can change that behavior.
#4 Assuming strip() changes the original string in place.
Explanation: Strings are immutable; strip() returns a new string.
Practice Questions
Read a name using the prompt Enter your name: and print Welcome, followed by the name.
Read two values, convert them to floats, and print the first divided by the second. Handle invalid numeric input and division by zero with helpful messages.
Input and Output Knowledge Check
1. What type does input() return?
2. What does print("a", "b", sep="-") display?
3. What happens if int("hello") is evaluated?
Technical & Placement Interview Questions
Key Takeaways & Summary
- input() returns a string.
- print() displays values and adds spaces/newlines by default.
- Use sep and end to customize output formatting.
- Convert input before numeric calculations.
- Handle ValueError and other expected input errors when appropriate.
Finished reading this lesson?
Track your course progress and update your learning dashboard.
Related Topics & Next Steps
Strengthen your programming fundamentals with these related lessons: