高级编程技术作业第五周 第十章课后练习

10-1:python学习笔记

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

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

with open('note.txt') as file_object:
    lines = file_object.readlines()
print('')
for line in lines:
    print(line.rstrip())

10-2:c语言学习笔记

with open('note.txt') as file_object:
    lines = file_object.readlines()
print('')
for line in lines:
    m = line.replace('python', 'c')
    print(m.rstrip())

10-3:访客:

filename = "guest.txt"
with open(filename, 'w') as file_object:
    name = input("Please input your name: ")
    file_object.write(name)

10-4:访客名单

filename = "guest_book.txt"
with open(filename, 'a') as file_object:
    while True:
        name = input("Please input your name: ")
        if name == 'q':
            break
        print("Hello " + name)
        file_object.write(name+'\n')

10-5:关于编程的调查

filename = "reasons.txt"
with open(filename, 'a') as file_object:
    while True:
        reason = input("Why you so like programming? ")
        if reason == 'q':
            break
        file_object.write(reason+'\n')

10-6:加法运算

print('请输入两个数字')
a=input()
b=input()
try:
    answer = int(a) + int(b)
except ValueError:
    print("You didn't input a number.")
else:
    print("The answer is " + str(answer))

10-7:加法计算器

while True:
    print('请输入两个数字')
    a = input()
    if a == 'q':
        break
    b = input()
    try:
        answer = int(a) + int(b)
    except ValueError:
        print("You didn't input a number.")
    else:
        print("The answer is " + str(answer))

10-8:猫和狗

try:
    with open('dogs.txt', 'r') as file_object:
        a = file_object.read()
        print(a)
except FileNotFoundError:
    print("Didn't find this file")

try:
    with open('cats.txt', 'r') as file_object:
        a = file_object.read()
        print(a)
except FileNotFoundError:
    print("Didn't find this file")

10-9:沉默的猫和狗

try:
    with open('cats.txt', 'r') as file_object:
        a = file_object.read()
        print(a)
except FileNotFoundError:
    pass

try:
    with open('dogs.txt', 'r') as file_object:
        a = file_object.read()
        print(a)
except FileNotFoundError:
    print("Didn't find this file")

10-11:喜欢的数字

import json

number = input("Please input your favourite number: ")

filename = 'numbers.json'

with open(filename, 'w') as file_object:
    json.dump(number, file_object)

with open(filename, 'r') as file_object:
    n = json.load(file_object)
    print("Your favourite number is:" + n)

猜你喜欢

转载自blog.csdn.net/weixin_38742280/article/details/79836911
今日推荐