10-1
with open('learning_Python.txt') as pro:
article = pro.read()
print(article)
with open('learning_Python.txt') as pro:
for line in pro:
print(line.rstrip())
lines = []
with open('learning_Python.txt') as pro:
lines = pro.readlines()
for line in lines:
print(line.rstrip())
10-2
with open('learning_Python.txt') as pro:
article = pro.read()
print(article.replace('Python', 'C'))
with open('learning_Python.txt') as pro:
for line in pro:
print(line.replace('Python', 'C').rstrip())
lines = []
with open('learning_Python.txt') as pro:
lines = pro.readlines()
for line in lines:
print(line.replace('Python', 'C').rstrip())
10-3
name = input('Please enter your name:\n')
with open('guest.txt', 'w') as pro:
pro.write(name)
10-4
while True:
name = input('Please enter your name:\n')
print('Thank you for using this system!')
with open('guest_book.txt','a') as pro:
pro.write(name + 'have used this system.\n')
10-6
try:
num1 = input('Please enter the first number:\n')
num2 = input('Please enter the second number:\n')
num1 = int(num1)
num2 = int(num2)
except ValueError or TypeError:
print('Sorry, please enter the valid number.')
else:
print(num1 + num2)
10-7
while True:
try:
num1 = input('Please enter the first number:\n')
num2 = input('Please enter the second number:\n')
num1 = int(num1)
num2 = int(num2)
except ValueError or TypeError:
print('Sorry, please enter the valid number.')
continue
else:
print(num1 + num2)
10-8
try:
with open('cats.txt') as pro:
cat = pro.read()
print(cat)
with open('dogs.txt') as pro1:
dog = pro1.read()
print(dog)
except FileNotFoundError:
print("Sorry, the file can't be found.")
10-9
try:
with open('cats.txt') as pro:
cat = pro.read()
print(cat)
with open('dogs.txt') as pro1:
dog = pro1.read()
print(dog)
except FileNotFoundError:
pass
10-11
import json
num = input('PLease enter your favourite number:\n')
file_name = 'fav_num.json'
with open(file_name, 'w') as pro:
json.dump(num, pro)
import json
file_name = 'fav_num.json'
with open(file_name) as pro:
name = json.load(pro)
print("I know your favourite number! It's " + name + '.')