第十章python作業

10-3 訪客 :編寫一個程序,提示用戶輸入其名字;用戶作出響應後,將其名字寫入到文件guest.txt中。
name=input("Please input your name:")
with open("guest.txt","w") as file_object:
	file_object.write(name)

10-4 訪客名單 :編寫一個while 循環,提示用戶輸入其名字。用戶輸入其名字後,在屏幕上打印一句問候語,並將一條訪問記錄添加到文件guest_book.txt中。確保這個文件中的每條記錄都獨佔一行。

with open("guest_book.txt","w") as file_object:
	while 1:
		name=input("Please input your name:")
		print("Welcome!"+name)
		file_object.write(name+"\n")

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

try:
	text=input("Please input number a:")
	a=int(text)
	text=input("Please input number b:")
	b=int(text)
	print("result:"+str(a+b))
except ValueError:
	print("Please input a number,not a text!")

10-7 加法計算器 :將你爲完成練習10-6而編寫的代碼放在一個while 循環中,讓用戶犯錯(輸入的是文本而不是數字)後能夠繼續輸入數字。

while 1:
	try:
		text=input("Please input number a:")
		a=int(text)
		text=input("Please input number b:")
		b=int(text)
		print("result:"+str(a+b))
	except ValueError:
		print("Please input a number,not a text!")
		continue
	else:
		break

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

try:
	with open("cat.txt") as file_obj:
		cat_contents=file_obj.readlines()
		for line in cat_contents:
			print(line.strip())
	with open("dog.txt") as file_obj:
		dog_contents=file_obj.readlines()
		for line in dog_contents:
			print(line.strip())
except FileNotFoundError:
	print("Sorry, File Not Found")

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

import json
num=int(input("Please input number:"))
with open("number.txt","w") as file_obj:
	json.dump(num,file_obj)
import json
with open("number.txt") as file_obj:
	number=json.load(file_obj)
print("I know your favorite number! It's "+str(number)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章