Python編程作業【第五週】(二)

10-1 Python notes

file_path = "learning_python.txt"
with open(file_path) as obj:
    str1 = obj.read()
print(str1)
with open(file_path) as obj:
    for line in obj.readlines():
        print (line)
with open(file_path) as obj:
    str3 = obj.readlines()
print(str3)

10-2 C notes

file_path = "learning_python.txt"
with open(file_path) as obj:
    str1 = obj.read()
print(str1.replace("python", "C"))

10-3 guests

file_path = "guest.txt"
guest = input("Please input the guest name: ")
with open(file_path, 'w') as obj:
    obj.write(guest)

10-4 guests list

file_path = "guest.txt"
with open(file_path, 'w') as obj:
    while True:
        guest = input("Please input the guest name: ")
        if guest == "q": break
        obj.write(guest + "\n")

10-5 survey of programming

file_path = "guest.txt"
with open(file_path, 'w') as obj:
    while True:
        guest = input("Please input the reason why you love programming: ")
        if guest == "q": break
        obj.write(guest + "\n")

10-6 addition calculator

try:
    num1 = input("Please input the first number: ")
    num2 = input("Please input the second number: ")
    print(int(num1) + int(num2))
except (ValueError):
    print("Sorry, you cannot input a string.")

10-7 additioner

while True:
    try:
        num1 = input("Please input the first number: ")
        num2 = input("Please input the second number: ")
        res = int(num1) + int(num2)
    except (ValueError):
        print("Sorry, you cannot input a string.")
        continue
    else: 
        print(res)
        break

10-8 cats and dogs

try:
    with open("cats.txt") as obj:
        for line in obj.readlines(): print(line)
    with open("dogs.txt") as obj:
        for line in obj.readlines(): print(line)
except FileNotFoundError:
    print("This file doesn't exist.")

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