Python練習#6-使用file指令做亂數與統計模組

by Gemma

本周目標

熟悉Python的基礎語法與資料結構

任務

  • 學習函數的定義和使用(Parameters、Return Values)
  • 練習設計和使用函數,並完成更多字串處理練習(例如文字查找和替換)
  • 學習file open, write, read指令

專案練習

寫入多行數字並計算多個數字總和

with open("1112data.txt",mode="w") as file:
    file.write("5\n6\n7\n8\n9")
sum=0
with open("1112data.txt",mode="r") as file:
    data=file.read()
    print("數字分別為:",data)
with open("1112data.txt",mode="r") as file:
    for line in file:
        sum+=int(line)
print("總和:",sum)

Output

數字分別為: 5
6
7
8
9
總和: 35

You may also like

Leave a Comment