Python:Python Input and Output (I/O) with print() and input()
Python•Input/Output

Python Input and Output (I/O) with print() and input()

The print() function outputs data to the standard output stream, supporting separators and custom line endings. The input() function reads a line from stdin as a string.

Syntax

print(*objects, sep=" ", end="\n") user_value = input(prompt)

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
*objectsAnyZero or more values to print.
sepstr (optional)String inserted between values, default space.
endstr (optional)String appended after the last value, default newline.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python Console I/O & Formatting
server_name = "Cloud-Node-1"
port = 8080
status = "ONLINE"

# Customized separator and end character
print("Cluster", "Status", "Report", sep=" | ")
print(f"Host: {server_name}", end=" ---> ")
print(f"Port: {port} [{status}]")

# Numeric formatting with f-strings
memory_used_gb = 7.4561
print(f"RAM Usage: {memory_used_gb:.2f} GB ({memory_used_gb * 1024:.0f} MB)")
Expected Output:
Cluster | Status | Report
Host: Cloud-Node-1 ---> Port: 8080 [ONLINE]
RAM Usage: 7.46 GB (7635 MB)

How It Works: Step-by-Step

  • Line 7: Uses sep=" | " to replace default whitespace separation.
  • Line 8: Uses end=" ---> " to keep subsequent print call on the same line.
  • Line 13: Formats float to 2 decimal places with :.2f and whole number with :.0f.

Key Concepts

  • print() automatically adds a newline unless overridden by end="".
  • f-strings (formatted string literals) allow inline expressions and format specifiers.
  • input() always returns a string; wrap with int() or float() to parse numbers.

Common Mistake: Forgetting that input() always returns a string

Adding numbers directly from input() will concatenate them as strings instead of doing math.

❌ Incorrect
val = "10"
result = val + 5 # TypeError: can only concatenate str to str
✅ Correct
val = "10"
result = int(val) + 5 # Result is 15

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler