10-1 Python学习笔记

代码:

with open('learning_python.txt') as fo:
content = fo.read()
print(content)

print("------------------------------------------------")
with open('learning_python.txt') as fo:
for line in fo:
print(line.rstrip())

print("------------------------------------------------")
with open('learning_python.txt') as fo:
lines = fo.readlines()
for line in lines:
print(line.rstrip())

运行结果:

第五周作业_Chapter 10课后练习


10-4 访客名单

代码:

with open('guest_book.txt','w') as fo:
while(True):
name = input("Please enter your name: ")
if name=='q':
break
message = "Hello, " + name + "!\n"
print(message)
fo.write(message)

运行结果:

第五周作业_Chapter 10课后练习

第五周作业_Chapter 10课后练习


10-7 加法计算器

代码:

while True:
a = input("You are plusing two numbers.Please enter the first number: ")
b = input("Please enter the other number: ")
try:
a = int(a)
b = int(b)
except ValueError:
print("Your enter is invalid, please enter again.")
continue
else:
c = a+b
print("The sum is " + str(c) + ".")
break

运行结果:

第五周作业_Chapter 10课后练习


10-12 记住喜欢的数字

代码:

运行结果:

import json
try:
with open('number.json') as f_obj:
content = f_obj.read()
except FileNotFoundError:
with open('number.json','w') as f_obj:
number = input("Please enter your favorite number: ")
message = "I know your favorite number, it's " + number + "!"
json.dump(message,f_obj)
else:
print(content)

第一次:

第五周作业_Chapter 10课后练习

第二次:

第五周作业_Chapter 10课后练习

相关文章: