1. 程式人生 > >高階程式設計技術課後作業 第十章練習

高階程式設計技術課後作業 第十章練習

10-1 python學習筆記

程式碼:

with open('input.txt') as input:
    print(input.read())

with open('input.txt') as input:
    file_in = input
    print(file_in.read())


list = []
with open('input.txt') as input:
    for line in input:
        list.append(line)
print(list)

結果:

This is a input file.
It is used to memorize python notes.
This is a input file.
It is used to memorize python notes.

['This is a input file.\n', 'It is used to memorize python notes.']

10-3 訪客:

程式碼:

name = ""
while True:
    name = input("請輸入你的名字,輸入exit退出程式:")
    if name == "exit":
        break
print("Hello," + name)
    with open('guest_book.txt', 'a') as output:
        output.write(name + "\n")
with open('guest_book.txt'
) as input: print(input.read())

結果:

請輸入你的名字,輸入exit退出程式:AmyHello,Amy請輸入你的名字,輸入exit退出程式:JohnHello,John請輸入你的名字,輸入exit退出程式:exitAmy

John

10-8 貓和狗

程式碼:

try:
    with open("cats.txt") as input:
        print("The cats:")
        print(input.read())
except FileNotFoundError:
    print("cats.txt檔案未找到")

try:
    with 
open("dogs.txt") as input: print("The dogs:") print(input.read()) except FileNotFoundError: print("dogs.txt檔案未找到")

結果:

The cats:AmeKaraSosoThe dogs:LekoMaka

Racoo

將cats.txt檔案移走後:

cats.txt檔案未找到The dogs:LekoMakaRacoo

10-11 喜歡的數字

程式碼:

import json
num = input("Your favorite number:")
filename = "num.json"
with open(filename, "w") as output:
    json.dump(num, output)

with open(filename) as input:
    num = json.load(input)
print("I know your favorite number! It's " + str(num))

結果:

Your favorite number:12

I know your favorite number! It's 12

結果: