3.1 Function calls

In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later,
you can “call” the function by name. We have already seen one example of a function call:
>>> type(32)
<class 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The result is called
the return value.


Trong ngữ cảnh của chương trình, một hàm là một câu lệnh được đặt tên để thực hiện việc tính toán. Khi bạn xác định 1 hàm, bạn phải dặt tên cho hàm đó và chuỗi của câu lệnh. Sau đó, bạn có thể "gọi" hàm bằng tên. Chúng ta sẽ thấy 1 ví dụ của gọi hàm:

>>> type(32)
<class 'int'>

Tên của hàm là loại. Biểu thức trong dấu ngoặc đơn gọi là đối số của hàm. Kết quả cho hàm này, là loại của đối số. kết quả được gọi là "giá trị trả về".

3.2 Type conversion functions
Python provides built-in functions that convert values from one type to another. The int function
takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction
part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'


3.2 Các hàm chuyển định dạng:

Python cung cấp các hàm có chức năng chuyển đổi các giá trị từ một dịnh dạng sang định dạng khác. Hàm int (số nguyên) nhận bất kỳ gá trị nào và chuyển đổi chúng thành mọt số nguyên, nếu nó có thể, hoặc nhận xét trả về:
>>> int ('32')
32
>>> int ('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
int có thể chuyển đổi thành số thực. 
>>> int (3.99999)
3
>>> int (-2.3)
-2
(hàm) float chuyển định dạng số nguyên và chuỗi sang số có dấu chấm (số thực - gọi là số thập phân cho dễ)
>>> float (32)
32.0

3.3 Math functions
Python has a math module that provides most of the familiar mathematical functions. A module is
a file that contains a collection of related functions.
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you get some
information about it:
>>> print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access one of the
functions, you have to specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module
also provides a function called log that computes logarithms base e.
The second example finds the sine of radians. The name of the variable is a hint that sin and the
other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to
radians, divide by 360 and multiply by 2π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865475
The expression math.pi gets the variable pi from the math module. The value of this variable is an
approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root
of two divided by two:


3.3 Hàm toán học
Python có một môdul toán cung cấp hầu hết các hàm toán học tương tự. Một mô dul là một file mà chứa một tập hợp các hàm chức năng.


Trước khi chúng ta có thể sử dụng mô dul, chúng ta cần phải chèn nó (import):
>>> import math
Đây là câu lệnh tạo một mô dul đối tượng tên toán. Nếu bạn  hiển thị (in) cái mô dul đối tượng này, bạn sẽ có được thông tin về nó:
>>> print (math)
<modul 'math' (built-in)>
Mô dul đối tượng bao gồm hàm và các biến được định nghĩa( xác định) trong mô dul. Để truy cập một trong các hàm, bạn phải gọi chính xác tên của mô dul và tên của hàm, chúng ngăn cách bởi một dấu chấm (cũng có thể hiểu như một chu kỳ). Định dạng này  được gọi là "dấu chấm".

>>> ratio = signal_power/noise_power
>>> decibels = 10* math.log10(ratio)

>>> radians = 0.7
>>> height = math.sin(radians)

Ví dụ đầu tiên tính toán logarit bậc 10 của tỷ lệ sóng ồn. Toán mô dul cũng cung cấp một hàm gọi là log để tính toán logarit bậc e.

Ví dụ thứ 2 tim sin của radians. Tên của biến là một dấu hiệu mà sin và các hàm lượng giác (cos, tan ...) lấy đối xứng trong radian. Để chuyển dạng từ góc sang radian, chia 360 và nhân với 2 pi:

>>> degrees = 45
>>> radians = degrees/360 * 2 * math.pi
>>> math.sin(radians) 
0.7071
Cách biểu hiện math.pi đưa cho biến pi trong mô dul toán học. Giá trị của biến này là xấp xỉ của pi, chính xác khoảng 15 số.
Nếu bạn biết về phép đo lượng giác của bạn, bạn có thể kiểm tra kết quả cung cấp bởi tinh toán thông qua phép bình phương của 2 số bị chia cho 2:
>>> math.sqrt(2)/2.0
0.7071

3.4 Composition
So far, we have looked at the elements of a program—variables, expressions, and statements—in
isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building
blocks and compose them. For example, the argument of a function can be any kind of expression,
including arithmetic operators:
x = math.sin(degrees / 360.0 * 2 * math.pi)
And even function calls:
x = math.exp(math.log(x+1))
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the
left side of an assignment statement has to be a variable name. Any other expression on the left side
is a syntax error1.
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!

SyntaxError: can't assign to operator

3.4 Thành phần
Cho đến nay, chúng ta đã xem xét phần tử của một chương trình như các biến, các biểu thức và câu lệnh riêng biệt, mà không nói về cách kết hợp chúng.

Một trong những tính năng hữu ích nhất của ngôn ngữ lập trình là khả năng xây dựng các khối nhỏ và  biên soạn ra chúng. Ví dụ, đối số của một hàm có thể là bất kỳ dạng biểu thức nào,
bao gồm các toán tử số học:

x = math.sin(degrees / 360.0 * 2 * math.pi)

Và thậm chí cả các cuộc gọi chức năng:

x = math.exp(math.log(x+1))

Hầu như bất cứ nơi đâu bạn đều có thể đặt một giá trị, bạn có thể đặt một biểu thức tùy ý, với một ngoại lệ:
bên trái của câu lệnh gán phải là một tên biến. Bất kỳ biểu hiện nào khác ở phía bên trái
là một lỗi cú pháp1.
>>> minutes = hours * 60 # right
>>> hours * 60 = minutes # wrong!
SyntaxError: can't assign to operator


3.5 Adding new functions - thêm các hàm mới.
So far, we have only been using the functions that come with Python, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that execute when the function is called.

Trước tới giờ, chung ta chỉ sử dụng những hàm mà được python cung cấp (mặc định), nhưng nó cũng có thể thêm các hàm mới. Một định nghĩa xác định hàm là tên của hàm mới và chuỗi các câu lệnh được thực hiện khi hàm được gọi.

Here is an example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def is a keyword that indicates that this is a function definition. The name of the function is
print_lyrics. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a
keyword as the name of a function, and you should avoid having a variable and a function with the
same name.

def là một từ khóa chỉ ra đây là một định nghĩa hàm. Tên của hàm là print_lyrics. Quy tắc cho tên các hàm thì tương tự với tên của biến: chữ cái, số và một vài dấu  câu hợp pháp, nhưng chữ cái đầu tiên không thể là 1 số. Bạn không thể sử dụng một từ khóa như là tên của hàm và bạn sẽ gặp vấn đề với 1 biến và một hàm có cùng tên. (đại loại là nhầm lẫn đó).

The empty parentheses after the name indicate that this function doesn’t take any arguments.
The first line of the function definition is called the header; the rest is called the body. The header
has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces (see Section 3.13). The body can contain any number of statements.
1We will see exceptions to this rule later.

Dấu ngoặc đơn rỗng sau tên chỉ ra rằng hàm này không lấy bất kỳ đối số nào.
Dòng đầu tiên của định nghĩa hàm được gọi là tiêu đề(mở bài); phần còn lại được gọi là thân (thân bài). Tiêu đề phải kết thúc bằng dấu hai chấm và phần thân phải được thụt lề. Theo quy ước, thụ số luôn luôn là bốn khoảng cách(dấu cách hoặc 1 cái tab-  cái này cần chú ý cài đặt đối với notepad++) (xem Phần 3.13).  Phần thân (bài) có tehẻ bao gồm bất kỳ số câu lệnh nào.

(Chúng ta sẽ thấy ngoại lệ đối với quy tắc này sau.)


The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do
the same thing; most people use single quotes except in cases like this where a single quote (which
is also an apostrophe) appears in the string.
To end the function, you have to enter an empty line (this is not necessary in a script).

Các chuỗi câu lệnh in ra được đóng vào trong dấu ngoặc kép. Dấu ngoặc kép hoặc dấu nháy đơn thì tương tự như nhau; một số người thì sử dụng dấu nháy đơn trong trường hợp này để áp dụng trong chuỗi.
kết thúc hàm, bạn phải để trống một khoảng (nó không cần trong đoạn script )

Defining a function creates a variable with the same name.
>>> print print_lyrics
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'>
The value of print_lyrics is a function object, which has type class 'function'.
The syntax for calling the new function is the same as for built-in functions:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Once you have defined a function, you can use it inside another function. For example, to repeat the
previous refrain, we could write a function called repeat_lyrics:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
But that’s not really how the song goes











Nhận xét

Bài đăng phổ biến từ blog này

2.7. Operators and Operands - toán tử và toán hạng

1.11. Formal and Natural Languages

3.10 Stack diagrams - sơ đồ xếp chồng