Python 从入门到实践 第十章作业

10-1

import json

with open('pyhton.txt') as file_object:
    contents = file_object.read()
    print(contents)
    print(contents)
    print(contents)

with open('pyhton.txt') as file_object:
    for line in file_object:
        print(line)


with open('pyhton.txt') as file_object:
    lines = file_object.readlines()


for line in lines:
    print(line)

10-2


for line in lines:
    print(line.replace('Python',"C++"))

10-3


filename = "guest.txt"
guest = input("Please Enter Your Name: ")
with open(filename, 'a') as file_object:
    file_object.write(guest+'\n')

10-5

filename = "reason.txt"
reason = ""
print("Enter 'quit' to quit")
while (reason.lower() != 'quit'):
    reason = input("Enter your own reason:")
    with open(filename, 'a') as file_object:
        file_object.write(reason+'\n')

10-6 10-7


a=''
b=''
while (a!='q' or b != 'q'):
    a = input("Please enter number a: ")
    b = input("Please enter number b: ")
    try:
        a = int(a)
        b = int(b)
    except TypeError:
        print("Sorry, what you enter is not a number.")
    else:
        print(a+b)

10-8 10-9


cat_file = 'cat.txt'
dog_file = 'dog.txt'

try:
    with open(cat_file) as file_object:
        for line in file_object:
            print(line)
except FileNotFound:
    #pass
    print("Sorry, the cat.txt does not exist.")

try:
    with open(dog_file) as file_object:
        for line in file_object:
            print(line)
except FileNotFound:
    #pass
    print("Sorry, the dog.txt does not exist.")

10-11 10-12


filename="number.json"
try:
    with open(filename) as f_obj:
        number = json.load(f_obj)
except FileNotFoundError:
    number = input("What is your number? ")
    with open(filename, 'w') as f_obj:
        json.dump(number, f_obj)
else:
    print("I know your favorite number! It's " + number + "!")

10-13

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj) 
    except FileNotFoundError:
        return None
    else:
        return username
def get_new_username():
    """提示用户输入用户名"""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    user = input("What is your name? ")
    username = get_stored_username()

    if username == user:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back, " + username + "!")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值