# 1.
Basic Function Definition
def greet(name):
return f"Hello, {name}!"
print(greet("Rohan"))
# 2. Function with Default Argument
def power(base, exponent=2):
return base ** exponent
print(power(5))
# 3. Lambda Function
square = lambda x: x * x
print(square(6))
# 4. Writing to a Text File
with open("sample.txt", "w") as file:
file.write("Hello, World!")
# 5. Reading from a Text File
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# 6. Appending to a Text File
with open("sample.txt", "a") as file:
file.write("\nWelcome to Python programming.")
# 7. Checking if File Exists
import os
if os.path.exists("sample.txt"):
print("File exists")
else:
print("File does not exist")
# 8. Writing to a CSV File
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
# 9. Reading from a CSV File
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 10. Appending to a CSV File
with open("data.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Bob", 30])
# 11. Writing Dictionary to CSV
data = [{"Name": "Alice", "Age": 25}, {"Name": "Bob", "Age": 30}]
with open("data.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["Name", "Age"])
writer.writeheader()
writer.writerows(data)
# 12. Reading Dictionary from CSV
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
# 13. Writing to a Binary File
data = b"Hello, Binary World!"
with open("binary_file.bin", "wb") as file:
file.write(data)
# 14. Reading from a Binary File
with open("binary_file.bin", "rb") as file:
data = file.read()
print(data)
# 15. Append Data to a Binary File
data = b" More binary data."
with open("binary_file.bin", "ab") as file:
file.write(data)
# 16. Using try-except with File Operations
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
# 17. Function to Write List to Text File
def write_list_to_file(filename, data_list):
with open(filename, "w") as file:
for item in data_list:
file.write(item + "\n")
write_list_to_file("list_data.txt", ["apple", "banana", "cherry"])
# 18. Function to Read List from Text File
def read_list_from_file(filename):
with open(filename, "r") as file:
return [line.strip() for line in file]
print(read_list_from_file("list_data.txt"))
# 19. Using with Statement for File Handling
with open("sample.txt", "r") as file:
content = file.readlines()
print(content)
# 20. Creating and Using a main() Function
def main():
print("This is the main function")
if __name__ == "__main__":
main()
# 21. Writing JSON Data to Text File
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
# 22. Reading JSON Data from Text File
with open("data.json", "r") as file:
data = json.load(file)
print(data)
# 23. Function with Variable-Length Arguments (*args)
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4))
# 24. Function with Keyword Arguments (**kwargs)
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="New York")
# 25. Function to Write and Read Binary Data (String)
def write_binary_string(filename, data):
with open(filename, "wb") as file:
file.write(data.encode())
def read_binary_string(filename):
with open(filename, "rb") as file:
return file.read().decode()
write_binary_string("binary_string.bin", "Hello Binary")
print(read_binary_string("binary_string.bin"))