Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Input / Output in Python

Input and output (I/O) operations are fundamental aspects of any programming language, allowing programs to interact with users and other systems. Python provides straightforward and flexible methods for handling I/O operations, including reading from and writing to the console, files, and other external sources.

Input in Python

input() Function

The input() function is used to get user input from the console. It reads a line from input, converts it to a string, and returns it.

Example

name = input("Enter your name: ")
print("Hello, " + name + "!")

Handling Different Data Types

Since input() returns a string, you may need to convert it to other data types such as integers or floats.

Example

age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print("You are " + str(age) + " years old and " + str(height) + " meters tall.")

Output in Python

print() Function

The print() function is used to output data to the console. It can accept multiple arguments, which are converted to strings and printed with a space between them by default.

Example

print("Hello, world!")
print("The sum of 2 and 3 is", 2 + 3)

String Formatting

Python offers several ways to format strings for output, including concatenation, the format() method, and f-strings (formatted string literals).

Concatenation

name = "Alice"
print("Hello, " + name + "!")

format() Method

name = "Alice"
print("Hello, {}!".format(name))
print("You are {} years old and {} meters tall.".format(age, height))

F-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals using curly braces {}.

name = "Alice"
age = 30
height = 1.75
print(f"Hello, {name}!")
print(f"You are {age} years old and {height} meters tall.")