Nhiều tham số và giá trị trả về

Giới thiệu về Functions trong Python

Hugo Bowne-Anderson

Instructor

Nhiều tham số hàm

  • Hàm nhận hơn 1 tham số:
def raise_to_power(value1, value2):
    """Lũy thừa: value1 mũ value2."""
    new_value = value1 ** value2
    return new_value
  • Gọi hàm: số đối số = số tham số
result = raise_to_power(2, 3)

print(result)
8
Giới thiệu về Functions trong Python

Lướt nhanh về tuple

  • Cho hàm trả về nhiều giá trị: Tuple!

  • Tuple:

    • Giống list - chứa nhiều giá trị

    • Bất biến - không thể sửa giá trị

    • Tạo bằng dấu ngoặc tròn ()

even_nums = (2, 4, 6)

print(type(even_nums))
<class 'tuple'>
Giới thiệu về Functions trong Python

Giải nén tuple

  • Giải nén tuple vào nhiều biến:
even_nums = (2, 4, 6)

a, b, c = even_nums
print(a)
2
print(b)
4
print(c)
6
Giới thiệu về Functions trong Python

Truy cập phần tử tuple

  • Truy cập phần tử tuple giống như list:
even_nums = (2, 4, 6)

print(even_nums[1])
4
second_num = even_nums[1]

print(second_num)
4
  • Dùng chỉ số bắt đầu từ 0
Giới thiệu về Functions trong Python

Trả về nhiều giá trị

def raise_both(value1, value2):
    """Lũy thừa: value1 mũ value2
    và ngược lại."""

    new_value1 = value1 ** value2
    new_value2 = value2 ** value1

    new_tuple = (new_value1, new_value2)

    return new_tuple
result = raise_both(2, 3)

print(result)
(8, 9)
Giới thiệu về Functions trong Python

Hãy thực hành!

Giới thiệu về Functions trong Python

Preparing Video For Download...