1. 程式人生 > >Python學習(十)

Python學習(十)

10-1 Python學習筆記 :在文字編輯器中新建一個檔案,寫幾句話來總結一下你至此學到的Python知識,其中每一行都以“In Python you can”打頭。將這個檔案命名為
learning_python.txt,並將其儲存到為完成本章練習而編寫的程式所在的目錄中。編寫一個程式,它讀取這個檔案,並將你所寫的內容列印三次:第一次列印時讀取整個

檔案;第二次列印時遍歷檔案物件;第三次列印時將各行儲存在一個列表中,再在with 程式碼塊外列印它們。

In Python you can print;
In Python you can strip;
In Python you can use Pygame

filename = 'learn.txt'

with open(filename) as file_object:
    talk = file_object.read()
    print(talk)

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

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

10-3 訪客 :編寫一個程式,提示使用者輸入其名字;使用者作出響應後,將其名字寫入到檔案guest.txt中。

10-4 訪客名單 :編寫一個while 迴圈,提示使用者輸入其名字。使用者輸入其名字後,在螢幕上列印一句問候語,並將一條訪問記錄新增到檔案guest.txt中。確保這個檔案中的每條記錄都獨佔一行。

filename = 'guest.txt'
with open(filename, 'a') as file_object:
    while True:
        name = input('Enter your name : ')
        if name == 'quit':
            break
        file_object.write(name + '\n')

10-6 加法運算 :提示使用者提供數值輸入時,常出現的一個問題是,使用者提供的是文字而不是數字。在這種情況下,當你嘗試將輸入轉換為整數時,將引發TypeError 異常。編寫一個程式,提示使用者輸入兩個數字,再將它們相加並列印結果。在使用者輸入的任何一個值不是數字時都捕獲TypeError 異常,並列印一條友好的錯誤訊息。對你編寫的程式進行測試:先輸入兩個數字,再輸入一些文字而不是數字。

10-7 加法計算器 :將你為完成練習10-6而編寫的程式碼放在一個while 迴圈中,讓使用者犯錯(輸入的是文字而不是數字)後能夠繼續輸入數字。

注:我沒有實現要求的TypeError,實現的是ValueError。

print("Give me two numbers, and I'll add them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number : ")
    if first_number == 'q':
        break
    try:
        first_number = int(first_number)
    except ValueError:
        print(first_number + " is not a number.") 
    else:
        second_number = input("Second number : ")
        if second_number == 'q':
            break
        try:
            second_number = int(second_number)
        except ValueError:
            print(second_number + " is not a number.")
        else:
            print(first_number + second_number)

10-8 貓和狗 :建立兩個檔案cats.txt和dogs.txt,在第一個檔案中至少儲存三隻貓的名字,在第二個檔案中至少儲存三條狗的名字。編寫一個程式,嘗試讀取這些檔案,並將其內容列印到螢幕上。將這些程式碼放在一個try-except 程式碼塊中,以便在檔案不存在時捕獲FileNotFound 錯誤,並列印一條友好的訊息。將其中一個檔案移到另一個地方,並確認except 程式碼塊中的程式碼將正確地執行。

try:
    with open('cats.txt') as cat_obj:
        cas = cat_obj.read()
except FileNotFoundError:
    print("'cats.txt' not found.")
else:
    try:
        with open('dogs.txt') as dog_obj:
           dos = dog_obj.read()
    except FileNotFoundError:
        print("'dogs.txt' not found.")
    else:
        print(cas)
        print(dos)

10-9 沉默的貓和狗 :修改你在練習10-8中編寫的except 程式碼塊,讓程式在檔案不存在時一言不發。

try:
    with open('cats.txt') as cat_obj:
        cas = cat_obj.read()
except FileNotFoundError:
    #print("'cats.txt' not found.")
    pass
else:
    try:
        with open('dogs.txt') as dog_obj:
           dos = dog_obj.read()
    except FileNotFoundError:
        #print("'dogs.txt' not found.")
        pass
    else:
        print(cas)
        print(dos)

10-11 喜歡的數字 :編寫一個程式,提示使用者輸入他喜歡的數字,並使用json.dump() 將這個數字儲存到檔案中。再編寫一個程式,從檔案中讀取這個值,並列印訊息“I know your favorite number! It's _____.”。

import json
num = input("Input your num : ")
filename = "num.json"
with open(filename, 'w') as f_obj:
    json.dump(num, f_obj)
import json
filename = "num.json"
with open(filename) as f_obj:
    number = json.load(f_obj)
print("I know your favorite number! It's " + number + '.')

10-12 記住喜歡的數字 :將練習10-11中的兩個程式合而為一。如果儲存了使用者喜歡的數字,就向用戶顯示它,否則提示使用者輸入他喜歡的數字並將其儲存到檔案中。執行這個程式兩次,看看它是否像預期的那樣工作。

import json

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