Py Chapter 2 Topic 1
Py Chapter 2 Topic 1
Python provides several ways to handle input and output (I/O) operations. These
operations are fundamental in programming as they allow interaction between the
user and the program.
1. Input in Python
Python has a built-in function called input() that is used to take input from the
user. By default, the input is treated as a string, so you may need to convert it to
other data types like integers or floats if necessary.
Syntax:
input(prompt)
Example:
Since input() returns a string, you may need to convert it using functions like
int(), float(), etc.
2. Output in Python
Syntax:
Basic Usage:
print("Hello, World!")
Printing Multiple Values:
name = "Alladi"
age = 25
print("Name:", name, "Age:", age)
Changing the Separator:
By default, Python separates items with a space. You can change this using the
sep parameter.
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry
Changing the End Character:
The end parameter defines what to print at the end of the output. By default, it's a
newline (\n).
Python offers various ways to format strings for output. The most common
methods are:
name = "Bob"
age = 30
print("Name: " + name + ", Age: " + str(age))
name = "Alladi"
age = 25
print("Name: {}, Age: {}".format(name, age))
pi = 3.14159
print(f"Value of pi: {pi:.2f}")
Python can also handle I/O with files. You can read from or write to files using the
built-in open() function.
Opening a File:
Examples
name = "Alice"
balance = 1234.56
print(f"{name}, your account balance is:
${balance:,.2f}")
# Output: Alice, your account balance is: $1,234.56
Example 3: Reading and Writing Files
# Writing to a file
with open('data.txt', 'w') as file:
file.write("Python is fun!\n")