print("Hello, World!")
name = "Python"
age = 30
print(name, age)
print(name, age, sep='-')
print("Hello", end='!')
print("World")
name = input("Please enter your name: ")
print(f"Hello, {name}!")
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))
with open('example.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\n")
f.writelines(["Line 1\n", "Line 2\n"])
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
f.seek(0)
line = f.readline()
print(line)
f.seek(0)
for line in f:
print(line, end='')
with open('example.txt', 'a', encoding='utf-8') as f:
f.write("\nAppended line")
data = bytes([65, 66, 67])
with open('binary.bin', 'wb') as f:
f.write(data)
with open('binary.bin', 'rb') as f:
binary_data = f.read()
print(binary_data)
name = "Python"
age = 30
print("%s is %d years old" % (name, age))
print("{} is {} years old".format(name, age))
print("{name} is {age} years old".format(name=name, age=age))
print(f"{name} is {age} years old")
num = 42
print(f"{num:03d}")
print(f"{num:5d}")
pi = 3.14159
print(f"{pi:.2f}")
print(f"{pi:10.2f}")
ratio = 0.8523
print(f"{ratio:.1%}")
data = [
["Name", "Age", "City"],
["Alice", 25, "Beijing"],
["Bob", 30, "Shanghai"]
]
for row in data:
print(f"{row[0]:<10}{row[1]:^5}{row[2]:>10}")
from tabulate import tabulate
print(tabulate(data, headers='firstrow', tablefmt='grid'))
from pathlib import Path
path = Path('example.txt')
content = path.read_text(encoding='utf-8')
path.write_text("Hello, World!", encoding='utf-8')
import os.path
file_path = os.path.join('folder', 'example.txt')
if os.path.exists(file_path):
print("File exists!")
try:
with open('nonexistent.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
except IOError as e:
print(f"IO Error: {e}")
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
except ValueError as e:
print(f"Invalid input: {e}")