Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

User Input Output in Python print, input: Tutorial, Examples, FAQs & Interview Tips

Output with print()

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

print() Function
print("Hello, World!")
print(42)
print(3.14)
print(True)

# Multiple values - separated by space by default
print("Name:", "Alice", "Age:", 25)   # Name: Alice Age: 25

# Custom separator
print("a", "b", "c", sep="-")        # a-b-c
print("a", "b", "c", sep="")         # abc

# Custom end (default is newline \n)
print("Hello", end=" ")
print("World")                        # Hello World (on one line)

# Print to a file
with open("log.txt", "w") as f:
    print("Log entry", file=f)

# Pretty print complex objects
import pprint
data = {"name": "Alice", "scores": [95, 87, 92], "active": True}
pprint.pprint(data)

User Input with input()

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

input() Function
# 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
# 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

Formatted Output
# tl-table-style output
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}")

# Output:
# Name        Age   Score
# -------------------------
# Alice        20    95.5
# Bob          22    87.0
# Charlie      21    92.3

# Progress indicator
import time
for i in range(1, 6):
    print(f"\rProgress: {i}/5", end="", flush=True)
    time.sleep(0.5)
print()  # newline after loop

Ready to Level Up Your Skills?

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