Introduction Python Basic Input:
Python provides several built-in functions for input and output operations. Here are some basic input and output techniques in Python:
Output:
print(): The print() function is used to display output on the console. It can be used to print variables, literals, and expressions. For example:
print("Hello, World!") # Prints the string "Hello, World!"
x = 10
print("The value of x is:", x) # Prints "The value of x is: 10"
y = 3
print("The sum of x and y is:", x + y) # Prints "The sum of x and y is: 13"
Input:
input(): The input() function is used to read user input from the console. It displays a prompt and waits for the user to enter a value. The value entered by the user is returned as a string. For example:
name = input("Enter your name: ")
print("Hello,", name) # Prints a personalized greeting
age = input("Enter your age: ")
age = int(age) # Convert the input to an integer
print("You were born in", 2023 - age) # Calculates the birth year based on the age
Formatted Output:
str.format(): The format() method is used to format strings by replacing placeholders with corresponding values. Placeholders are represented by curly braces {} in the string, which can be replaced with variables or expressions. For example:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Prints "My name is Alice and I am 25 years old."
x = 3
y = 4
print("The sum of {} and {} is {}.".format(x, y, x + y))
# Prints "The sum of 3 and 4 is 7."
File I/O:
open(): The open() function is used to open a file for reading or writing. It returns a file object that can be used to perform various file operations. For example:
# Writing to a file
file = open("output.txt", "w") # Opens the file in write mode
file.write("Hello, World!") # Writes the string to the file
file.close() # Closes the file
# Reading from a file
file = open("input.txt", "r") # Opens the file in read mode
contents = file.read() # Reads the entire file contents
print(contents) # Prints the file contents
file.close() # Closes the file
with statement: The with statement provides a convenient way to handle file objects. It automatically takes care of closing the file after its usage, even if an exception occurs. For example:
# Writing to a file using 'with'
with open("output.txt", "w") as file:
file.write("Hello, World!")
# Reading from a file using 'with'
with open("input.txt", "r") as file:
contents = file.read()
print(contents)
These are some of the basic input and output operations in Python. Python also provides many additional functionalities and libraries for more advanced input and output tasks