10-1
with open('learning_python.txt') as file_object:
contents=file_object.read()
print(contents)
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.rstrip())
with open('learning_python.txt') as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
10-3
filename="guest.txt"
with open(filename,'w') as file_object:
for i in range(0,3):
file_object.write(input("Please input the guest's name:")+'\n')
10-6
def add():
one=input("Please input the first number:")
two=input("Please input the second number:")
try:
int(one)
int(two)
except ValueError:
print("you should input numbers that don't contain characters.")
else:
sum=int(one)+int(two)
print(str(sum))
add()
add()
10-11
import json
filename="fav.json"
try:
with open(filename) as f_obj:
number=json.load(f_obj)
print("I know your favorite number is "+str(number))
except FileNotFoundError:
with open(filename,'w') as f_obj:
num=input("Please input the number that you like:")
json.dump(num,f_obj)
10-12
import json
filename="favorite_num.json"
def store():
with open(filename,'w') as f_obj:
num=input("Please input your favorite number:")
json.dump(num,f_obj)
def read():
try:
with open(filename) as f_obj:
number=json.load(f_obj)
print("I know your favorite number! It's "+number)
except FileNotFoundError:
store()
read()