PythonMastery
beginner 18 min read · lesson 6 of 19 in Python Fundamentals

Input & Output: Talking to Your User

1 · The lesson

read

A program that calculates something but never shows the result is not much use. A useful program needs to show information to the user (output) and get information from the user (input).

This lesson covers everything you need to make your programs interactive: print() in depth, input(), type conversion (the part where almost every beginner makes a mistake), and a safe pattern for handling bad input.


1. Output: print() in Depth

You've seen print() before. Here is what else it can do.

python
# Pass several values. print puts a space between them by default
print("Hello", "world", 2026)             # Hello world 2026

# Change the separator between values
print("apple", "banana", "cherry", sep=", ")
# apple, banana, cherry

# Change what's printed at the end (default is "\n", a new line)
print("Loading", end="...")
print("done")
# Loading...done

# Print to standard error instead of standard output (for warnings/errors)
import sys
print("Something went wrong", file=sys.stderr)

The sep and end arguments are small but useful. They let you control the output format without building the string yourself.


2. Input: Getting Data from the User

input() is how a Python program reads what the user types. When the program hits an input() call, it pauses and waits for the user to type something and press Enter.

python
name = input("What is your name? ")
print(f"Hello, {name}!")

The argument to input() is the prompt: the text shown before the user types. Always end the prompt with a space ("...? "). Otherwise the user's answer appears directly after the question mark, with no space.

Note: input() works here. Press Run and an answer box opens under the code: type your answer and press Enter.


3. The Most Important Rule

input() always returns a string. Always. Even if the user types 42, you get the string "42".

Almost every Python beginner makes a mistake with this at least once. Look at this example:

python
# Pretend this came from input(), which always returns a string
age_text = "25"            # This is what input() would give us

# The first attempt crashes, because you can't add 1 to a string:
# print(age_text + 1)      # TypeError!

# The fix: convert the string to a number before doing math:
age = int(age_text)
print(f"Next year you will be {age + 1}")     # Next year you will be 26

If you want a number, you must convert the string yourself. That's what the next section is about.


4. Type Conversion: int(), float(), str(), bool()

Python gives you four conversion functions for the basic types. Each takes a value and tries to produce the matching type.

python
# Turn a string into an integer
n = int("42")
print(n, type(n))                  # 42 <class 'int'>

# Turn a string into a float (a decimal number)
price = float("19.99")
print(price, type(price))          # 19.99 <class 'float'>

# Turn a number into a string
score = 95
label = str(score)
print(label, type(label))          # 95 <class 'str'>

# Turn anything into a boolean (zero and empty values become False)
print(bool(0))                     # False
print(bool(""))                    # False
print(bool("hello"))               # True
print(bool([]))                    # False
print(bool([1, 2]))                # True

Using float(): float() accepts both ints and strings, so float("3") gives 3.0, and float(3) also gives 3.0. This is useful when you don't know if the input will have a decimal point.

A common mistake with int(): int("3.5") raises an error. int() only parses whole-number strings. Use int(float("3.5")) if you want to drop the decimal part, or round(float("3.5")) if you want to round.

python
# This works:
print(int("3"))                    # 3
print(int(3.9))                    # 3 (int() cuts off the decimal part and does not round)

# This crashes:
# print(int("3.5"))                # ValueError: invalid literal for int()

# This is the safe pattern:
print(int(float("3.5")))           # 3 (reads the number, then cuts off the decimal part)
print(round(float("3.5")))         # 4 (rounds to the nearest whole number)

5. The Real-World Pattern: input() + conversion

Combining everything you've learned, here is how most beginner Python programs start:

python
# Pretend the user typed "100" at the prompt
user_input = "100"                 # in real code: input("How much? ")

# Convert right away, so the rest of your code works with a number
amount = float(user_input)

# Now you can do math
tip = amount * 0.18
total = amount + tip

print(f"Tip: ${tip:.2f}")          # Tip: $18.00
print(f"Total: ${total:.2f}")      # Total: $118.00

The :.2f inside the f-string formats the number to 2 decimal places, which is what you usually want for money.


6. Safe Input: Handling Bad Data

What if the user types "abc" when you asked for a number? int("abc") raises a ValueError and your program crashes.

Real programs handle this with try/except. A later lesson covers it fully, but here is the pattern you will use:

python
user_input = "not a number"        # what the user might type

try:
    amount = float(user_input)
    print(f"You entered: {amount}")
except ValueError:
    print("That doesn't look like a number. Please try again.")

When float() raises a ValueError, the except block catches it and we print a friendly message instead of crashing. A program that real people use needs this kind of error handling.


7. Mistakes You'll Hit

1. Forgetting to convert

python
# This crashes, because you can't add a number to text
# age = input("Age: ") + 1

Fix: always convert immediately after input().

2. No trailing space in the prompt

python
# Ugly: the cursor sits right against the colon
name = input("Name:")
# Better
name = input("Name: ")

3. Using int() on a decimal string

python
# Crashes
# int("3.5")
# Works
int(float("3.5"))

4. Forgetting that print() adds a newline

python
print("Loading")
print("done")
# Two lines. If you want them joined:
print("Loading", end="")
print("done")


8. A Mini Program: Everything Together

python
# A simple unit converter from Celsius to Fahrenheit
# (This pretends to read input. In your own program, use input("...") instead of "100")

celsius_text = "100"

try:
    celsius = float(celsius_text)
    fahrenheit = (celsius * 9 / 5) + 32
    print(f"{celsius}°C = {fahrenheit}°F")
except ValueError:
    print(f"'{celsius_text}' is not a valid temperature.")

That's a working program. Change celsius_text and click Run. Then try a value that is not a number, and see the except block run.


🎯 Your Turn: Print a Receipt That Lines Up

Columns that don't line up make a program's output hard to read. Write
print_receipt(items) where items is a list of (name, quantity, unit_price)
tuples, and print a receipt whose columns line up no matter how long the names
are.

Names left-aligned in 14 characters, quantity right-aligned in 3, line total
right-aligned in 9 with two decimals.

python
Tea             2    90.00
Filter Coffee   1   120.00
Masala Dosa     3   240.00
------------------------------
TOTAL               450.00

Skeleton:

python
def print_receipt(items):
    total = 0
    for name, qty, price in items:
        line_total = qty * price
        # TODO 1: add line_total to total
        # TODO 2: print name, qty and line_total using f-string alignment
        ...
    # TODO 3: print the dashed line and the TOTAL row, lined up with the column above
    ...

print_receipt([("Tea", 2, 45.0), ("Filter Coffee", 1, 120.0), ("Masala Dosa", 3, 80.0)])
Hint 1: You set the alignment inside the f-string After the colon in an f-string placeholder you can give an alignment and a width: {name:<14} pads on the right to 14 characters, {qty:>3} pads on the left to 3. Combine with a format spec for decimals: {amount:>9.2f}.
Hint 2: The TOTAL row must match the columns above it The amount column starts after 14 + 3 characters of earlier columns. Pad the word TOTAL to that same width so the numbers stack: f"{'TOTAL':<17}{total:>9.2f}".
Show full solution
python
def print_receipt(items):
    total = 0
    for name, qty, price in items:
        line_total = qty * price
        total += line_total
        print(f"{name:<14}{qty:>3}{line_total:>9.2f}")

    print("-" * 30)
    print(f"{'TOTAL':<17}{total:>9.2f}")


print_receipt([
    ("Tea", 2, 45.0),
    ("Filter Coffee", 1, 120.0),
    ("Masala Dosa", 3, 80.0),
])

Three format specs do all the work. :<14 left-aligns and pads names to a fixed
width, :>3 and :>9.2f right-align the numbers so the decimal points stack in
a straight line. Right-alignment makes a column of money easy to read: the
digits line up by place value, so you can quickly see which amounts are bigger.


What You Learned

  • print() sends output to the screen. Use sep, end, file to control formatting.
  • input() waits for the user to type and press Enter. It always returns a string.
  • Convert straight after input(), usually with int() or float(). (Be careful with bool(): bool("False") is True, because any non-empty string is truthy.)
  • int() only parses whole-number strings. Use int(float(x)) for decimals.
  • Wrap in try/except ValueError when you want to handle bad input without crashing.

You now have everything you need to build interactive Python programs. The next lesson covers strings in depth: the text your programs read and print.

Next: Working with Strings.


Source: adapted from Python official documentation Section 7 (Input and Output). PSF License.

Practice this

on practicepython.in

Short exercises that run in your browser and tell you what your code did, as well as whether a test passed.

Found this useful? Share it with a friend who’s learning Python.