Tutorials Logic, IN info@tutorialslogic.com

User Input Output in Python print, input

Python Input

input() always returns text, even when the user types digits.

Use conversion functions such as int() or float() only after deciding what kind of value the program needs.

Good beginner input code explains what to type, validates the answer, and prints results in a readable format.

print Output

The print() function outputs text to the console. It's the most basic way to display information.

print() Function

print() Function
print("Hello, World!")
print(42)
print("Name:", "Alice", "Age:", 25)
print("a", "b", "c", sep="-")
print("a", "b", "c", sep="")
print("Hello", end=" ")
print("World")

with open("log.txt", "w", encoding="utf-8") as file:
    print("Log entry", file=file)

input Function

The input() function reads a line from the user. It always returns a string - convert it if you need a number.

Read and Convert Console Input

Read and Convert Console Input
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# input() always returns a string - convert as needed
age_str = input("Enter your age: ")
age = int(age_str)
print(f"In 10 years you'll be {age + 10}")

# One-liner conversion
height = float(input("Enter your height in meters: "))

# Multiple inputs on one line
x, y = input("Enter two numbers separated by space: ").split()
x, y = int(x), int(y)
print(f"Sum: {x + y}")

# Read a list of numbers
numbers = list(map(int, input("Enter numbers: ").split()))
print(f"Sum: {sum(numbers)}")
print(f"Max: {max(numbers)}")

Input Validation

Validating Input

Validating Input
# Keep asking until valid input
def get_int(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please enter a valid integer.")

age = get_int("Enter your age: ")
print(f"Age: {age}")

# Validate within a range
def get_score() -> int:
    while True:
        try:
            score = int(input("Enter score (0-100): "))
            if 0 <= score <= 100:
                return score
            print("Score must be between 0 and 100.")
        except ValueError:
            print("Please enter a number.")

# Yes/No prompt
def ask_yes_no(question: str) -> bool:
    while True:
        answer = input(f"{question} (y/n): ").strip().lower()
        if answer in ("y", "yes"):
            return True
        if answer in ("n", "no"):
            return False
        print("Please enter y or n.")

if ask_yes_no("Continue-"):
    print("Continuing...")

Formatted Output

Align Values with f-strings

Align Values with f-strings
students = [
    ("Alice", 20, 95.5),
    ("Bob", 22, 87.0),
    ("Charlie", 21, 92.3),
]

print(f"{'Name':<10} {'Age':>4} {'Score':>7}")
print("-" * 25)
for name, age, score in students:
    print(f"{name:<10} {age:>4} {score:>7.1f}")

for step in range(1, 6):
    print(f"\rProgress: {step}/5", end="", flush=True)
print()
Input-output check

Can You Read Input and Print Clear Output?

4 checks
  • The print() function outputs text to the console.
  • It's the most basic way to display information.
  • The input() function reads a line from the user.
  • It always returns a string - convert it if you need a number.

Input Decisions

0 of 2 checked

Q1. Why should raw input often be stripped?

Q2. What should repeated input validation become?

Input Conversion Traps

  • Forgetting input returns text

    Convert the input result before arithmetic, even if the user types digits.
  • Trusting raw input

    Trim spaces and validate required values before using them.
  • Repeating prompts everywhere

    Move repeated input-and-validate logic into a helper function.

Try this next

Ask, Convert, and Print

0 of 3 completed

  1. Ask for age, convert it to int, and print next year's age.
  2. Keep asking until the user enters at least one non-space character.
  3. Write read_int(prompt) that returns a converted integer.

Questions About Input Output

Keyboard input arrives as text. Python waits for you to decide whether that text should become an int, float, date, or another type.

Validate first or use a focused try except around the conversion. Then show a clear message and ask again if needed.

No. Many functions should return data, while the main program decides how to print or display it.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.