Home Python Python Input and Output Explained — print(), input() and Formatting

Python Input and Output Explained — print(), input() and Formatting

In Plain English 🔥
Think of a Python program like a vending machine. You press buttons to put information IN (that's input), and the machine displays or dispenses something back OUT (that's output). The print() function is your program's way of talking to you — like the screen on the vending machine. The input() function is how your program listens — like the keypad you type on. That's literally it.
⚡ Quick Answer
Think of a Python program like a vending machine. You press buttons to put information IN (that's input), and the machine displays or dispenses something back OUT (that's output). The print() function is your program's way of talking to you — like the screen on the vending machine. The input() function is how your program listens — like the keypad you type on. That's literally it.

Every useful program in the world does two things: it accepts information from somewhere, and it sends information somewhere else. Google takes your search query (input) and shows you results (output). A calculator takes numbers (input) and shows the answer (output). Without input and output, a program is just a silent machine locked in a room — it can't communicate with anything or anyone. That's why this is the very first real skill you need as a Python developer.

Before input and output, you could write code that calculated things internally, but you'd have no way to see results or respond to a user. You'd be flying blind. Python's built-in print() and input() functions solve this completely. They are the bridge between your code and the real world — the moment your program stops being a private monologue and starts becoming a conversation.

By the end of this article you'll know how to display any message or value to the screen using print(), how to ask a user for information with input(), how to format output cleanly using f-strings, and how to avoid the three classic mistakes that trip up almost every beginner. You'll be ready to build interactive programs from scratch.

Displaying Information with print() — Your Program's Voice

The print() function is how Python speaks to you. Every time you call it, Python takes whatever you put inside the parentheses and displays it in the terminal or console. It then automatically moves to a new line, ready for the next thing — like pressing Enter after you finish typing a sentence.

You can print plain text (called a string) by wrapping it in quotes. You can print numbers without any quotes at all. You can even print multiple things in one go by separating them with commas — Python will put a space between each item automatically.

Here's the thing beginners often miss: print() is a function, which means it does a job and you trigger it by writing its name followed by parentheses. Everything you want it to display goes inside those parentheses. That pair of parentheses is not optional — it's what actually runs the function. In older Python 2 code you might see print without parentheses, but in Python 3 (which is what everyone should be using) the parentheses are required.

hello_world_output.py · PYTHON
123456789101112131415161718192021
# print() sends text or values to the terminal for the user to see

# Printing a simple text message — wrap text in quotes to make it a string
print("Hello! Welcome to TheCodeForge.")

# Printing a number — no quotes needed for numbers
print(42)

# Printing multiple items separated by commas — Python adds a space between them
print("Your score is:", 95, "out of 100")

# Printing a blank line — call print() with nothing inside to create spacing
print()

# Using the 'sep' argument to change what goes between items (default is a space)
print("2024", "01", "15", sep="-")  # Useful for formatting dates

# Using the 'end' argument to control what appears at the end of the line
# Default is a newline character. Here we replace it with a space.
print("Loading", end=" ")
print("complete!")  # This continues on the same line as 'Loading'
▶ Output
Hello! Welcome to TheCodeForge.
42
Your score is: 95 out of 100

2024-01-15
Loading complete!
⚠️
Pro Tip:Use print() with sep and end arguments when you want precise control over formatting. For example, print("Error", end="\n\n") adds a blank line after your message — handy for making terminal output readable without calling print() twice.

Getting Information with input() — Your Program's Ears

If print() is how your program talks, input() is how it listens. When Python hits an input() call, it pauses everything, displays a prompt message to the user, and waits — patiently — until the user types something and presses Enter. Whatever the user typed gets handed back to your program as a value you can store and use.

The message you put inside input() is the prompt — it's what tells the user what to type. Always write a clear, friendly prompt. 'Enter your name: ' is good. '' (nothing) is confusing — the program just freezes and the user has no idea why.

Here's the most important rule about input() that catches almost every beginner: it always returns a string. Always. Even if the user types 42, Python gives you back the text '42', not the number 42. This means if you want to do maths with what the user typed, you must convert it first using int() for whole numbers or float() for decimals. We'll see exactly how to do that in the code below.

user_input_demo.py · PYTHON
1234567891011121314151617181920212223
# input() pauses the program and waits for the user to type something
# Whatever they type is returned as a STRING — remember this rule!

# Asking for the user's name — the string inside input() is the prompt they see
user_name = input("What is your name? ")

# Now user_name holds whatever the user typed, as a string
print("Nice to meet you,", user_name)

# Asking for a number — input() still returns a string here
raw_age = input("How old are you? ")

# We MUST convert it to an integer before we can do maths with it
# int() converts the string '25' into the actual number 25
user_age = int(raw_age)

# Now we can use it in a calculation
year_born = 2024 - user_age
print("You were born around the year", year_born)

# You can also do the conversion directly in one line (very common pattern)
favourite_number = int(input("Enter your favourite number: "))
print("Double your favourite number is:", favourite_number * 2)
▶ Output
What is your name? Alex
Nice to meet you, Alex
How old are you? 28
You were born around the year 1996
Enter your favourite number: 7
Double your favourite number is: 14
⚠️
Watch Out:Never do maths directly on what input() returns without converting it first. Writing age + 5 when age is still a string will crash your program with a TypeError. Always wrap with int() or float() before any arithmetic.

Formatting Output Beautifully with f-strings

Concatenating strings with + signs gets messy fast. Imagine building a sentence like 'Hello Alex, you are 28 years old' by gluing variables and text together — you'd need to remember to convert numbers back to strings, add spaces carefully, and the code becomes hard to read. There's a much better way: f-strings.

An f-string (short for formatted string literal) lets you embed variables directly inside a string by prefixing the string with the letter f and wrapping variable names in curly braces {}. Python replaces {variable_name} with the actual value when the line runs. It handles the type conversion automatically — no need to call str() on numbers.

f-strings were introduced in Python 3.6 and are now the industry standard for formatting output. They're faster than the older .format() method, cleaner than concatenation, and far more readable. Senior developers use them constantly. Learn them early and use them always.

fstring_formatting.py · PYTHON
1234567891011121314151617181920212223242526272829
# f-strings: prefix the string with f, then put variable names inside {}
# Python swaps the {} placeholders with the actual variable values at runtime

player_name = "Jordan"
player_score = 4750
player_level = 12

# Basic f-string — clean, readable, no type conversion needed
print(f"Player: {player_name}")
print(f"Score: {player_score}")
print(f"Level: {player_level}")

print()  # blank line for spacing

# You can even do calculations inside the curly braces
best_possible_score = 5000
percentage = (player_score / best_possible_score) * 100
print(f"{player_name} achieved {percentage}% of the maximum score.")

# Controlling decimal places — :.2f means 'show 2 digits after the decimal point'
item_price = 4.5
quantity = 3
total_cost = item_price * quantity
print(f"Total cost: ${total_cost:.2f}")  # Shows 13.50, not 13.5

# Padding numbers for aligned columns — useful for receipts or tables
print(f"{'Item':<15} {'Qty':>5} {'Price':>8}")
print(f"{'Coffee':<15} {2:>5} {3.50:>8.2f}")
print(f"{'Muffin':<15} {1:>5} {2.75:>8.2f}")
▶ Output
Player: Jordan
Score: 4750
Level: 12

Jordan achieved 95.0% of the maximum score.
Total cost: $13.50
Item Qty Price
Coffee 2 3.50
Muffin 1 2.75
🔥
Interview Gold:Interviewers love asking about string formatting in Python. If asked 'how do you format strings?', mention f-strings and explain that :.2f inside the braces controls decimal precision. Knowing the alignment specifiers (< for left, > for right) puts you ahead of most candidates.

Building a Real Interactive Program — Putting It All Together

Knowing print() and input() separately is like knowing how to hold a guitar and how to press a string — useful, but the music only happens when you combine them. Here we'll build a small, real program: a personal budget calculator. It takes user input, processes it, and displays a formatted summary.

This example shows you the natural rhythm of an interactive Python program: prompt the user, collect their input, convert it to the right type, do something useful with it, then display the result clearly. This exact pattern — input, process, output — is the foundation of almost every program ever written, from mobile apps to banking systems.

Read through the code carefully. Every line has a comment explaining its purpose. After reading this, try changing the program to also ask for the user's monthly income and calculate how much they're saving. That hands-on practice will make this stick.

budget_calculator.py · PYTHON
12345678910111213141516171819202122232425262728293031323334353637
# A simple monthly budget calculator
# Demonstrates input(), int()/float() conversion, f-strings and print() together

print("===== Monthly Budget Calculator =====")
print()  # blank line for visual breathing room

# Collect the user's name for a personalised experience
user_name = input("Enter your name: ")

# Collect financial figures — wrap with float() to allow decimal amounts like 1250.50
monthly_income = float(input("Enter your monthly income ($): "))
rent = float(input("Enter your monthly rent ($): "))
groceries = float(input("Enter your monthly grocery bill ($): "))
utilities = float(input("Enter your monthly utilities ($): "))

# Calculate totals — all values are now proper floats, so maths works correctly
total_expenses = rent + groceries + utilities
remaining_balance = monthly_income - total_expenses

# Calculate what percentage of income is spent on expenses
spending_percentage = (total_expenses / monthly_income) * 100

print()  # blank line before the summary
print("===== Budget Summary for", user_name, "=====")

# f-strings with :.2f formatting keep all dollar amounts to exactly 2 decimal places
print(f"  Monthly Income:    ${monthly_income:>10.2f}")
print(f"  Total Expenses:    ${total_expenses:>10.2f}")
print(f"  Remaining Balance: ${remaining_balance:>10.2f}")
print()
print(f"  You spent {spending_percentage:.1f}% of your income this month.")

# Give the user a personalised message based on their financial situation
if remaining_balance >= 0:
    print(f"  Great work, {user_name}! You stayed within your budget.")
else:
    print(f"  Heads up, {user_name} — you exceeded your budget this month.")
▶ Output
===== Monthly Budget Calculator =====

Enter your name: Maria
Enter your monthly income ($): 3000
Enter your monthly rent ($): 950
Enter your monthly grocery bill ($): 300
Enter your monthly utilities ($): 120

===== Budget Summary for Maria =====
Monthly Income: $ 3000.00
Total Expenses: $ 1370.00
Remaining Balance: $ 1630.00

You spent 45.7% of your income this month.
Great work, Maria! You stayed within your budget.
⚠️
Pro Tip:Notice how all the input() calls are grouped at the top and all the print() calls are grouped at the bottom. This is called the input-process-output pattern and it makes programs far easier to debug. When something goes wrong, you immediately know which phase to look at.
Feature / Aspectprint()input()
PurposeSends data OUT to the terminalBrings data IN from the user
Return valueReturns None (gives nothing back)Returns the typed text as a string
Requires quotes for text?Yes — text must be in quotesYes — the prompt must be in quotes
Handles numbers directly?Yes — prints numbers without conversionNo — always returns a string, must convert
Pauses the program?No — runs instantlyYes — waits until user presses Enter
Common partner functionf-strings for formattingint() or float() for numeric conversion
Typical position in programMiddle and end — showing resultsBeginning — collecting what's needed

🎯 Key Takeaways

  • print() sends information to the terminal — it accepts text, numbers, and multiple comma-separated values in a single call
  • input() always returns a string — convert with int() or float() before doing any arithmetic on user-provided numbers
  • f-strings (prefix a string with f and use {} for variable names) are the modern, readable standard for formatting output — use :.2f inside braces to control decimal precision
  • The input-process-output pattern — collect all inputs first, compute in the middle, display results at the end — keeps programs clean, readable and easy to debug

⚠ Common Mistakes to Avoid

  • Mistake 1: Doing maths on input() without converting it first — Symptom: TypeError: can only concatenate str (not 'int') to str, or getting '55' instead of 10 when adding 5+5 typed by the user — Fix: Always wrap input() with int() or float() before arithmetic: age = int(input('Enter age: '))
  • Mistake 2: Forgetting quotes around the prompt inside input() — Symptom: NameError: name 'Enter your name' is not defined — Python thinks the prompt is a variable name, not a string — Fix: Always use quotes: input('Enter your name: ') not input(Enter your name: )
  • Mistake 3: Using + to join strings and numbers in print() — Symptom: TypeError: can only concatenate str (not 'int') to str when writing print('Your score is: ' + score) where score is an integer — Fix: Either use a comma instead (print('Your score is:', score)) or use an f-string (print(f'Your score is: {score}')) — both handle the type difference automatically

Interview Questions on This Topic

  • QWhat does input() always return in Python, and why does that matter when you ask a user for a number?
  • QWhat is an f-string and how does it differ from using the + operator to concatenate strings? When would you prefer one over the other?
  • QIf a user types '5' into an input() prompt and you add it to the integer 10 without any conversion, what happens and why? How would you fix it?

Frequently Asked Questions

How do I get a number from the user in Python?

Use input() to collect the text, then immediately wrap it with int() for whole numbers or float() for decimals. The pattern is: age = int(input('Enter your age: ')). Never skip the conversion step — input() always returns a string even if the user types digits.

What is the difference between print() and input() in Python?

print() sends data out to the screen — it's one-way communication from your program to the user. input() does the opposite: it shows a prompt and waits for the user to type something, then sends that typed value back into your program. One speaks, the other listens.

Why does Python's input() return a string even when I type a number?

Because input() has no way to know what the user intends to type — it could be a name, a number, a date, or anything. To keep things safe and predictable, it always hands back raw text (a string). It's your job to convert it to the right type using int(), float(), or any other conversion function once you know what you're expecting.

🔥
TheCodeForge Editorial Team Verified Author

Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.

← PreviousOperators in PythonNext →Type Conversion in Python
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged