[Day 2] Một số kiến thức căn bản - Phần 1

Bài viết này nằm trong 1 series những ghi chép để học kiến thức Cloud – DevOps, bạn có thể xem lại bài 1:

https://shinchan.asia/2023/03/06/day-1-cloud-computing-nhap-mon/

A. Một số kiến thức tiền đề để bắt đầu với Cloud Computing

Để có thể bắt đầu với Cloud Computing hiệu quả, bạn nên chuẩn bị trước cho mình một số kỹ năng cơ bản:

Kiến thức về lập trình:

Bạn không cần phải code quá giỏi, tuy nhiên các công việc như Automation, xử lý dữ liệu cơ bản có thể nói là công việc hằng ngày của một Cloud Engineer. Nếu bạn chưa biết lập trình, bạn có thể bắt đầu với ngôn ngữ Python và/hoặc Golang.

Một số tài nguyên tham khảo bạn có thể sử dụng:

Programming for Everybody (Getting Started with Python):https://www.coursera.org/learn/python

How to Think Like a Computer Scientist: Interactive Edition:https://runestone.academy/ns/books/published/thinkcspy/index.html

Google’s Python Class:https://developers.google.com/edu/python

The Python Tutorial:https://docs.python.org/3/tutorial/

Learn Python – Full Course for Beginners:https://www.youtube.com/watch?v=rfscVS0vtbw&t=1s

Intermediate Python Programming Course:https://www.youtube.com/watch?v=HGOBQPFzWKo

Python Automation Tutorial – How to Automate Tasks for Beginners [Full Course]:https://www.youtube.com/watch?v=s8XjEuplx_U

Automate with Python – Full Course for Beginners:https://www.youtube.com/watch?v=PXMJ6FS7llk

Python deep dive series:

Part 1 – Functional: udemy.com/course/python-3-deep-dive-part-1

Part 2 – Iteration, Generators: udemy.com/course/python-3-deep-dive-part-2

Part 3 – Dictionaries, Sets, JSON: udemy.com/course/python-3-deep-dive-part-3

Part 4 – OOP: udemy.com/course/python-3-deep-dive-part-4

100 Days of Code: The Complete Python Pro Bootcamp for 2023: udemy.com/course/100-days-of-code

Vì khuôn khổ bài viết có hạn, nên mình sẽ không cover hết tất cả các kiến thức Python ở đây, mà sẽ chỉ viết lại một số kiến thức cơ bản và quan trọng, các kiến thức khác, bạn hãy tham khảo trong link tài liệu bên trên.

Bắt đầu với Python

Python là một ngôn ngữ lập trình có cú pháp khá đơn giản và dễ hiểu. Ứng dụng của Python trong thực tế có thể kể đến: Phát triển web, các ứng dụng network, các app khoa học, các app desktop, và các automation script,…

Để chạy được các chương trình viết bằng Python, bạn sẽ cần đến trình biên dịch (interpreter) của Python.

Bạn có thể tải Python interpreter tại đây: https://www.python.org/downloads/

Để phục vụ cho việc lập trình với Python, bạn có thể sử dụng các IDE ví dụ như: PyCharm, PyDev, Wing IDE. Với những người mới bắt đầu với Python, bạn có thể sử dụng Thonny – 1 IDE với giao diện đơn giản và dễ dàng debug cho người mới: https://thonny.org/, hoặc đơn giản là sử dụng 1 text editor như VS Code.

Những câu lệnh Python đầu tiên

Như thông lệ của việc học các ngôn ngữ lập trình, chúng ta sẽ bắt đầu với việc viết chương trình Hello world:

hello.py

#!/usr/bin/env python3
print('Hello World!')

Các file chương trình Python sẽ có extension là .py

Để chạy được chương trình, bạn mở terminal và chạy câu lệnh sau:

python hello.py

Lúc này bạn sẽ thấy dòng “Hello World!” được in ra. Chúc mừng bạn, bạn đã hoàn thành việc tạo chương trình đầu tiên bằng Python.

Bạn cũng có thể sử dụng Python interpreter ở interactive mode để thực thi những câu lệnh Python đơn giản. Để làm được điều này, bạn mở Terminal lên và gõ Python:

$ python
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec  6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

bạn có thể chạy các chương trình đơn giản:

the_world_is_flat = True

if the_world_is_flat:
    print("Be careful not to fall off!")

Để tìm hiểu kỹ hơn về Python interpreter cũng như cách sử dụng, bạn tham khảo thêm trong tài liệu này: https://docs.python.org/3/tutorial/interpreter.html

Variables (Biến) và types (các kiểu dữ liệu) trong Python

Python hỗ trợ rất nhiều kiểu dữ liệu, ví dụ như number, float, boolean, string,…

Bạn không cần phải khai báo kiểu dữ liệu cho biến, tất cả những gì bạn cần làm là gán 1 giá trị nào đó cho biến đó. Python xác định kiểu dữ liệu của biến dựa trên giá trị mà bạn gán cho biến đó.

Ví dụ:

#!/usr/bin/python

x = 3              # a whole number                   
f = 3.1415926      # a floating point number              
name = "Python"    # a string

print(x)
print(f)
print(name)

combination = name + " " + name
print(combination)

sum = f + f
print(sum)

Đọc các giá trị nhập vào từ bàn phím:

Bạn sử dụng hàm input(). Ví dụ:

#!/usr/bin/env python3

name = input('What is your name? ')
print('Hello ' + name)

job = input('What is your job? ')
print('Your job is ' + job)

num = input('And your age? ')
print('You said: ' + str(num))

Một số method với string khác trong Python mà bạn nên tìm hiểu thêm:

MethodsDescription
upper()converts the string to uppercase
lower()converts the string to lowercase
partition()returns a tuple
replace()replaces substring inside
find()returns the index of first occurrence of substring
rstrip()removes trailing characters
split()splits string from left
startswith()checks if string starts with the specified string
isnumeric()checks numeric characters
index()returns index of substring

Escape Sequences trong Python:

Escape sequences được sử dụng để thoát khỏi một số ký tự có trong một chuỗi.

Giả sử chúng ta cần bao gồm cả trích dẫn kép và trích dẫn đơn bên trong một chuỗi:

example = "He said, "What's there?""
print(example) # throws error

Chúng ta sẽ cần sửa lại như sau:

# escape double quotes
example = "He said, \\"What's there?\\""

# escape single quotes
example = 'He said, "What\\'s there?"'

print(example)
# Output: He said, "What's there?"

Bảng một số escape sequences trong Python:

Escape SequenceDescription
\\Backslash
\’Single quote
\”Double quote
\aASCII Bell
\bASCII Backspace
\fASCII Formfeed
\nASCII Linefeed
\rASCII Carriage Return
\tASCII Horizontal Tab
\vASCII Vertical Tab
\oooCharacter with octal value ooo
\xHHCharacter with hexadecimal value HH

f-Strings

Python f-Strings giúp in các giá trị và variables. Ví dụ:

name = 'Yen'
country = 'VN'
print(f'{name} is from {country}')
import math
print(f'The value of pi is approximately {math.pi:.3f}.')

Việc pass vào một số nguyên sau dấu ‘:’ sẽ khiến trường đó có chiều rộng là số ký tự tối thiểu. Điều này rất hữu ích để tạo các cột thẳng hàng. Ví dụ:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10d}')

# Result: 
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

Các modifierscó thể được sử dụng để chuyển đổi giá trị trước khi nó được định dạng. ‘!a’ áp dụng ascii(), ‘!s’ áp dụng str() và ‘!r’ áp dụng repr(). Ví dụ:

animals = 'eels'

print(f'My hovercraft is full of {animals}.')
# My hovercraft is full of eels.

print(f'My hovercraft is full of {animals!r}.')
# My hovercraft is full of 'eels'.

specifier “=” có thể được sử dụng để mở rộng một biểu thức thành văn bản của biểu thức, một dấu bằng, sau đó là biểu diễn của biểu thức được đánh giá:

bugs = 'roaches'
count = 13
area = 'living room'

print(f'Debugging {bugs=} {count=} {area=}')
# Debugging bugs='roaches' count=13 area='living room'

Toán tử % (modulo) cũng có thể được sử dụng để định dạng string, các instance % trong string được thay thế bằng 0 hoặc nhiều phần tử giá trị. Hoạt động này thường được gọi là interpolation. Ví dụ:

import math

print('The value of pi is approximately %5.3f.' % math.pi)
# The value of pi is approximately 3.142.

format():

print('We are the {} who say "{}!"'.format('knights', 'Ni'))
# We are the knights who say "Ni!"
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
# This spam is absolutely horrible.
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
# The story of Bill, Manfred, and Georg.
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '

      'Dcab: {0[Dcab]:d}'.format(table))
# Jack: 4098; Sjoerd: 4127; Dcab: 8637678
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
# Jack: 4098; Sjoerd: 4127; Dcab: 8637678
for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

# Result: 
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

Number trong Python:

Python hỗ trợ integers (số nguyên), floating-point numbers và complex numbers (số phức). Chúng được định nghĩa là int, float và complex trong Python.

Ví dụ:

num1 = 1  ## int 
print(num1, 'is of type', type(num1))

num2 = 1.01 ## float
print(num2, 'is of type', type(num2))

num3 = 1+2j ## complex
print(num3, 'is of type', type(num3))

Những con số chúng ta xử lý hàng ngày thuộc hệ thống số thập phân (cơ số 10).

Nhưng các lập trình viên máy tính cần phải làm việc với các hệ thống số nhị phân (cơ số 2), thập lục phân (cơ số 16) và bát phân (cơ số 8).

Trong Python, chúng ta có thể biểu diễn các số này bằng cách đặt một tiền tố thích hợp trước số đó. Bảng sau đây liệt kê các tiền tố này.

Number SystemPrefix
Binary0b or 0B
Octal0o or 0O
Hexadecimal0x or 0X

Ví dụ:

print(0b1101011)  # 107

print(0xFB + 0b10)  # 253

print(0o15)  # 13

Trong lập trình, chuyển đổi kiểu là quá trình chuyển đổi một kiểu số thành kiểu số khác. Ví dụ:

print(1 + 2.0) # prints 3.0

Ở ví dụ trên, Python sẽ ngầm hiểu và tự động chuyển kết quả thành float. Chúng ta cũng có thể sử dụng các hàm có sẵn như int(), float() và complex() để chuyển đổi giữa các kiểu một cách rõ ràng. Các chức năng này thậm chí có thể chuyển đổi từ string. Ví dụ:

a = int(2.3)
print(a)  # prints 2

b = int(-2.8)
print(b)  # prints -2

c = float(5)
print(c) # prints 5.0

d = complex('3+5j')
print(d)  # prints (3 + 5j)

Python cung cấp module math() để thực hiện các phép toán khác nhau như lượng giác, logarit, xác suất và thống kê, v.v. Ví dụ:

import math

print(math.pi)

print(math.cos(math.pi))

print(math.exp(10))

print(math.log10(1000))

print(math.sinh(1))

print(math.factorial(6))

Python Sets

Tạo một set trong Python:

# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)

# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

Để tạo 1 set trống:

# create an empty set
empty_set = set()

# create an empty dictionary
empty_dictionary = { }

# check data type of empty_set
print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set
print('Data type of empty_dictionary', type(empty_dictionary))

Set sẽ loại bỏ các phần tử bị trùng lặp, do đó:

numbers = {2, 4, 6, 6, 2, 8}
print(numbers)   # {8, 2, 4, 6}

Có thể thấy từ kết quả đoạn chương trình trên, phần tử 2, 6 trùng lặp đã bị loại bỏ.

Một đặt điểm quan trọng của set mà bạn cần nhớ là set không quan tâm thứ tự các phần tử, do đó khái niệm index là không có ý nghĩa đối với set.

Để thêm giá trị vào set trống:

Bạn sử dụng phương thức add(). Ví dụ:

numbers = {21, 34, 54, 12}

print('Initial Set:',numbers)

# using add() method
numbers.add(32)

print('Updated Set:', numbers)

Để update phần tử trong set:

Bạn sử dụng phương thức update(). Ví dụ:

companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']

companies.update(tech_companies)

print(companies)

# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Loại bỏ phần tử ra khỏi set:

Bạn dùng phương thức remove(). Ví dụ:

languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set
removedValue = languages.discard('Java')

print('Set after remove():', languages)

Lặp các phần tử trong set:

fruits = {"Apple", "Peach", "Mango"}

# for loop to access each fruits
for fruit in fruits: 
    print(fruit)

Tính số phần tử có trong set:

Bạn sử dụng len():

even_numbers = {2,4,6,8}
print('Set:',even_numbers)

# find number of elements
print('Total Elements:', len(even_numbers))

Set operations:

Union: Sử dụng toán tử | hoặc phương thức union():

# first set
A = {1, 3, 5}

# second set
B = {0, 2, 4}

# perform union operation using |
print('Union using |:', A | B)

# perform union operation using union()
print('Union using union():', A.union(B))

Set Intersection: Sử dụng toán tử & hoặc phương thức intersection()

Ví dụ:

# first set
A = {1, 3, 5}

# second set
B = {1, 2, 3}

# perform intersection operation using &
print('Intersection using &:', A & B)

# perform intersection operation using intersection()
print('Intersection using intersection():', A.intersection(B))

Difference:

Sử dụng toán tử “ – “ hoặc difference():

Ví dụ:

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &
print('Difference using &:', A - B)

# perform difference operation using difference()
print('Difference using difference():', A.difference(B))

Symmetric Difference:

Sử dụng toán tử “ ^ “ hoặc phương thức symmetric_difference()

Ví dụ:

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &
print('using ^:', A ^ B)

# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))

Một số method của set khác mà bạn nên biết:

MethodDescription
add()Adds an element to the set
clear()Removes all elements from the set
copy()Returns a copy of the set
difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an element from the set if it is a member. (Do nothing if the element is not in set)
intersection()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
pop()Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove()Removes an element from the set. If the element is not a member, raises a KeyError
symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another
union()Returns the union of sets in a new set
update()Updates the set with the union of itself and others

Python dictionary

Python dictionary là một collection có thứ tự ((bắt đầu từ Python 3.7). Nó lưu trữ các phần tử dưới dạng key/value. Ví dụ:

KeysValues
NepalKathmandu
ItalyRome
EnglandLondon

Tạo một dictionary:

capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
print(capital_city)

Thêm phần tử vào dictionary:

capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)

Thay đổi giá trị của phần tử:

student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", student_id)

student_id[112] = "Stan"

print("Updated Dictionary: ", student_id)

Truy cập vào các phần tử:

student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}

print(student_id[111])  # prints Eric
print(student_id[113])  # prints Butters

Bỏ phần tử ra khỏi dictionary:

student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}

print("Initial Dictionary: ", student_id)

del student_id[111]

print("Updated Dictionary ", student_id)
student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}

# delete student_id dictionary
del student_id

print(student_id)

# Output: NameError: name 'student_id' is not defined

Kiểm tra xem giá trị có phải là phần tử của dictionary không:

# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares) # prints True

print(2 not in squares) # prints True

# membership tests for key only not value
print(49 in squares) # prints false

Lặp các phần tử:

# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
    print(squares[i])

Các method khác:

FunctionDescription
all()Return True if all keys of the dictionary are True (or if the dictionary is empty).
any()Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len()Return the length (the number of items) in the dictionary.
sorted()Return a new sorted list of keys in the dictionary.
clear()Removes all items from the dictionary.
keys()Returns a new object of the dictionary’s keys.
values()Returns a new object of the dictionary’s values

Python list

Trong Python, list được sử dụng để lưu trữ nhiều dữ liệu cùng một lúc.

Tạo một list:

# A list with 3 integers
numbers = [1, 2, 5]

print(numbers)

# Output: [1, 2, 5]
# empty list
my_list = []

# list with mixed data types
my_list = [1, "Hello", 3.4]

Truy cập vào các phần tử:

languages = ["Python", "Swift", "C++"]

# access item at index 0
print(languages[0])   # Python

# access item at index 2
print(languages[2])   # C++

Index sẽ luôn bắt đầu từ 0.

Negative index:

Python cho phép negative index. index -1 đề cập đến mục cuối cùng, -2 cho mục cuối cùng thứ hai, v.v.

languages = ["Python", "Swift", "C++"]

# access item at index 0
print(languages[-1])   # C++

# access item at index 2
print(languages[-3])   # Python

Truy cập vào 1 phần của list:

Trong Python, có thể truy cập một phần của các mục từ danh sách bằng cách sử dụng toán tử cắt” : “. Ví dụ:

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# items from index 2 to index 4
print(my_list[2:5])

# items from index 5 to end
print(my_list[5:])

# items beginning to end
print(my_list[:])

Thêm phần tử vào list:

numbers = [21, 34, 54, 12]

print("Before Append:", numbers)

# using append method
numbers.append(32)

print("After Append:", numbers)

Thêm toàn bộ 1 list vào 1 list khác:

prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)

even_numbers = [4, 6, 8]
print("List2:", even_numbers)

# join two lists
prime_numbers.extend(even_numbers)

print("List after append:", prime_numbers)

Thay đổi giá trị của phần tử:

languages = ['Python', 'Swift', 'C++']

# changing the third item to 'C'
languages[2] = 'C'

print(languages)  # ['Python', 'Swift', 'C']

Bỏ một hoặc nhiều phần tử ra khỏi list:

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item
del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item
del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']

# delete first two items
del languages[0 : 2]  # ['C', 'Java', 'Rust']
print(languages)

Ngoài ra có thể sử dụng remove():

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# remove 'Python' from the list
languages.remove('Python')

print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

Các method với list khác:

MethodDescription
append()add an item to the end of the list
extend()add items of lists and other iterables to the end of the list
insert()inserts an item at the specified index
remove()removes item present at the given index
pop()returns and removes item present at the given index
clear()removes all items from the list
index()returns the index of the first matched item
count()returns the count of the specified item in the list
sort()sort the list in ascending/descending order
reverse()reverses the item of the list
copy()returns the shallow copy of the list

Lặp 1 list:

languages = ['Python', 'Swift', 'C++']

# iterating through the list
for language in languages:
    print(language)

Kiểm tra xem giá trị có tồn tại trong list không:

languages = ['Python', 'Swift', 'C++']

print('C' in languages)    # False
print('Python' in languages)    # True

Tính số phần tử có trong list:

languages = ['Python', 'Swift', 'C++']

print("List: ", languages)

print("Total Elements: ", len(languages))    # 3

Python Tuple

Tạo một tuple:

Tuple được tạo bằng cách đặt tất cả các phần tử bên trong dấu (), được phân cách bằng dấu phẩy. Các dấu ngoặc đơn là tùy chọn, nhưng bạn nên sử dụng chúng.

Một tuple có thể có bất kỳ phần tử nào, và chúng có thể thuộc các loại dữ liệu khác nhau (integer, float, list, string, etc.)

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Tạo tuple có 1 phần tử duy nhất:

var1 = ("Hello") # string
var2 = ("Hello",) # tuple

Truy cập vào các phần tử:

  • Dựa vào index:
# accessing tuple elements using indexing
letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0])   # prints "p" 
print(letters[5])   # prints "a"
  • negative index:
# accessing tuple elements using negative indexing
letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(letters[-1])   # prints 'z' 
print(letters[-3])   # prints 'm'

Truy cập vào 1 phần tuple:

# accessing tuple elements using slicing
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index
print(my_tuple[1:4])  #  prints ('r', 'o', 'g')

# elements beginning to 2nd
print(my_tuple[:-7]) # prints ('p', 'r')

# elements 8th to end
print(my_tuple[7:]) # prints ('i', 'z')

# elements beginning to end
print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Python tuple methods

Trong Python, các phương thức add hoặc remove không khả dụng với Tuple. Chỉ có hai phương thức count và index. Một số ví dụ về các phương thức Tuple trong Python:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p'))  # prints 2
print(my_tuple.index('l'))  # prints 3
  • my_tuple.count(‘p’) – đếm tổng số ‘p’ trong my_tuple

  • my_tuple.index(‘l’) – trả về lần xuất hiện đầu tiên của ‘l’ trong my_tuple

Loop các phần tử:

languages = ('Python', 'Swift', 'C++')

# iterating through the tuple
for language in languages:
    print(language)

Kiểm tra có phải là phần tử của tuple hay không:

languages = ('Python', 'Swift', 'C++')

print('C' in languages)    # False
print('Python' in languages)    # True

Lợi thế của tuple so với list:

List và tuple khá giống nhau, nên đôi khi có thể được dùng thay thế cho nhau. Tuy nhiên tuple có 1 số lợi thế so với list:

Tuple thường dùng cho các loại dữ liệu không đồng nhất (heterogeneous) và list dùng cho các loại dữ liệu đồng nhất (homogeneous).

Vì tuple là immutable, nên việc lặp qua một tuple sẽ nhanh hơn so với một list. Vì vậy, có một sự gia tăng hiệu suất nhẹ.

Tuple chứa các phần tử immutable có thể được sử dụng làm key cho dictionary. Với list, điều này là không thể. Việc triển khai dữ liệu dưới dạng tuple sẽ đảm bảo rằng dữ liệu được bảo vệ chống ghi đè.

Python functions

Functions

Có hai loại hàm trong lập trình Python:

Standard library functions – Đây là các hàm tích hợp sẵn trong Python có sẵn để sử dụng.

User-defined functions – Chúng ta có thể tạo các chức năng của riêng mình dựa trên nhu cầu.

Cách khai báo một hàm:

def function_name(arguments):
    # function body 

    return
  • def – từ khóa dùng để khai báo hàm

  • function_name – tên hàm

  • arguments: giá trị được truyền cho hàm

  • return (tùy chọn) – trả về giá trị từ một hàm

Cách gọi một hàm:

def currentYear():
    print('2018')

currentYear()

Function (hàm) có arguments:

Ví dụ:

#!/usr/bin/env python3

def f(x,y):
    return x*y

print(f(3,4))

Trong ví dụ này, chúng ta có hai hàm: f(x,y) và print(). Hàm f(x,y) đã chuyển đầu ra của nó cho hàm in bằng cách sử dụng từ khóa return.

Return variables:

Một hàm Python có thể hoặc không thể trả về một giá trị. Nếu chúng ta muốn hàm của mình trả về một số giá trị khi gọi hàm, chúng ta sử dụng câu lệnh return. Ví dụ:

# function definition
def find_square(num):
    result = num * num
    return result

# function call
square = find_square(3)

print('Square:',square)

# Output: Square: 9

Python Library Functions:

Trong Python, Python Library Functions là các hàm tích hợp sẵn có thể được sử dụng trực tiếp trong chương trình của chúng ta. Ví dụ, print() – in chuỗi bên trong dấu ngoặc kép sqrt() – trả về căn bậc hai của một số pow() – trả về lũy thừa của một số.

Các Python Library Functions này được định nghĩa bên trong module. Và, để sử dụng chúng, chúng ta phải import module vào bên trong chương trình của mình.

Ví dụ:

import math

# sqrt computes the square root
square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power
power = pow(2, 3)

print("2 to the power 3 is",power)

Scope của variable

Scope liên quan đến nơi một biến có thể được sử dụng. Nếu bạn xác định một biến, nó không nhất thiết phải sử dụng được ở mọi nơi trong code. Một biến được xác định trong một hàm chỉ được biết trong một hàm (chỉ dùng được bên trong hàm đó), trừ khi bạn trả về nó. Ví dụ:

def something():
   localVar = 1

# this will crash because localVar is a local variable
print(localVar)

Điều đó có nghĩa là trừ khi bạn trả về các biến từ một hàm, chúng chỉ có thể được sử dụng ở đó. Điều này hoàn toàn trái ngược với các global variables: các global variables có thể được sử dụng ở bất cứ đâu kể cả trong nhiều function và main code. Global variables thường được định nghĩa ở đầu chương trình.

Trong chương trình dưới đây, balance là một global variable. Nó có thể được sử dụng ở bất cứ đâu trong code. Nhưng biến x chỉ có thể được sử dụng bên trong addAmount (local variable).

#!/usr/bin/env python3

balance = 0

def addAmount(x):
    global balance
    balance = balance + x

addAmount(5)
print(balance)

Function arguments

def add_numbers(a, b):
    sum = a + b
    print('Sum:', sum)

add_numbers(2, 3)

# Output: Sum: 5

Trong ví dụ trên, hàm add_numbers() nhận hai tham số: a và b. Chú ý dòng:

add_numbers(2, 3)

Ở đây, add_numbers(2, 3) chỉ định rằng tham số a và b sẽ nhận giá trị 2 và 3 tương ứng.

Trong Python, chúng ta có thể cung cấp các giá trị mặc định cho các đối số của hàm. Chúng ta sử dụng toán tử = để cung cấp các giá trị mặc định. Ví dụ,

def add_numbers( a = 7,  b = 8):
    sum = a + b
    print('Sum:', sum)


# function call with two arguments
add_numbers(2, 3)

#  function call with one argument
add_numbers(a = 2)

# function call with no arguments
add_numbers()

Trong keyword arguments, các đối số được gán dựa trên tên của các đối số. Ví dụ:

def display_info(first_name, last_name):
    print('First Name:', first_name)
    print('Last Name:', last_name)

display_info(last_name = 'Cartman', first_name = 'Eric')

Hàm Python với các đối số tùy ý (Arbitrary Arguments)

Đôi khi, chúng ta không biết trước số lượng đối số sẽ được truyền vào một hàm. Để xử lý loại tình huống này, chúng ta có thể sử dụng Arbitrary Arguments trong Python.

Arbitrary Arguments cho phép chúng ta chuyển một số lượng giá trị khác nhau trong khi gọi hàm. Chúng ta sử dụng dấu hoa thị (*) trước tên tham số để biểu thị loại đối số này. Ví dụ:

# program to find sum of multiple numbers 

def find_sum(*numbers):
    result = 0

    for num in numbers:
        result = result + num

    print("Sum = ", result)

# function call with 3 arguments
find_sum(1, 2, 3)

# function call with 2 arguments
find_sum(4, 9)

Python recursion

Trong Python, chúng ta biết rằng một hàm có thể gọi các hàm khác. Hàm thậm chí có thể gọi chính nó. Các kiểu cấu trúc này được gọi là các hàm đệ quy (recursive functions)

Ví dụ:

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))


num = 3
print("The factorial of", num, "is", factorial(num))

Lợi ích của Recursion:

  • Một nhiệm vụ phức tạp có thể được chia nhỏ thành các vấn đề con đơn giản hơn bằng cách sử dụng đệ quy.

  • Tạo trình tự dễ dàng hơn khi dùng đệ quy so với sử dụng một số phép lặp lồng nhau.

Tuy nhiên, đệ quy cũng có những nhược điểm:

  • Đôi khi logic đằng sau đệ quy khó theo dõi.

  • Các cuộc gọi đệ quy rất tốn kém (không hiệu quả) vì chúng chiếm nhiều bộ nhớ và thời gian.

  • Hàm đệ quy khó debug.

Lambda/Anonymous Function

Trong Python, hàm lambda là một loại hàm đặc biệt không có tên hàm. Ví dụ:

lambda : print('Hello World')

Chúng ta sử dụng từ khóa lambda thay vì def để tạo hàm lambda. Đây là cú pháp để khai báo hàm lambda:

lambda argument(s) : expression

Ví dụ:

greet = lambda : print('Hello World')

Ở đây, chúng ta đã định nghĩa một hàm lambda và gán nó cho biến có tên là hello. Để thực thi hàm lambda này, chúng ta cần gọi nó. Đây là cách chúng ta có thể gọi hàm lambda:

# call the lambda
greet()

Tương tự như các hàm bình thường, hàm lambda cũng có thể chấp nhận các arguments. Ví dụ:

# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user('Delilah')

# Output: Hey there, Delilah

Trong ví dụ trên, chúng ta gán hàm lambda cho biến welcome_user. Ở đây, tên sau từ khóa lambda chỉ định rằng hàm lambda chấp nhận argument có tên name. Lưu ý cách gọi hàm:

greet_user('Delilah')

Ở đây, chúng ta đã pass 1 giá trị string ‘Delilah’ cho hàm lambda.

Global Keyword

Trong Python, từ khóa global cho phép chúng ta sửa đổi biến bên ngoài phạm vi hiện tại. Nó được sử dụng để tạo một biến global và thực hiện các thay đổi đối với biến đó trong ngữ cảnh global.

c = 1 # global variable

def add():
    print(c)

add()

# Output: 1

Ở đây, chúng ta có thể thấy rằng chúng ta đã truy cập một biến global từ bên trong một hàm. Tuy nhiên, nếu chúng ta cố gắng sửa đổi biến global từ bên trong một hàm thành:

# global variable
c = 1 

def add():

     # increment c by 2
    c = c + 2

    print(c)

add()

Output sẽ là:

UnboundLocalError: local variable 'c' referenced before assignment

Điều này là do chúng ta chỉ có thể truy cập biến global chứ không thể sửa đổi nó từ bên trong hàm. Giải pháp cho việc này là sử dụng từ khóa global:

# global variable
c = 1 

def add():

    # use of global keyword
    global c

    # increment c by 2
    c = c + 2 

    print(c)

add()

# Output: 3

Trong ví dụ trên, chúng ta đã định nghĩa c là từ khóa global bên trong hàm add(). Sau đó, chúng ta đã tăng biến c lên 2, tức là c = c + 2. Như chúng ta có thể thấy khi gọi hàm add(), giá trị của biến c được thay đổi từ 1 thành 3.

Trong Python, chúng ta cũng có thể sử dụng từ khóa global trong một hàm lồng nhau. Ví dụ:

def outer_function():
    num = 20

    def inner_function():
        global num
        num = 25

    print("Before calling inner_function(): ", num)
    inner_function()
    print("After calling inner_function(): ", num)

outer_function()
print("Outside both function: ", num)

Các quy tắc cơ bản cho từ khóa toàn cầu trong Python là:

  • Khi chúng ta tạo một biến bên trong một function, nó mặc định là local.

  • Khi chúng ta định nghĩa một biến bên ngoài một function, nó là biến global, và bạn không cần phải sử dụng từ khóa global.

  • Chúng ta sử dụng từ khóa global để đọc và ghi một biến global bên trong một function.

  • Việc sử dụng từ khóa global bên ngoài một function không có ý nghĩa.

Modules

Module là một tệp chứa code để thực hiện một tác vụ cụ thể. Một module có thể chứa các biến, function, class, v.v. Hãy xem một ví dụ: tạo một module. Nhập nội dung sau và lưu dưới dạng example.py:

# Python Module addition

def add(a, b):

   result = a + b
   return result

Ở đây, chúng ta đã định nghĩa một hàm add() bên trong một module có tên là example. Hàm nhận vào hai số và trả về tổng của chúng.

Chúng ta có thể import một module bên trong 1 module khác. Chúng ta sử dụng từ khóa import để import module:

import example

Thao tác này không import trực tiếp tên của các hàm được định nghĩa trong example. Nó chỉ import module tên là example. Sử dụng tên module, chúng ta có thể truy cập chức năng bằng cách sử dụng dấu chấm. Ví dụ:

addition.add(4,5) # returns 9

Giả sử chúng ta muốn lấy giá trị của số pi, đầu tiên chúng ta nhập module math c và sử dụng math.pi. Ví dụ:

# import standard math module 
import math

# use math.pi to get value of pi
print("The value of pi is", math.pi)

Chúng ta cũng có thể đặt lại tên cho module được import:

# import module by renaming it
import math as m

print(m.pi)

# Output: 3.141592653589793

Chúng tôi có thể import các tên cụ thể từ một module mà không cần import toàn bộ module. Ví dụ:

# import only pi from math module
from math import pi

print(pi)

# Output: 3.141592653589793

Hoặc import tất cả các tên:

# import all names from the standard module math
from math import *

print("The value of pi is", pi)

Ở đây, chúng ta đã import tất cả các định nghĩa từ module toán học. Điều này bao gồm tất cả các tên hiển thị trong phạm vi ngoại trừ những tên bắt đầu bằng dấu gạch dưới (private definitions).

Import * không phải là một cách lập trình tốt. Điều này có thể dẫn đến sự trùng lặp cho các identifier, và làm code khó đọc hơn:

# import all names from the standard module math
from math import *

print("The value of pi is", pi)

Trong Python, chúng ta có thể sử dụng hàm dir() để liệt kê tất cả các tên hàm trong một module. Ví dụ, trước đó chúng ta đã định nghĩa hàm add() trong ví dụ về module. Chúng ta có thể sử dụng dir trong module example theo cách sau:

dir(example)

['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']

Package

Package là một container các chức năng khác nhau để thực hiện các tác vụ cụ thể. Ví dụ: package math bao gồm hàm sqrt() để thực hiện căn bậc hai của một số.

Khi làm việc với các dự án lớn, chúng ta phải xử lý một lượng lớn code và việc viết mọi thứ cùng nhau trong cùng một tệp sẽ khiến code của chúng ta trông lộn xộn. Thay vào đó, chúng ta có thể tách code của mình thành nhiều tệp bằng cách chia code liên quan với nhau thành các package.

Ví dụ về cấu tạo 1 package:

Chúng ta có thể sử dụng các module trong 1 package bằng cách import và sử dụng dấu chấm:

import Game.Level.start

Game.Level.start.select_difficulty(2)

Hoặc:

from Game.Level import start
start.select_difficulty(2)

Hoặc chỉ import function mà ta cần:

from Game.Level.start import select_difficulty
select_difficulty(2)

Mutiple return

Các hàm Python có thể trả về nhiều biến. Các biến này có thể được lưu trữ trực tiếp trong các biến. Một hàm không bắt buộc phải trả về một biến, nó có thể trả về 0, một, hai hoặc nhiều biến.

Các biến được định nghĩa trong hàm chỉ được biết trong hàm. Đó là do phạm vi của biến. Nhưng nếu bạn muốn sử dụng đầu ra của hàm trong chương trình của mình? => Trong trường hợp đó, bạn có thể trả về các biến từ một hàm. Trong trường hợp đơn giản nhất, bạn có thể trả về một biến duy nhất:

def complexfunction(a,b):
    sum = a +b
    return sum

Lúc này, bạn có thể sử dụng hàm trong chương trình của mình như sau:

complexfunction(2,3)

Trường hợp trả về nhiều biến:

#!/usr/bin/env python3

def getPerson():
    name = "Leona"
    age = 35
    country = "UK"
    return name,age,country

name,age,country = getPerson()
print(name)
print(age)
print(country)

Control structures

if…else Statement

Trong ví dụ dưới đây, chúng ta hiển thị câu lệnh if, một cấu trúc điều khiển (Control structures). Câu lệnh if đánh giá dữ liệu (một điều kiện) và đưa ra lựa chọn. Hãy xem xét một câu lệnh if cơ bản. Ở dạng cơ bản, nó trông như thế này:

#!/usr/bin/env python3
if <condition>:
    <statement>

Một câu lệnh if không cần phải có một câu lệnh duy nhất, nó có thể có một khối (block). Một khối là nhiều hơn một câu lệnh. Ví dụ bên dưới hiển thị một khối mã có 3 câu lệnh (print). Một khối được Python xem như một thực thể duy nhất, điều đó có nghĩa là nếu điều kiện là đúng, toàn bộ khối sẽ được thực thi (mọi câu lệnh).

#!/usr/bin/env python3
x = 4
if x < 5:
    print("x is smaller than five")
    print("this means it's not equal to five either")
    print("x is an integer")

Các ngôn ngữ lập trình khác thường sử dụng các ký hiệu như {, } hoặc các từ bắt đầu và kết thúc. Tuy nhiên, hãy xem xét trong python:

if <condition>:
    <statement>
    <statement>
    <statement>

<statement>  # not in block

Sau khi hoàn thành câu lệnh if, Python tiếp tục thực thi chương trình. Câu lệnh if kết thúc bằng phần ghi chú của nó, nó lùi lại bốn khoảng trắng.

Nó cũng sử dụng từ khóa else. Ví dụ: Khi so sánh tuổi (tuổi < 5) else (>= 5) thì thực hiện một tác vụ khác:

#!/usr/bin/env python3

gender = input("Gender? ")
gender = gender.lower()
if gender == "male":
    print("Your cat is male")
elif gender == "female":
    print("Your cat is female")
else:
    print("Invalid input")

age = int(input("Age of your cat? "))
if age < 5:
    print("Your cat is young.")
else:
    print("Your cat is adult.")

Nếu bạn muốn đánh giá một số trường hợp, bạn có thể sử dụng mệnh đề elif. elif là viết tắt của other if:

>>> x = 3
>>> if x == 2:
...     print('two')
... elif x == 3:
...     print('three')
... elif x == 4:
...     print('four')
... else:
...     print('something else')
... 
three
>>>

Đoạn code trên tương đương với:

x = 3
if x == 2:
    print('two')
if x == 3:
    print('three')
if x == 4:
    print('four')

for Loop

Trong Python, vòng lặp for được sử dụng để chạy một block code một số lần nhất định. Nó được sử dụng để lặp qua list,tuple, string…

Cú pháp của vòng lặp for là:

for val in sequence:
    # statement(s)

Lặp một list:

languages = ['Swift', 'Python', 'Go', 'JavaScript']

# access items of a list using for loop
for language in languages:
    print(language)

Python for Loop với range()

range là một chuỗi các giá trị nằm giữa hai khoảng số. Chúng ta có thể sử dụng hàm range() để xác định một dải giá trị. Ví dụ:

values = range(4)

Ở đây, range() xác định một phạm vi chứa các giá trị 0, 1, 2, 3.

# use of range() to define a range of values
values = range(4)

# iterate from i = 0 to i = 3
for i in values:
    print(i)

Python for loop với else:

digits = [0, 1, 5]

for i in digits:
    print(i)
else:
    print("No items left.")

while Loop

Vòng lặp while trong Python được sử dụng để chạy block code cho đến khi đáp ứng một điều kiện nhất định. Cú pháp của vòng lặp while là:

while condition:
    # body of while loop

Ví dụ:

# program to display numbers from 1 to 5

# initialize the variable
i = 1
n = 5

# while loop from i = 1 to 5
while i <= n:
    print(i)
    i = i + 1

hoặc:

# program to calculate the sum of numbers
# until the user enters zero

total = 0

number = int(input('Enter a number: '))

# add numbers until number is zero
while number != 0:
    total += number    # total = total + number

    # take integer input again
    number = int(input('Enter a number: '))


print('total =', total)

Lặp vô hạn:

Nếu điều kiện của một vòng lặp luôn là True, vòng lặp sẽ chạy vô hạn (cho đến khi bộ nhớ đầy). Ví dụ:

age = 32

# the test condition is always True
while age > 18:
    print('You can vote')

Trong Python, một vòng lặp while có thể có một block else tùy chọn. Ở đây, phần khác được thực thi sau khi điều kiện của vòng lặp được đánh giá là False:

counter = 0

while counter < 3:
    print('Inside loop')
    counter = counter + 1
else:
    print('Inside else')

else block sẽ không thực thi nếu vòng lặp while bị kết thúc bởi câu lệnh break:

counter = 0

while counter < 3:
    # loop ends because of break
    # the else part is not executed 
    if counter == 1:
        break

    print('Inside loop')
    counter = counter + 1
else:
    print('Inside else')

break and continue

Ví dụ break statement:

# program to find first 5 multiples of 6

i = 1

while i <= 10:
    print('6 * ',(i), '=',6 * i)

    if i >= 5:
        break

    i = i + 1

Ví dụ continue:

for i in range(5):
    if i == 3:
        continue
    print(i)

Python continue Statement với while Loop

# program to print odd numbers from 1 to 10

num = 0

while num < 10:
    num += 1

    if (num % 2) == 0:
        continue

    print(num)

Pass

Trong lập trình Python, câu lệnh pass là một câu lệnh null có thể được sử dụng làm trình giữ chỗ cho code trong tương lai. Giả sử chúng ta có một vòng lặp hoặc một chức năng chưa được triển khai, nhưng chúng ta muốn triển khai nó trong tương lai. Trong những trường hợp như vậy, chúng ta có thể sử dụng câu lệnh pass.

Ví dụ:

n = 10

# use pass inside if statement
if n > 10:
    pass

print('Hello')

pass Statement trong Function hoặc Class

def function(args):
    pass
class Example:
    pass

Nested loop

Một vòng lặp có thể chứa một hoặc nhiều vòng lặp khác: bạn có thể tạo một vòng lặp bên trong một vòng lặp. Nguyên tắc này được gọi là vòng lặp lồng nhau. Các vòng lặp lồng nhau trải qua hai hoặc nhiều vòng lặp.

Chúng ta chỉ nên dùng 2-3 vòng lặp lồng nhau, nếu quá nhiều vòng lặp lồng, sẽ gây rối mắt, và khó debug về sau.

Ví dụ:

#!/usr/bin/python

persons = [ "John", "Marissa", "Pete", "Dayton" ]
restaurants = [ "Japanese", "American", "Mexican", "French" ]

for person in persons:
    for restaurant in restaurants:
        print(person + " eats " + restaurant)

Date and time

datetime module

Python có một mô-đun tên là datetime để làm việc với ngày và giờ. Nó cung cấp nhiều lớp khác nhau để biểu diễn và thao tác ngày và giờ, cũng như để định dạng và phân tích ngày và giờ ở nhiều định dạng khác nhau.

Ví dụ:

import datetime

# get the current date and time
now = datetime.datetime.now()

print(now)
import datetime

# get current date
current_date = datetime.date.today()

print(current_date)

Python datetime.date Class

Trong Python, chúng ta có thể khởi tạo các đối tượng ngày từ class date:

import datetime

d = datetime.date(2022, 12, 25)
print(d)

Lấy ngày hiện tại bằng cách sử dụng today()

from datetime import date

# today() to get current date
todays_date = date.today()

print("Today's date =", todays_date)

Lấy ngày từ timestamp

from datetime import date

timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)

In năm, tháng và ngày hôm nay

from datetime import date

# date object of today's date
today = date.today() 

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Python datetime.time Class

Time object thể hiện thời gian

from datetime import time

# time(hour = 0, minute = 0, second = 0)
a = time()
print(a)

# time(hour, minute and second)
b = time(11, 34, 56)
print(b)

# time(hour, minute and second)
c = time(hour = 11, minute = 34, second = 56)
print(c)

# time(hour, minute, second, microsecond)
d = time(11, 34, 56, 234566)
print(d)

In ra giờ, phút, giây

from datetime import time

a = time(11, 34, 56)

print("Hour =", a.hour)
print("Minute =", a.minute)
print("Second =", a.second)
print("Microsecond =", a.microsecond)

datetime.datetime Class

Python datetime object

from datetime import datetime

# datetime(year, month, day)
a = datetime(2022, 12, 28)
print(a)

# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2022, 12, 28, 23, 55, 59, 342380)
print(b)

In ra năm, tháng, ngày, giờ, phút, giây và timestamp

from datetime import datetime

a = datetime(2022, 12, 28, 23, 55, 59, 342380)

print("Year =", a.year)
print("Month =", a.month)
print("Hour =", a.hour)
print("Minute =", a.minute)
print("Timestamp =", a.timestamp())

Python datetime.timedelta Class

from datetime import datetime, date

# using date()
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)

t3 = t1 - t2

print("t3 =", t3)

# using datetime()
t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5
print("t6 =", t6)

print("Type of t3 =", type(t3)) 
print("Type of t6 =", type(t6))

Python format datetime

Cách thể hiện ngày và giờ có thể khác nhau ở những nơi, tổ chức khác nhau, v.v. Việc sử dụng mm/dd/yyyy phổ biến hơn ở Hoa Kỳ, trong khi dd/mm/yyyy phổ biến hơn ở Vương quốc Anh.

Python có các phương thức strftime() và strptime() để xử lý việc này.

strftime()

Phương thức strftime() được định nghĩa trong các class date, datetimetime. Phương thức tạo ra một string được định dạng từ một đối tượng ngày, giờ hoặc thời gian nhất định.

from datetime import datetime

# current date and time
now = datetime.now()

t = now.strftime("%H:%M:%S")
print("Time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

%Y, %m, %d, %H,.. là format code. Method strftime() lấy một hoặc nhiều code định dạng và trả về một chuỗi được định dạng dựa trên nó.

Trong ví dụ trên, t, s1 và s2 là các string.

  • %Y – year [0001,…, 2018, 2019,…, 9999]

  • %m – month [01, 02, …, 11, 12]

  • %d – day [01, 02, …, 30, 31]

  • %H – hour [00, 01, …, 22, 23

  • %M – minute [00, 01, …, 58, 59]

  • %S – second [00, 01, …, 58, 59]

strptime()

Phương thức strptime() tạo một đối tượng datetime từ một chuỗi đã cho (đại diện cho ngày và giờ). Ví dụ:

from datetime import datetime

date_string = "25 December, 2022"
print("date_string =", date_string)

# use strptime() to create date object
date_object = datetime.strptime(date_string, "%d %B, %Y")

print("date_object =", date_object)

Phương thức strptime() nhận hai argument:

  • một string đại diện cho ngày và thời gian

  • format code %d, %B và %Y được sử dụng cho ngày, tháng và năm tương ứng.

Handle timezone:

Giả sử, chúng ta đang làm việc trên một dự án và cần hiển thị ngày và giờ dựa trên múi giờ của họ. Thay vì cố gắng tự xử lý múi giờ, chúng ta nên sử dụng mô-đun pytZ.

from datetime import datetime
import pytz

local = datetime.now()
print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S"))


tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London:", datetime_London.strftime("%m/%d/%Y, %H:%M:%S"))

Python files

Read file

Có hai cách để đọc tệp:

  • từng dòng

  • đọc từng khối

Đọc từng dòng: Sử dụng method readlines()

#!/usr/bin/env python

filename = "file.py"

with open(filename) as f:
    content = f.readlines()

print(content)

Đọc theo block: sử dụng method read()

#!/usr/bin/env python

filename = "file.py"

infile = open(filename, 'r')
data = infile.read()
infile.close()

print(data)

Write file

Tạo một file mới:

#!/usr/bin/env python

# create and open file
f = open("test.txt","w")

# write data to file 
f.write("Hello World, \n")
f.write("This data will be written to the file.")

# close file
f.close()

Ghi bổ sung vào 1 file:

#!/usr/bin/env python

# create and open file
f = open("test.txt","a")

# write data to file 
f.write("Don't delete existing data \n")
f.write("Add this to the existing file.")

# close file
f.close()

Đọc JSON file

import json

# read file
with open('example.json', 'r') as myfile:
    data=myfile.read()

# parse file
obj = json.loads(data)

# show values
print("usd: " + str(obj['usd']))
print("eur: " + str(obj['eur']))
print("gbp: " + str(obj['gbp']))

Try và except

Try và except statement được sử dụng để xử lý ngoại lệ.

try:
    <do something>
except Exception:
    <handle the error>

Ý tưởng của khối try-except là:

  • try: code có (các) ngoại lệ cần bắt. Nếu ngoại lệ xảy ra, nó sẽ nhảy thẳng vào khối except.

  • except: code này chỉ được thực thi nếu một ngoại lệ xảy ra trong khối try.

Nó có thể được kết hợp với các từ khóa else và finally.

  • else: Code trong khối khác chỉ được thực thi nếu không có ngoại lệ nào được đưa ra trong khối try.

  • finally: Code trong khối cuối cùng luôn được thực thi, bất kể có ngoại lệ nào xảy ra hay không.

try-except:

try:
    x = input("Enter number: ")
    x = x + 1
    print(x)
except:
    print("Invalid input")

try finally

Cú pháp:

try:
    <do something>
except Exception:
    <handle the error>
finally:
    <cleanup>

Ví dụ:

try: 
    f = open("test.txt")
except: 
    print('Could not open file')
finally:
    f.close()

print('Program continue')

try else:

try:
    x = 1
except:
    print('Failed to set x')
else:
    print('No exception occured')
finally:
    print('We always do this')

Raise Exception:

Python có thể force trả ra một ngoại lệ bằng từ khóa raise:

>>> raise MemoryError("Out of memory")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError: Out of memory