重點:參數傳遞、回傳值、作用域
練習:追蹤函數呼叫鏈
def greet():
print("早安!")
greet()
def say_hello(name):
print("你好," + name)
say_hello("會安")
def add(a, b):
print("總和是:", a + b)
add(3, 5)
def square(x):
print("平方是:", x ** 2)
square(4)
def get_area(length, width):
return length * width
print(get_area(5, 3))
def double(n):
return n * 2
result = double(6)
print("結果:", result)
def get_discount(price, rate):
return price * (1 - rate)
print(get_discount(100, 0.2))
def is_even(n):
return n % 2 == 0
print(is_even(4))
def check_score(score):
if score >= 60:
return "及格"
else:
return "不及格"
print(check_score(75))
def grade(score):
if score >= 90:
return "優"
elif score >= 75:
return "甲"
else:
return "乙"
print(grade(88))
def is_adult(age):
return age >= 18
print(is_adult(20))
def classify_temp(temp):
if temp > 30:
return "炎熱"
elif temp < 15:
return "寒冷"
else:
return "舒適"
print(classify_temp(22))
def repeat_message(msg, times):
for i in range(times):
print(msg)
repeat_message("早安", 3)
def print_squares(n):
for i in range(1, n+1):
print(i ** 2)
print_squares(5)
def list_items(items):
for item in items:
print("項目:", item)
list_items(["蘋果", "香蕉", "芒果"])
def countdown(n):
while n > 0:
print(n)
n -= 1
countdown(3)
def show_name():
name = "會安"
print(name)
show_name()
# print(name) # 這行會錯誤,因為 name 是區域變數
total = 0
def add_to_total(x):
global total
total += x
add_to_total(5)
print("總和:", total)
def outer():
x = "外層"
def inner():
print("內層:", x)
inner()
outer()
def multiply(a, b):
result = a * b
return result
print(multiply(3, 4))
def add(a, b):
return a + b
def square(x):
return x ** 2
print(square(add(2, 3)))
def greet(name):
return f"你好,{name}"
def welcome(name):
message = greet(name)
print(message)
welcome("會安")
def get_tax(price):
return price * 0.05
def get_total(price):
return price + get_tax(price)
print(get_total(100))
def square(x):
return x * x
def cube(x):
return x * square(x)
print(cube(3))
import math
print("平方根:", math.sqrt(16))
import random
print("隨機數:", random.randint(1, 10))
from datetime import datetime
now = datetime.now()
print("現在時間:", now)
import statistics
scores = [80, 90, 100]
print("平均分:", statistics.mean(scores))