# Tổng quát

> <https://www.codecademy.com/catalog/language/python>

### **Quy tắc đặt tên** <a href="#quy-tac-dat-ten" id="quy-tac-dat-ten"></a>

* Tên class phải tuân theo quy tắc CapWords – quy tắc viêt hoa chữ cái đầu tiên của mỗi từ. Ví dụ: *MyDog, MyFish,…*
* Tên functions phải được viết chữ thường và nên sử dụng dấu gạch dưới để phân tách ác từ nếu cần thiết. Ví dụ: *calculate\_force, sum\_two\_num*,…
* Tên Variable phải tuân theo các quy tắc tương tự như hàm

### **Thụt lề** <a href="#id-2-thut-le" id="id-2-thut-le"></a>

* Nó rất quan trọng đối trong Python vì groups các dòng code
* Mỗi lần thụt đầu dòng là 1 tab hoặc phải có 4 spaces

{% code overflow="wrap" lineNumbers="true" %}

```python
# comments: đây là hàm tính tổng của 2 biến truyền vào
def sum_two_num(num_a, num_b):
    sum = num_a + num_b       #tạo biến tổng
    return sum                #trả về kết quả
```

{% endcode %}

### **Hello World** <a href="#hello-world" id="hello-world"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
def main():
    print('Hello World!')
 
if __name__ == '__main__':
    main()
```

{% endcode %}

### **Input and Output** <a href="#input-and-output" id="input-and-output"></a>

{% code overflow="wrap" %}

```python
>>> input('What is your name?\n') #nhận dữ liệu đầu vào từ người dùng
What is your name?
Viet
'Viet'
>>> name = input('What is your name?\n') #nhận dữ liệu đầu vào và gán vào biến
What is your name?
Viet
>>> name #type name là str
'Viet'
>>> print(name)
Viet

```

{% endcode %}

### **Variables** <a href="#variables" id="variables"></a>

* Chỉ định kiểu dữ liệu cho biến: ***str(), int(), float(), bool()***. Ví dụ str(43.3)
* Printing the Data Type: ***type()***.
* Nếu thêm **global** trước tên biến trong hàm thì ta có thể lấy giá trị của biến đó trên mọi chương trình và từ đó khi ta thao tác sữa hay thay đổi biến đó sẽ dẫn tới thay đổi cả về sau

{% code overflow="wrap" lineNumbers="true" %}

```python
spam = 33
def foo():
    global spam  # ta chỉ sử dụng nó trong hàm con của chương trình
    spam  =99
    print(spam)
foo() # 99
print(spam) #99 chứng tỏ là spam đã bị ảnh hưởng bởi foo()
```

{% endcode %}

### **Operators** <a href="#operators" id="operators"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
x = 4
y = 3
 
x + y  # returns 7
x - y  # returns 1
x * y  # returns 12
x ** y # returns 64
x / y  # returns 1.333
x // y # returns 1
x % y # returns 1

x == y # returns False
x != y # returns True
x > y  # returns True
x < y  # returns False
x >= y # returns True
x <= y # returns False

x > 2 and y > 1      # returns True
x > 5 or y <= 3      # returns True
not(x > 2 and y > 1) # returns False

x += 4  # x is 8
x -= 4  # x is 0
x *= 4  # x is 16
x /= 4  # x is 1.0
x %= 4  # x is 0
```

{% endcode %}

### **if, elif, else** <a href="#if-elif-else" id="if-elif-else"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
# if Statements
score = 90
 
if score >= 80:
   print('You pass the course!')

# else statements
score = 70
 
if score >= 80:
   print('You pass the course!') 
else:
   print('You do not pass the course!')

#elif statements
score = 70
 
if score >= 80:
   print('You pass the course with flying colors!')
elif score > 65:
   print('You pass the course! Talk to your instructor.')
else:
   print('You do not pass the course!')
```

{% endcode %}

### **Loops (for, while)** <a href="#loops-for-while" id="loops-for-while"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
nums = [1, 2, 3, 4, 5]
 
for num in nums:
   print(num + 1) # 2 3 4 5 6

for i in range(3):
   print(i) # 0 1 2

teams = [['Jody', 'Abe'], ['Abhishek', 'Kim'], ['Taylor', 'Jen']]
for team in teams:
   for name in team:
       print(name)

# Dùng tổ hợp phím Ctrl + C để kết thúc vòng lặp trên terminal
# Từ khóa Pass, Break, Continue
# pass: chương trình sẽ không thực hiện sau Pass
# break: dừng hoặc kết thúc vòng lặp tại điểm đó
# continue: bỏ qua vòng lặp và chuyển sang lần lặp tiếp
```

{% endcode %}

### **Error Handling (try and except)** <a href="#error-handling-try-and-except" id="error-handling-try-and-except"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
nums = ['x', 'y', 'z']
 
try:
   print(sum(nums)) # cố gắng thử nếu thành công thì thực hiện
 
except:
   print('Cannot print the sum! Your variables are not numbers.')

# finally sẽ hữu ích khi cả try và except đều thất bại
finally:
   print('Hope you got the result you want!')
```

{% endcode %}

### **Functions** <a href="#functions" id="functions"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
# Creating a Function
def add_three(num1, num2, num3):
   sum_three = num1 + num2 + num3
   return sum_three

# using a Function
sum_output = add_three(2, 4, 6)

# Lambda Functions
# lambda argument(s): expression
add_two = lambda x: x + 2
add_two(5) #7
```

{% endcode %}

### **Classes and Objects** <a href="#classes-and-objects" id="classes-and-objects"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
class Dog:
   # this is a blank class
   pass

# Objects pepper
pepper = Dog()
print(pepper)

# Hàm tạo và hàm hủy
# __init__() được sử dụng là constructor và được gọi khi tạo 1 object
class ClassSchedule:
   def __init__(self, course):
       self.course = course

# __del__() đại diện cho hàm hủy trong 1 lớp
class ClassSchedule:
   def __init__(self, course):
       self.course = course
 
   def __del__(self):
       print('You successfully deleted your schedule')

sched = ClassSchedule('Chemistry')
del sched

# Theo mặc định tất cả các thành viên trong lớp là PUBLIC
# Thêm tiền tố _ : PROTECTED
# Thêm tiền tố __ : PRIVATE

class ClassSchedule:
   def __init__(self, course, instructor):
       self._course = course # protected
       self.__instructor = instructor # private
 
   def display_course(self):
       # public

# Kế thừa lớp cha
class Person:
  def __init__(self, name, age):
      self.name = name
      self.age = age
  def print_info(self):
      print(self.name)
      print(self.age)
 
class Teacher(Person):
  def __init__(self, name, age, subject):
      self.subject = subject
 
      Person.__init__(self, name, age)
```

{% endcode %}

### **String Methods** <a href="#string-methods" id="string-methods"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
intro = "My name is Jeff!"
print(intro[0]) # M
intro[0:2] # My
intro[-5:-1] # Jeff
len(intro) # 16
# str.lower(), str.upper(), str.title()

myTuple = ("John", "Peter", "Vicky")
x = " ".join(myTuple) # Nối chuỗi

txt = "welcome to the jungle"
x = txt.split() # tách chuỗi thành list

txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ") # có thể tách chuỗi thành list sử dụng dấu 

# format() chèn giá trị vào các vị trí chỉ định
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {:x}".format("John",36) #formatting types

# print theo format
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
# %x/%X - Integers in hex representation (lowercase/uppercase)
a = 10
print("%d is decimal number = %X is hexadecimal" % (a,a))
```

{% endcode %}

* The **capitalize()** method converts the first character of a string to an uppercase letter and all other alphabets to lowercase.

{% code overflow="wrap" lineNumbers="true" %}

```python
sentence = "i love PYTHON"

# converts first character to uppercase and others to lowercase
capitalized_string = sentence.capitalize()

print(capitalized_string)

# Output: I love python
```

{% endcode %}

* có thể print string bằng kí hiệu %s,%d,%f,%c

{% code overflow="wrap" lineNumbers="true" %}

```python
>>> print('Xin chao ban %s' % ('Anh'))
Xin chao ban Anh
>>> print('day la ki tu: %c' %('c'))
day la ki tu: c
```

{% endcode %}

### **Lists (Danh sách)** <a href="#lists-danh-sach" id="lists-danh-sach"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
lst = ['abc', 123, 'def', 10.5, 62, ['g', 'h', 'i']]

print(lst[0]) # prints abc
print(lst[4:6]) # prints [62, ['g', 'h', 'i']]

print(len(lst)) # prints 6

lst.append(99) # appends 99 at the end of the list

lst.remove(62) # removes 62 from the list

lst.pop() # removes ['g', 'h', 'i']
lst.pop(0) # removes 'abc'

```

{% endcode %}

### **Files** <a href="#files" id="files"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
f = open("path", mode='', endingcode ='') # mở file tùy chỉnh mode
file.close() #đóng file
file.read(n) # đọc nhiều nhất n ký tự từ tệp
file.readable() #trả về True nếu được đọc từ file
file.readline(n=-1) #trả về một dòng từ file cho đến n dòng tối đa
file.readlines(n=-1) #kết quả trả về là list với các pt là 1 dòng đọc trong file
```

{% endcode %}

### Class <a href="#class" id="class"></a>

* Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.
* The `__init__()` function, is a special function that is called when the class is being initiated. It’s used for assigning values in a class

{% code overflow="wrap" lineNumbers="true" %}

```python
class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def __init__(self, name, color, value):
        self.name = name
        self.color = color
        self.value = value
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
# your code goes here
# test code
car1 = Vehicle("Fer", "red", 60000)
car2 = Vehicle("Jump", "blue", 100000)
print(car1.description())
print(car2.description())
```

{% endcode %}

### **Một số hàm sẵn hay dùng** <a href="#mot-so-ham-san-hay-dung" id="mot-so-ham-san-hay-dung"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
# range()
range(stop)
range(start = 0, stop)
range(start = 0, stop, step = 1)

# reverse() đảo ngược
reversed(iterator)

# round() trả về bao nhiêu số sau dấu phẩy
round(number, digits)
round(323.4242,1) # 323.4

# str() chuyển thành chuỗi
# abs() giá trị tuyệt đối
# chr() trả về ký tự unicode
# pow(x,y,z) nếu chỉ có x và y: trả về x mũ y; nếu có z: trả số dư khi chia z
```

{% endcode %}

#### Format() <a href="#format" id="format"></a>

{% code overflow="wrap" %}

```python
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

>>> '{:<30}'.format('left aligned')
'left aligned                  '

>>> '{:>30}'.format('right aligned')
'                 right aligned'

>>> '{:^30}'.format('centered')
'           centered           '

>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'

# show a space for positive numbers
>>> '{: f}; {: f}'.format(3.14, -3.14)  
' 3.140000; -3.140000'

# show only the minus -- same as '{:f}; {:f}'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  
'3.140000; -3.140000'

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'

>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

>>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 88.64%'
```

{% endcode %}

#### Eval <a href="#eval" id="eval"></a>

* *Eval()* trả về kết quả được thực hiện từ *bieuthuc*

{% code overflow="wrap" %}

```python
eval(bieuthuc, global=None, local=None)
```

{% endcode %}

#### intertools.product() <a href="#intertools-product" id="intertools-product"></a>

* product(A,B) returns the same as ((x,y) for x in A for y in B)

{% code overflow="wrap" %}

```python
>>> from itertools import product
>>>
>>> print list(product([1,2,3],repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>>
>>> print list(product([1,2,3],[3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>>
>>> A = [[1,2,3],[3,4,5]]
>>> print list(product(*A))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
>>>
>>> B = [[1,2,3],[3,4,5],[7,8]]
>>> print list(product(*B))
[(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]
```

{% endcode %}

#### collections.Counter() <a href="#collections-counter" id="collections-counter"></a>

* A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.

{% code overflow="wrap" %}

```python
>>> from collections import Counter
>>> 
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print(Counter(myList))
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print(Counter(myList).items())
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>> 
>>> print(Counter(myList).keys())
[1, 2, 3, 4, 5]
>>> 
>>> print(Counter(myList).values())
[3, 4, 4, 2, 1]
>>> 
>>> lst = collections.Counter(map(int,input().split()))
3  4 55  4  33 
Counter({4: 2, 3: 1, 55: 1, 33: 1})
>>>
>>> lst[3] # có thể try xuất số lượng của values và thay thế nó.
1
>>>
```

{% endcode %}

#### map() <a href="#map" id="map"></a>

{% code overflow="wrap" %}

```python
>>> size,price = map(int, input().split())
1 30
2 45
5 90
```

{% endcode %}

#### divmod() <a href="#divmod" id="divmod"></a>

* Return the tuple (x//y, x%y). Invariant: div\*y + mod == x.

```python
>>> print divmod(177,10)
(17, 7)
```

#### set() <a href="#set" id="set"></a>

* Sets are used to store multiple items in a single variable
* A set is a collection which is *unordered*, *unchangeable\**, and *unindexed*.

{% code overflow="wrap" %}

```python
>>> thisset = {"apple", "banana", "cherry"}
>>> print(thisset)
{'apple', 'banana', 'cherry'}
>>> len(thisset)
3
>>> thisset.add('orange') # or update()
{'banana', 'apple', 'orange', 'cherry'}
>>> thisset.remove('banana') #nếu k tìm thấy sẽ báo lỗi
# or discard() nếu k tồn tại thì nó không thông báo lỗi
>>> thisset.clear() # lam cho set empties
set()
>>> del thisset # no se xoa toan bo thisset
```

{% endcode %}

* *union()* or *update()* method that inserts all the items from one set into anther.
* *difference()* return a set that contains the items that only exist in set x, and not in set y. (z = x.difference(y).
* *intersection\_update()* method will keep only the items that are present in both sets
* *intersection()* method will return a new set, that only contains the items that are present in both sets
* *symmetric\_difference\_update()* method will keep only the elements that are NOT present in both sets
* *symmetric\_difference()* method will return a new set, that contains only the elements that are NOT present in both sets.
* *copy()* returns a copy of the set

#### Calendar Module <a href="#calendar-module" id="calendar-module"></a>

{% code overflow="wrap" %}

```python
>>> import calendar
>>> for i in calendar.day_name: # day_name la mot doi tuong chua ten cac thu trong tuan
...     print(i)
...
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
>>> calendar.day_name[calendar.weekday(2022,8,9)] # tra ve thu trong tuan

```

{% endcode %}

#### random.randint(), seed(),shuffle() <a href="#random-randint-seed-shuffle" id="random-randint-seed-shuffle"></a>

* randit(start, end): lấy 1 int ngẫu nhiên có trong khoảng
* seed(): dùng để tạo 1 hạt giống sử dụng để tái sử dụng khi tạo ra 1 list ngẫu nhiên cùng seed
* shuffle(): xáo trộn giá trị trong 1 list data

{% code overflow="wrap" %}

```python
import random
random.randint(1,200) # có thể ra ngẫu nhiên bất kì số nào
Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
```

{% endcode %}

#### import copy <a href="#import-copy" id="import-copy"></a>

{% code overflow="wrap" lineNumbers="true" %}

```python
import copy
lst1 = [1,2,3,4,5]
lst2 = copy.deepcopy(lst1)
lst1.append(6)
lst1[0]  =0 
lst2.pop()
print(lst1,lst2)

lst3 = [1,2,3,4,5]
lst4 = copy.copy(lst3)
lst3[0] = 0
print(lst3,lst4)

print(type(random.shuffle(lst1))) # <class 'NoneType'>
print(random.shuffle(lst1)) #None
print(lst1) #1 list được sắp xếp ngẫu nhiên các giá trị của lst1
```

{% endcode %}

#### os.path.exists() <a href="#os-path-exists" id="os-path-exists"></a>

* dùng để kiểm tra đường dẫn có đúng không hoặc tồn tại, nó thường kiểm tra xem file này có tồn tại hay không.

{% code overflow="wrap" lineNumbers="true" %}

```python
import os
print(os.path.exists('C:\\Users\\Viet Nguyen\\Downloads\\a.txt'))
```

{% endcode %}

#### time.time() <a href="#time-time" id="time-time"></a>

* dùng để hiện thị thời gian hiện tại time.time()

{% code overflow="wrap" lineNumbers="true" %}

```python
import time
start_time = time.time()
print(start_time)
for _ in range(10000):
    print(' ', end= '!')
print("\n Thoi gian thuc hien chuong trinh = %f" % (time.time() - start_time))
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://viettaliii.gitbook.io/home/ctf/cheatsheet/python/tong-quat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
