Python練習#5-使用def和tuple計算平均值

by Gemma

本周目標

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

任務

  • 學習Python基礎語法(變數、數據類型、條件語句、迴圈)
  • 使用 if 條件控制和 for 迴圈來做簡單的數學計算
  • 深入學習列表(List)、字典(Dictionary)等資料結構
  • 學習使用break, continue和else
  • 學習使用def程式區塊與呼叫指令
  • def與tuple結合

專案練習

1. 計算平均值

def avg(*ns):
    sum=0
    for a in ns: #將數字從tuple列表抓出
        sum+=a #計算總和
    print(sum/len(ns)) #len算出列表長度(幾個數字或文字))

avg(1,2,3)
avg(10,27,30,25)
avg(15,15)
avg(1,2,3,4,5,6,7,8,9,10)

Output

2.0
23.0
15.0
5.5

You may also like

1 comment

Download now 2025 年 3 月 13 日 - 上午 1:04

Helpful information. Lucky me I discovered your website
unintentionally, and I am shocked why this twist
of fate did not took place earlier! I bookmarked
it.

Reply

Leave a Comment