Nội dung bài họcLesson content
Hàm (function) là gì?What is a function?
Hàm là khối code có tên, thực hiện một việc cụ thể, có thể gọi lại nhiều lần. Thay vì viết cùng code 10 lần, bạn viết 1 hàm rồi gọi 10 lần. Hàm giúp code gọn, dễ sửa, dễ đọc. Dùng def để tạo hàm.A function is a named block of code that performs a specific task and can be called multiple times. Instead of writing the same code 10 times, you write 1 function and call it 10 times. Functions make code compact, easy to fix, and readable. Use def to create a function.
Tạo hàm với defCreating functions with def
Dùng def ten_ham(): để tạo hàm. Code bên trong thụt lề 4 khoảng trắng. Gọi hàm bằng ten_ham(). Hàm có thể nhận tham số (parameter) và trả về giá trị (return).Use def function_name(): to create a function. Code inside is indented 4 spaces. Call the function with function_name(). Functions can take parameters and return values.
def chao(ten):
print("Xin chào", ten)
chao("An") # In: Xin chào An
chao("Bình") # In: Xin chào Bình
# Hàm có return
def cong(a, b):
return a + b
tong = cong(5, 3)
print(tong) # In: 8
Module: thư viện có sẵnModules: built-in libraries
Module là thư viện code có sẵn mà bạn có thể nhập (import) vào chương trình. Python có hàng tràn module: random (số ngẫu nhiên), math (toán học), time (thời gian), turtle (đồ họa). Dùng import ten_module để nhập.A module is a pre-written code library that you can import into your program. Python has hundreds of modules: random (random numbers), math (mathematics), time (timing), turtle (graphics). Use import module_name to import.
import random
import math
# Random
so = random.randint(1, 100)
print("Số ngẫu nhiên:", so)
# Math
can_bac_2 = math.sqrt(144)
print("Căn bậc 2 của 144:", can_bac_2) # 12.0
Module turtle: vẽ đồ họaThe turtle module: graphics
turtle là module đồ họa dành cho người mới bắt đầu. Một "con rùa" di chuyển trên màn hình và vẽ đường. Dùng turtle.forward(100) để đi 100 bước, turtle.right(90) để xoay 90 độ. Kết hợp với for để vẽ hình.turtle is a graphics module for beginners. A "turtle" moves on the screen and draws a trail. Use turtle.forward(100) to move 100 steps, turtle.right(90) to turn 90 degrees. Combine with for to draw shapes.
import turtle
t = turtle.Turtle()
t.speed(5)
for i in range(4):
t.forward(100)
t.right(90)
turtle.done() # Mở cửa sổ đồ họa