Professional Documents
Culture Documents
Thụt lề trong Python:
Nếu đã học ở NNLT Java bạn sẽ biết rằng những ngôn ngữ lập trình này sử dụng { } để xác
định các khối code. Trong Python thì khác, những khối lệnh sẽ được nhận biết thông qua
thụt lề. Đó là lý do vì sao thụt lề trong Python vô cùng quan trọng, nếu bạn thụt hoặc thò
nhầm là sẽ bị báo lỗi ngay.
Một khối code (thường là khối lệnh của hàm, vòng lặp,...) bắt đầu với thụt lề và kết thúc với
dòng đầu tiên không thụt lề. Thụt lề bao nhiêu là tùy thuộc ở bạn nhưng chúng phải nhất
2
quán trong suốt khối code đó, tức là các lệnh trong cùng một khối thì phải có độ thụt lề bằng
nhau.
Thông thường, sẽ dùng 4 lần phím cách để thụt lề, chúng được các lập trình viên yêu thích
hơn là phím tab, giống như ví dụ dưới đây:
for i in range(1,11):
print(i)
if i == 5:
break
Khối lệnh của for gồm có print(i) và if, được viết thụt lề bằng nhau, break là lệnh trong if,
nên lại được thụt lề thêm một đoạn nữa. Bạn chưa cần hiểu cụ thể đoạn code trên nói cái gì,
chỉ cần ghi nhớ trong đầu về cách thụt lề của Python thôi, dần dần chúng ta sẽ tìm hiểu chi
tiết, từng thứ một.
Nếu lệnh trên được viết thành:
for i in range(1,11):
print(i)
if i == 5:
break
Ta sẽ nhận được thông báo lỗi ngay lập tức, và lỗi sẽ hiện trước lệnh print(i) bởi không thụt
lề.
Nhờ thụt đầu dòng mà code trong Python trông gọn gàng và rõ ràng hơn. Ta có thể bỏ qua
thụt đầu dòng với những câu lệnh viết trên nhiều dòng, nhưng những nhà lập trình nhiều
kinh nghiệm khuyên rằng: Hãy luôn thụt lề, điều đó làm cho code dễ đọc hơn.
Vd:
if True:
print('Xin chào!')
q = 10
Và:
if True: print('Xin chào!'); q = 10
Cả hai cách viết trên đều đúng và thực hiện công việc tương tự nhau, nhưng ta có thấy cách
viết đầu nhìn rõ ràng hơn.
3
Trong Python, chúng ta sử dụng ký tự # để bắt đầu một chú thích. Chú thích bắt đầu sau dấu
# cho đến khi bắt đầu một dòng mới. Khi thông dịch, Python sẽ bỏ qua những chú thích này.
# đây là chú thích
# đây là lời nhắc
Có cách khác để viết chú thích là sử dụng 3 dấu nháy đơn ' ' ' hoặc nháy kép " " ". Những
dấu nháy này thường được sử dụng cho các chuỗi nhiều dòng. Nhưng chúng cũng có thể
được sử dụng để viết chú thích trên nhiều dòng. Chỉ cần không phải là docstring thì nó sẽ
không tạo ra thêm bất cứ code nào khác.
"""Đây là chú thích
3/.Biến:
Biến là một thực thể chiếm giữ 1 vị trí trong bộ nhớ được sử dụng để lưu trữ dữ liệu (giá
trị). Biến được đặt tên duy nhất để phân biệt giữa các vị trí bộ nhớ khác nhau. Các quy tắc
để viết tên một biến giống như quy tắc viết các định danh trong Python.
Trong Python, bạn không cần khai báo biến trước khi sử dụng, chỉ cần gán cho biến một giá
trị và nó sẽ tồn tại. Cũng không cần phải khai báo kiểu biến, kiểu biến sẽ được nhận tự động
dựa vào giá trị mà bạn đã gán cho biến.
Gán giá trị cho biến:
Các biến Python không cần khai báo rõ ràng để dành không gian bộ nhớ. Việc khai báo xảy
ra tự động khi ta gán giá trị cho một biến. Dấu bằng (=) dùng để gán giá trị cho các biến.
Vd:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
Number
4
String
List
Tuple
Dictionary
Ta sẽ dùng hàm type() để kiểm tra xem biến hoặc giá trị thuộc kiểu số nào và hàm
isinstance() để kiểm tra xem chúng có thuộc về một class cụ thể nào không.
Vd:
a = 100
# Output: <class 'int'>
print(type(a))
# Output: <class 'float'>
print(type(120.342343))
# Output: (15+6j)
b = 13 + 6j
print(b + 2)
# Kiểm tra xem b có phải là số phức không
# Output: True
print(isinstance(b, complex))
Kết quả:
<class 'int'>
<class 'float'>
(15+6j)
True
Hệ thống số Tiền tố
5
Hệ nhị phân '0b' hoặc '0B'
Hệ bát phân '0o' hoặc '0O'
Hệ thập lục phân '0x' hoặc '0X'
Vd:
# Output: 10
print(0b1010)
# Output: 4090)
print(0xFFA)
# Output: 80
print(0o120)
Vd:
import fractions
# Output: 1
print(fractions.Fraction(1,5) + fractions.Fraction(4,5))
# Output: 4/5
print(fractions.Fraction(2,5) + fractions.Fraction(2,5))
# Output: 5/3
print(1 / fractions.Fraction(3,5))
# Output: False
print(fractions.Fraction(-2,3) > 0)
# Output: True
print(fractions.Fraction(-2,3) < 0)
Kết quả:
Nhập số a: 12
Nhập số b: 45
Tổng 2 số là: 1245
Kết quả:
Nhập số a: 12
Nhập số b: 45
Tổng 2 số là: 57.0
1 abs(x)
2 ceil(x)
The ceiling of x: the smallest integer not less than x (làm tròn xuống)
3 cmp(x, y)
7
-1: if x < y, 0: if x == y, or 1: if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x. (trị tuyệt đối của x)
6 floor(x)
The floor of x: the largest integer not greater than x (làm tròn lên)
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the
same sign as x. The integer part is returned as a float (trả về phần lẻ và phần
nguyên của x).
12 pow(x, y)
The value of x**y. (lũy thừa)
14 sqrt(x)
8
The square root of x for x > 0 (căn bậc 2)
1 choice(seq)
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.
5 shuffle(lst)
Randomizes the items of a list in place. Returns None.
9
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y
1 acos(x)
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
Return the cosine of x radians.
6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).
7 sin(x)
Return the sine of x radians.
8 tan(x)
Return the tangent of x radians.
9 degrees(x)
Converts angle x from radians to degrees.
10 radians(x)
10
Converts angle x from degrees to radians.
1 pi
The mathematical constant pi.
2 e
The mathematical constant e.
Câu hỏi:
Làm sao truy xuất đến phần tử thứ 6: s[5]
Làm sao truy xuất đến chuỗi từ vị trí thứ 3 đến thứ 6 ?
Vd:
s1 = 'Hello World!'
s2 = "Python Programming"
print(s1)
print(s2)
print("s1[0]: ", s1[0])
print("s2[1:5]: ", s2[1:5])
Kết quả:
Hello World!
Python Programming
11
s1[0]: H
s2[1:5]: ytho
\b 0x08 Backspace
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
12
range
not in Membership - Returns true if a character does not M not in a will give
exist in the given string 1
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n
characters. The syntax for raw strings is exactly the and print
same as for normal strings with the exception of the R'\n'prints \n
raw string operator, the letter "r," which precedes the
quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.
1 capitalize()
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
columns.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to
the default string encoding.
13
5 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError
unless errors is given with 'ignore' or 'replace'.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize
not provided.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise.
12 isdigit()
Returns true if string contains only digits and false otherwise.
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false
otherwise.
14
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
Returns true if string is properly "titlecased" and false otherwise.
17 isupper()
Returns true if string has at least one cased character and all cased characters are
in uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into
a string, with separator string.
19 len(string)
Returns the length of the string
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of
width columns.
21 lower()
Converts all uppercase letters in string to lowercase.
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
Returns a translation table to be used in translate function.
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Returns the min alphabetical character from the string str.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of
width columns.
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with
NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending
index end are given) starts with substring str; returns true if so and false
otherwise.
34 strip([chars])
Performs both lstrip() and rstrip() on string.
35 swapcase()
Inverts case for all letters in string.
36 title()
16
Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in
the del string.
38 upper()
Converts lowercase letters in string to uppercase.
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters;
intended for numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
Vd: xuất ra 4 dòng (kết quả tương tự nếu thay 3 dấu nháy kép = 3 dấu nháy đơn)
s = """Dòng 1,
Dòng 2,
Dòng 3,
và Dòng 4."""
print(s)
Kết quả:
Dòng 1,
Dòng 2,
Dòng 3,
và Dòng 4.
Kết quả:
M
ù
17
a
T
h
u
Vd: đảo ngược chuỗi. Trong ví dụ, chỉ thị [:: - 1] có nghĩa là bắt đầu ở cuối chuỗi và kết
thúc ở vị trí 0, di chuyển với bước -1 (trừ một), có nghĩa là lùi một bước.
txt = "Hello World" [::-1]
print(txt)
Kết quả:
dlroW olleH
Kết quả:
['apple', 'banana', 'cherry', 1001, 25.2]
<class 'list'>
18
Truy cập các giá trị trong List. hãy sử dụng dấu ngoặc vuông [] để cắt cùng với chỉ số hoặc
các chỉ mục để lấy giá trị có sẵn tại chỉ mục đó.
Vd:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
Kết quả:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Kết quả:
['Chanh', 'Quít', 'Cam', 'Xoài', 'Chuối']
List sau khi xóa phần tử thứ 3 :
['Chanh', 'Quít', 'Xoài', 'Chuối']
19
Vd:
list1 =[1,2,3]
list2 =["Xoài", "Chuối"]
list3 = list1 + list2
list4 = ["Hồ Chí Minh", "Nguyễn Tất Thành"] * 3
print("List1 có độ dài : ", len(list1))
print("List2 có độ dài : ", len(list2))
print("List3 : ", list3)
print("List4 : ", list4)
for x in list2:
print(x)
print("Hồ Chí Minh" in list4)
Kết quả:
List1 có độ dài : 3
List2 có độ dài : 2
List3 : [1, 2, 3, 'Xoài', 'Chuối']
List4 : ['Hồ Chí Minh', 'Nguyễn Tất Thành', 'Hồ Chí Minh', 'Nguyễn Tất Thành', 'Hồ
Chí Minh', 'Nguyễn Tất Thành']
Xoài
Chuối
True
Vd: Chỉ số trong list với số dương âm (Sinh viên tìm hiểu và giải thích)
L = ['Miền Nam', 'Miền Trung', 'Miền Bắc',"Hải đảo","Hải ngoại"]
print(L[2])
print(L[-2])
print(L[0])
print(L[-1])
Kết quả:
Miền Bắc //phần tử chỉ số 2
Hải đảo //phần tử chỉ số -2, tính từ phải qua
Miền Nam //phần tử chỉ số 0
Hải ngoại //phần tử chỉ số -1, tính từ phải qua
20
mylist = ["a", "b", "a", "c", "c", "e", "f", "e", "a"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
Kết quả:
['a', 'b', 'c', 'e', 'f']
1 cmp(list1, list2)
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
1 list.append(obj)
2 list.count(obj)
21
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
Kết quả:
('Cam', 'Quít', 'Cam', 12.562, 2000)
(1, 8, 0, 9, 2, 7, 5, 1)
('a', 'b', 'c', 'd')
tup1[0]: Cam
tup2[1:5]: (8, 0, 9, 2)
list2[1:5]: [8, 0, 9, 2]
Tuple là bất biến: có nghĩa là ta không thể cập nhật hoặc thay đổi giá trị các phần tử của
tuple. Bạn có thể lấy các phần của các bộ giá trị hiện có để tạo các bộ giá trị mới như ví dụ
sau minh họa:
Vd:
tup1 = ('Cam', 'Quít', "Cam", 12.562, 2000)
tup2 = (1, 8, 0, 9, 2, 7, 5, 1)
# 2 lệnh sau là lỗi: TypeError: 'tuple' object does not support
item assignment
tup1[0]="Xoài"
tup2[2]=1001
Xóa phần tử Tuple: Không thể xóa các phần tử Tuple riêng lẻ. Chỉ có loại bỏ toàn bộ một
Tuple bằng cách sử dụng câu lệnh del.
Vd:
tup = (1, 2, 4, 12.562, 2000)
print("Nội dung của tup trước khi xóa: ",tup)
del tup
23
list =["Cóc", "Xoài","Cam", "Quít"]
print("Nội dung của list trước khi xóa: ",list)
del list
print("Nội dung của list sau khi xóa: ",list)
Kết quả:
Nội dung của list trước khi xóa: ['Cóc', 'Xoài', 'Cam', 'Quít']
Nội dung của list sau khi xóa: <class 'list'>
Các phép toán trên Tuple:
Vd: Chỉ số trong tuple với số dương âm (Sinh viên tìm hiểu và giải thích)
tuple1 = ('Miền Nam','Miền Trung', 'Miền Bắc','Hải đảo','Hải
ngoại')
print(tuple1[2])
print(tuple1[-2])
print(tuple1[0])
print(tuple1[-1])
24
Các hàm trên Tuple:
1 cmp(tuple1, tuple2)
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
6 count()
Returns the number of times a specified value occurs in a tuple
7 index()
Searches the tuple for a specified value and returns the position of where it was
found
Vd:
tup1 =[1, 2, 3, 5, "a", "Cóc", "Xoài", 5, 5]
x = tup1.count(5)
print("Số 5 có trong Tuple ",x, " lần")
found = tup1.index("Xoài")
print("Xoài tại vị trí thứ ", found)
Kết quả:
Số 5 có trong Tuple 3 lần
25
Xoài tại vị trí thứ 6
Kết quả:
{'brand': 'Ford', 'model': 'Escape', 'year': 2010}
Kết quả:
{'brand': 'Ford', 'electric': False, 'year': 2021, 'colors': ['red', 'white', 'blue']}
<class 'dict'>
Vd: có thay đổi giá trị
dict = {'Name': 'Laura', 'Age': 6, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
print("dict['Class']: ", dict['Class'])
dict['Name']="Betty"
dict['Age']=6
26
print("Sau khi thay đổi:")
dict['Class']="Two"
print(dict)
Kết quả:
dict['Name']: Laura
dict['Age']: 6
dict['Class']: First
Sau khi thay đổi:
{'Name': 'Betty', 'Age': 6, 'Class': 'Two'}
Xóa Dictionary: Bạn có thể xóa từng phần tử trong Dictionary hoặc xóa toàn bộ nội dung
của Dictionary. Để xóa ta dùng lệnh del, phương thức clear()..
Vd:
dict = {'Name': 'Laura', 'Age': 6, 'Class': 'First'}
del dict['Name']; # Xóa key 'Name'
print("Sau khi xóa Name: ",dict)
dict.clear(); # Xóa toàn bộ các key
print("Sau khi xóa các phần tử: ",dict)
del dict ; # Xóa dictionary
print("Sau khi xóa từ điển: ",dict)
Kết quả:
Sau khi xóa Name: {'Age': 6, 'Class': 'First'}
Sau khi xóa các phần tử: {}
Sau khi xóa từ điển: <class 'dict'>
Các hàm trên Dictionary:
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of
27
items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.
1 dict.clear()
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
28
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10 dict.values()
Returns list of dictionary dict's values
hoặc có thể tạo cách khác như sau: dùng constructor set()
myset = set(('Xoài', 'Chuối', 'Me', 'Chôm chôm', 23, 45, 12.678))
print(myset)
Kết quả:
{'Chôm chôm', 'Xoài', 'Me', 'Chuối', 23, 12.678, 45}
Vd: Set có chứa giá trị trùng nhau
myset = {'Xoài', 23, 'Chuối', 'Me', 'Me', 'Me', 23, 45, 12.678}
print(myset)
Kết quả:
{'Me', 23, 'Xoài', 12.678, 45, 'Chuối'}
Vd: chứa giá trị số, chuỗi, boolean
29
set1 = {"Nguyễn Tất Thành", 34, True, 40, False, "Sinh nhật"}
print(set1)
Kết quả:
{False, 'Nguyễn Tất Thành', 34, True, 'Sinh nhật', 40}
Vd: dùng for
myset = set(('Xoài', 'Chuối', 'Me', 'Chôm chôm', 23, 45, 12.678))
for x in myset:
print(x)
Kết quả:
Chôm chôm
Me
Xoài
45
Chuối
12.678
23
Các Phương thức trên Set: (sinh viên thực hiện các ví dụ cho các phương thức)
Method Description
30
difference_update() Removes the items in this set that are also included in
another, specified set
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
31
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Kết quả:
{'Chuối', 'Chanh', 'Táo', 'Măng cụt', 'Cam', 'Bưởi', 'Mít'}
Vd: update từ List
myset = {"Cam", "Bưởi", "Chuối","Chanh"}
mylist = ["Chôm chôm", "Nhãn"]
myset.update(mylist)
print(myset)
Kết quả:
{'Bưởi', 'Chuối', 'Chôm chôm', 'Cam', 'Nhãn', 'Chanh'}
Vd: Phương thức remove
Kết quả:
{'Bưởi', 'Chanh', 'Cam'}
Vd: Phương thức union:
32
set1 = {"a", "b" , "c"}
set2 = {7, 5, 27}
set3 = set1.union(set2)
print(set3)
Kết quả:
{7, 'c', 'b', 5, 27, 'a'}
Vd: Phương thức update khác (tương tự union)
set1 = {"a", "b" , "c"}
set2 = {7, 5, 27}
set1.update(set2)
print(set1)
Kết quả:
{7, 5, 'c', 27, 'a', 'b'}
Kết quả:
{'apple'}
Vd: Phương thức symmetric_difference_update: lấy các phần tử không có trong cả 2 tập
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
33
Kết quả:
{'microsoft', 'banana', 'cherry', 'google'}
Vd: Phương thức symmetric_difference: trả về tập hợp chức các phần tử không có trong cả
2 tập
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Kết quả:
{'google', 'banana', 'cherry', 'microsoft'}
Toán tử Mô Tả Ví Dụ
34
/ Toán tử chia các giá trị cho nhau a / b = 0.7142857142857143
Toán
Chú Thích Ví Dụ
tử
So sánh giá trị của các đối số xem có bằng nhau hay
không. a == b
==
Nếu bằng nhau thì kết quả trả về sẽ là True và ngược lại False
sẽ là False.
So sánh giá trị của các đối số xem có khác nhau hay
không. a != b
!=
Nếu khác nhau thì kết quả trả về sẽ là True và ngược lại True
sẽ là False.
Dấu < đại diện cho phép toán nhỏ hơn, nếu đối số 1 nhỏ
a<b
< hơn đối số 2 thì kết quả sẽ trả về là True và ngược lại sẽ là
True
False.
Dấu > đại diện cho phép toán lớn hơn, nếu đối số 1 lớn
a>b
> hơn đối số 2 thì kết quả sẽ trả về là True và ngược lại sẽ là
False
False.
Dấu > đại diện cho phép toán nhỏ hơn hoặc bằng, nếu đối
a <= b
<= số 1 nhỏ hơn hoặc bằng đối số 2 thì kết quả sẽ trả về là
True
True và ngược lại sẽ là False.
Dấu > đại diện cho phép toán lớn hơn hoặc bằng, nếu đối
a>= b
>= số 1 lớn hơn hoặc bằng đối số 2 thì kết quả sẽ trả về là
False
True và ngược lại sẽ là False.
35
Toán
Chú Thích Ví Dụ
Tử
Toán
Chú Thích
Tử
Nếu 2 vế của toán tử này đều là True thì kết quả sẽ là True và ngược lại
and
nếu 1 trong 2 vế là False thì kết quả trả về sẽ là False.
Nếu 1 trong 2 vế là True thì kết quả trả về sẽ là True và ngược lại nếu cả 2
or
vế là False thì kết quả trả về sẽ là False.
Đây là dạng phủ định, nếu biểu thức là True thì nó sẽ trả về là False và
not
ngược lại.
36
Toán tử Mô tả Ví dụ
& Binary AND Operator copies a bit to the result if it exists in (a & b)
both operands (means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49
both. (means
0011 0001)
<< Binary Left Shift The left operands value is moved left by the a << 2 =
number of bits specified by the right operand. 240 (means
1111 0000)
>> Binary Right The left operands value is moved right by the a >> 2 = 15
Shift number of bits specified by the right operand. (means
0000 1111)
Toán
Chú Thích Ví Dụ
Tử
37
Nếu 1 đối số thuộc một tập đối số nó sẽ trả về True và
in a in b //False
ngược lại/
Toán
Chú Thích Ví Dụ
Tử
not is Toán tử này sẽ trả về True nếu a != b và ngược lại a is not b //True
38