Skip to content

Python Input and Output Functions

Python provides simple and efficient built-in functions for interacting with users through input and output operations. These functions allow data to be read from the user (input) and displayed back to the user (output).


1. Input Function: input()

The input() function is used to take input from the user in Python. It always returns the input as a string.

Syntax

variable = input(prompt)

Parameters

  • prompt: A string displayed to the user as a message (optional).

Example

name = input(“Enter your name: “)

print(“Hello, ” + name)

Type Casting for Numeric Input

Since input() returns a string, you need to explicitly convert it to the desired type (e.g., int, float).

age = int(input(“Enter your age: “))

print(“You are”, age, “years old.”)

Advanced Input Handling

You can handle invalid input using exception handling:

try:

    num = int(input(“Enter a number: “))

    print(“You entered:”, num)

except ValueError:

    print(“Invalid input. Please enter a number.”)


2. Output Function: print()

The print() function is used to display output on the screen. It can handle multiple values, data types, and formatting options.

Syntax

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

Parameters

  1. *objects: The values to be printed. Multiple values can be separated by commas.
  2. sep: The separator between multiple objects. Default is a space (‘ ‘).
  3. end: Determines the string appended after the last value. Default is a newline (‘\n’).
  4. file: Specifies the output stream. Default is sys.stdout.
  5. flush: If True, forces the stream to be flushed.

Example

  1. Simple Print

print(“Hello, World!”)

  • Printing Multiple Values

name = “Alice”

age = 25

print(“Name:”, name, “Age:”, age)

  • Using sep Parameter

print(“apple”, “banana”, “cherry”, sep=”, “)

# Output: apple, banana, cherry

  • Using end Parameter

print(“Hello”, end=” “)

print(“World!”)

# Output: Hello World!

  • Redirecting Output to a File

with open(“output.txt”, “w”) as file:

    print(“Hello, File!”, file=file)


3. String Formatting in Output

Python provides various methods for formatting output:

a. Using Concatenation

name = “Alice”

age = 25

print(“Name: ” + name + “, Age: ” + str(age))

b. Using format() Method

name = “Alice”

age = 25

print(“Name: {}, Age: {}”.format(name, age))

c. Using f-strings (Python 3.6+)

name = “Alice”

age = 25

print(f”Name: {name}, Age: {age}”)

d. Formatting Numbers

pi = 3.14159

print(“Value of pi: {:.2f}”.format(pi))  # Output: 3.14


4. Reading Multiple Inputs

a. Using input() Separately

name = input(“Enter your name: “)

age = int(input(“Enter your age: “))

print(f”Name: {name}, Age: {age}”)

b. Using a Single input() with split()

You can read multiple inputs in a single line.

x, y = input(“Enter two numbers separated by space: “).split()

print(“First number:”, x)

print(“Second number:”, y)

c. Converting Input to Specific Data Types

x, y = map(int, input(“Enter two integers: “).split())

print(“Sum:”, x + y)


5. Advanced Print Customizations

a. Printing Escape Sequences

  • \n for newline
  • \t for tab
  • \\ for backslash

print(“Hello\nWorld”)  # Newline

print(“Hello\tWorld”)  # Tab

b. Printing Unicode Characters

print(“\u2764”)  # Output: ❤ (Heart symbol)

c. Aligning Output

# Right-align, Left-align, Center-align

print(“{:>10}”.format(“Right”))   # Output: ‘     Right’

print(“{:<10}”.format(“Left”))    # Output: ‘Left     ‘

print(“{:^10}”.format(“Center”))  # Output: ‘  Center  ‘


6. Common Use Cases

a. User Input for Calculations

x = float(input(“Enter the first number: “))

y = float(input(“Enter the second number: “))

print(f”The sum is: {x + y}”)

b. Logging Output

print(“INFO: The program started successfully.”)

c. Interactive Programs

name = input(“What is your name? “)

print(f”Hello, {name}! Welcome to Python.”)


7. Best Practices

  1. Use Descriptive Prompts:

age = int(input(“Please enter your age: “))

  • Handle Errors in Input:

try:

    num = int(input(“Enter a number: “))

except ValueError:

    print(“Invalid input! Please enter a valid number.”)

  • Use f-strings for Better Readability:

print(f”Name: {name}, Age: {age}”)

  • Avoid Excessive Input/Output Statements:
    • Combine them logically to keep code concise and clear.

Conclusion

Python’s input() and print() functions provide robust mechanisms for interactive programs. By mastering input/output operations and formatting techniques, you can create user-friendly applications and scripts effectively.