FirstHack Learn
Log in Sign up free

Input and Output

8 min read · 30 views

Talking to the user

So far your programs have contained every value you needed, written directly into the code. That is fine for learning, but a program that always prints the same thing is not very useful. Input lets the person running the program supply the values.

Python's built-in input() function does this: it pauses the program, waits for the user to type something and press Enter, and hands back what they typed.

TEXT
name = input("What is your name? ")
print("Hello,", name)

The text inside the brackets is the prompt. It is optional but you should almost always include one — a program that stops with a blank screen and no explanation is confusing. Put a trailing space in the prompt so the typed answer does not run into your question.

ℹ️Why this block has no Run button

Code blocks marked as python on this site can be run in your browser, but a browser code runner has nowhere to type an answer, so input() would hang. Examples using input() are shown as plain text. Copy them into a real Python file on your own machine to try them.

input() always returns a string

This is the single most important fact in this tutorial. Whatever the user types — a name, a number, a date — input() returns it as a string. Even 25 comes back as "25".

TEXT
age = input("Enter your age: ")
print(type(age))          # <class 'str'>
print(age + 1)            # TypeError

age + 1 fails because you cannot add a number to text. To do arithmetic you must convert first:

TEXT
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

Read that from the inside out: input(...) collects the text, then int(...) converts it to a whole number, then = stores the result. Use float() instead of int() when the value may have a decimal part, such as a CGPA or a price.

To see the effect without needing to type anything, here is the same logic with a hardcoded string standing in for what the user would enter:

Python 3
typed = "25"          # pretend the user typed this
print(type(typed))
print(typed + typed)  # string joining, not addition

age = int(typed)
print(type(age))
print("Next year you will be", age + 1)

Run that and watch typed + typed produce 2525 while age + 1 produces 26. Same characters on screen, entirely different behaviour, decided by type.

Printing more carefully

print with commas works, but it always puts exactly one space between values and gives you no control over formatting. Two extra arguments help:

Python 3
print("a", "b", "c", sep="-")
print("Loading", end="")
print("...", end="")
print(" done")
print("Line one")
print("Line two")

sep sets what goes between values (default: a single space). end sets what goes after the whole line (default: a newline, \n). Setting end="" keeps the next print on the same line, which is how the first three lines above produce Loading... done together.

f-strings

For anything beyond the simplest output, use an f-string. Put f immediately before the opening quote, and then any {...} inside the string is treated as Python code whose result is inserted at that spot.

Python 3
name = "Kavya"
marks = 87
total = 100

print(f"{name} scored {marks} out of {total}.")
print(f"That is {marks / total * 100} percent.")
print(f"Rounded: {marks / total * 100:.2f} percent.")
print(f"Twice the marks would be {marks * 2}.")

Three reasons f-strings are worth learning immediately:

  • No manual conversion. f"Age: {age}" works whether age is an int, float or string. You never need str().
  • The values sit where they appear. Compare f"{name} scored {marks}" with print(name, "scored", marks). The f-string shows the shape of the output directly.
  • Formatting is built in. {value:.2f} means "as a float with two decimal places". That is how you turn 86.99999999999999 into a readable 87.00.

A few formatting specifiers you will actually use:

Written as Effect
{x:.2f} Two decimal places
{x:.0f} No decimal places, rounded
{x:5} Padded to width 5, right-aligned
{x:<8} Padded to width 8, left-aligned
Python 3
subjects = "Maths"
score = 78.456
percent = 0.782

print(f"|{subjects:<10}|{score:>8.2f}|")
print(f"|{'Physics':<10}|{65.5:>8.2f}|")
print(f"Percentage: {percent * 100:.1f}%")

The < and > alignment specifiers are how you print tidy columns without counting spaces by hand.

Putting it together

A complete small program, written with hardcoded values so you can run it here, and with the input() lines shown as comments where they would go:

Python 3
# name = input("Name: ")
# marks_str = input("Marks out of 100: ")
name = "Arjun"
marks_str = "72"

marks = int(marks_str)
grade_points = marks / 10

print(f"Student: {name}")
print(f"Marks:   {marks}/100")
print(f"Points:  {grade_points:.1f}")
print(f"Passed:  {marks >= 40}")

Swapping the hardcoded strings for input() calls is the only change needed to make this interactive. Keeping test values hardcoded while you get the logic right, and only adding input() at the end, is a genuinely useful habit — it saves you retyping the same answers on every run.

Reading several values at once

Each input() call reads one line, so three values normally means three calls. If you would rather the user type them on a single line separated by spaces, split() breaks that line apart:

TEXT
line = input("Enter three marks separated by spaces: ")
parts = line.split()
a = int(parts[0])
b = int(parts[1])
c = int(parts[2])
print("Total:", a + b + c)

split() with no argument splits on any run of whitespace and returns a list of strings — so each piece still needs converting. Here is the same processing on a hardcoded line, which you can run:

Python 3
line = "78 65 91"        # pretend this was typed
parts = line.split()
print(parts)

a = int(parts[0])
b = int(parts[1])
c = int(parts[2])

print(f"Total: {a + b + c}")
print(f"Average: {(a + b + c) / 3:.2f}")

Escape sequences

Inside a string, a backslash gives certain characters a special meaning. The two you will use are \n for a new line and \t for a tab.

Python 3
print("Name\tMarks")
print("Arjun\t72")
print("Kavya\t87")
print("\nReport complete.")
print("She said \"well done\".")

\" lets you put a double quote inside a double-quoted string. The simpler alternative is to wrap the string in single quotes instead: 'She said "well done".'.


Common mistakes

Forgetting to convert, then doing arithmetic. total = input("Marks: ") + 10 raises TypeError. Wrap the input in int() or float().

Converting when you should not. int(input("Name: ")) fails with ValueError as soon as someone types a name. Only convert values that genuinely are numbers.

Putting int() in the wrong place. int(input("Age: ")) is correct. input(int("Age: ")) tries to convert the prompt to a number and fails immediately. Brackets nest inside-out: the innermost call runs first.

Assuming the user types sensibly. If someone types abc when your program expects a number, int() raises ValueError and the program stops. Handling that properly needs try/except, which comes later — for now, just know the crash is your input's fault, not a bug in Python.

Missing the f on an f-string. print("{name} scored {marks}") prints the braces literally. The f prefix is what activates substitution.

Expecting print to return something. x = print("hi") sets x to None. print displays a value; it does not hand one back.

Practice

Try the input and output exercises on the practice page.

Create a free account to track what you have finished.