Question
教材中课后的练习,10-1到10-13,选一些写到你的博客上
Answer
'''
SYSU - [专选]高级编程技术 - Week5, Lecture2 HW
by Duan
2018.04.08
'''
'''
10-1 Python 学习笔记:
'''
filename = 'learning_python.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line, end = '')
#Output:
# In Python you can do anything!
# In Python you can print "hello world".
# In Python you can read the Zen of Python.
'''
10-3 访客:
'''
print('\n')
quit = True
while quit:
name = input('Please enter your name("q" to quit):')
if name == 'q': quit = False
filename = 'guest.txt'
with open(filename, 'a') as file_object:
file_object.write(name + '\n')
#Input:
# Luffy
# Zoro
# Sanji
# q
#In guest.txt:
# Luffy
# Zoro
# Sanji
'''
10-6 加法运算:
'''
import sys
num1 = input('Please input the 1st number:')
try:
n1 = float(num1)
except ValueError:
print('You must input a number!')
sys.exit()
num2 = input('Please input the 2nd number:')
try:
n2 = float(num2)
except ValueError:
print('You must input a number!')
sys.exit()
else:
print(n1 + n2)
#=================== case 1 ===================
#Input:
# d
#Output:
# You must input a number!
#=================== case 2 ===================
#Input:
# 3
# d
#Output:
# You must input a number!
#=================== case 2 ===================
#Input:
# 3
# 4
#Output:
# 7.0
'''
10-11 喜欢的数字:
'''
import json
num = input('Please input your favorite number:')
filename = 'favorite_num.json'
with open(filename, 'w') as f_obj:
json.dump(num, f_obj)
print('We have stored your favorite number.')
import json
filename = 'favorite_num.json'
with open(filename) as f_obj:
number = json.load(f_obj)
print("I know you favorite number! It's", number + '.')
#Output:
# Please input your favorite number:7
# We have stored your favorite number.
# I know you favorite number! It's 7.