# dòng code mà ai cũng sẽ thử
print("Hello, World!")
Hello, World!
# viết comment 1 dòng
print("Hello, World!")
Hello, World!
"""
viết comment nhiều dòng
"""
print("Hello, World!")
Hello, World!
Variables là objects trong Python dùng để lưu giá trị nào đó như số hoặc chuỗi.
# gán giá trị cho biến
male = 70
family_status = "Single"
amt_income = 135000.0
# dùng dấu ',' để ghép nhiều mệnh đề
print("male =", male)
('male =', 70)
# dùng {fieldname:conversion} để định dạng chuỗi
# link 1: https://docs.python.org/3.5/library/string.html#string.Formatter.format
# link 2: https://www.python-course.eu/python3_formatted_output.php
# link 3: https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
# mặc định {}
print("family status = {}".format(family_status))
# {fieldname} có thứ tự
print("male = {1}, family status = {0}".format(family_status, male))
# format integer {:conversion}
print("male = {:05d}".format(male))
# format float {:conversion}
print("amount incode = {:08.2f}".format(amt_income))
# placeholder arg
print("amount incode = {} {info}".format(amt_income, info="Wow!"))
family status = Single male = 70, family status = Single male = 00070 amount incode = 135000.00 amount incode = 135000.0 Wow!
Có nhiều loại kiểu dữ liệu trong variables. Trong biến số ta có thể có kiểu integers (int), floats (float), etc.
# kiểm tra kiểu dữ liệu
print(type(male))
print(type(family_status))
print(type(amt_income))
<type 'int'> <type 'str'> <type 'float'>
Lists là objects trong Python dùng để lưu chuỗi có thứ tự số hoặc text. Các phần tử cùng kiểu hoặc khác kiểu dữ liệu
# tạo list
ls_id = [100065, 100005, 100150]
print("type: {}, ls_id = {}, length = {}".format(type(ls_id), ls_id, len(ls_id)))
type: <type 'list'>, ls_id = [100065, 100005, 100150], length = 3
# thêm phần tử vào list
ls_id.append(100152)
print(ls_id)
[100065, 100005, 100150, 100152]
ls_account_info = [100107, "Cash loans", "M", 180000.0]
print("sk_id_curr:{}, name_contract:{}, code_gender:{}, amt_income:{}".format(ls_account_info[0],
ls_account_info[1],
ls_account_info[2],
ls_account_info[3]))
sk_id_curr:100107, name_contract:Cash loans, code_gender:M, amt_income:180000.0
# truy xuất list
print(ls_account_info[0])
print(ls_account_info[-2])
100107 M
# slicing list
print(ls_account_info[2:4])
['M', 180000.0]
# nối 2 list
ls_z = ls_id + ls_account_info
print(ls_z)
[100065, 100005, 100150, 100152, 100107, 'Cash loans', 'M', 180000.0]
Immutable list (không thể thay đổi giá trị của phần tử)
ls_flag_own_car = ["Y", "Y", "N", "Y", "N", "N"]
ls_flag_own_car[0] = "N"
print(ls_flag_own_car)
tpl_flag_own_car = ("Y", "Y", "N", "Y", "N", "N")
try:
tpl_flag_own_car[0] = "N"
except Exception as err:
print("Reason: {}".format(err))
['N', 'Y', 'N', 'Y', 'N', 'N'] Reason: 'tuple' object does not support item assignment
# thêm phần tử vào tuple
tpl_flag_own_car = tpl_flag_own_car + ("Unknown",)
print (tpl_flag_own_car)
('Y', 'Y', 'N', 'Y', 'N', 'N', 'Unknown')
List of key-value pairs
dict_account_info = {
"sk_id_curr": 100107,
"name_contract": "Cash loans",
"code_gender": "M",
"amt_income": 180000.0
}
print(dict_account_info)
{'name_contract': 'Cash loans', 'amt_income': 180000.0, 'code_gender': 'M', 'sk_id_curr': 100107}
# thay đổi giá trị của key
dict_account_info["amt_income"] = 27000.5
print(dict_account_info)
{'name_contract': 'Cash loans', 'amt_income': 27000.5, 'code_gender': 'M', 'sk_id_curr': 100107}
# thêm cặp key-value mới
dict_account_info["cnt_children"] = 2
print(dict_account_info)
{'name_contract': 'Cash loans', 'cnt_children': 2, 'amt_income': 27000.5, 'code_gender': 'M', 'sk_id_curr': 100107}
# độ dài của dictionary
print(len(dict_account_info))
5
Ta dùng mệnh đề if để rẽ nhánh câu lệnh theo các điều kiện chỉ định
code_gender = "M"
if code_gender == "M":
print("Gender: Male")
elif code_gender == "F":
print("Gender: Female")
else:
print("Unknown")
Gender: Male
Ta dùng for loop để duyệt từng phần tử trong list hoặc tuple
# for loop in list
for flag in ls_flag_own_car:
print(flag)
# for loop with enumerate
for i, flag in enumerate(ls_flag_own_car):
print(i, flag)
N Y N Y N N (0, 'N') (1, 'Y') (2, 'N') (3, 'Y') (4, 'N') (5, 'N')
# for loop in dictionary
for k, v in dict_account_info.items():
print("{}: {}".format(k, v))
name_contract: Cash loans cnt_children: 2 amt_income: 27000.5 code_gender: M sk_id_curr: 100107
num_cars = [2, 1, 3, 4]
double_num_cars = [num * 2 for num in num_cars]
print(double_num_cars)
[4, 2, 6, 8]
ls_paragraph = [
['Many',
'people',
'struggle',
'to',
'get',
'loans',
'due',
'to',
'insufficient',
'or',
'non-existent',
'credit',
'histories.',
'And,',
'unfortunately,',
'this',
'population',
'is',
'often',
'taken',
'advantage',
'of',
'by',
'untrustworthy',
'lenders.'],
['Home',
'Credit',
'strives',
'to',
'broaden',
'financial',
'inclusion',
'for',
'the',
'unbanked',
'population',
'by',
'providing',
'a',
'positive',
'and',
'safe',
'borrowing',
'experience.',
'In',
'order',
'to',
'make',
'sure',
'this',
'underserved',
'population',
'has',
'a',
'positive',
'loan',
'experience,',
'Home',
'Credit',
'makes',
'use',
'of',
'a',
'variety',
'of',
'alternative',
'data--including',
'telco',
'and',
'transactional',
'information--to',
'predict',
'their',
"clients'",
'repayment',
'abilities.']
]
flatten_paragraph = [word for paragraph in ls_paragraph for word in paragraph]
print(" ".join(flatten_paragraph))
Many people struggle to get loans due to insufficient or non-existent credit histories. And, unfortunately, this population is often taken advantage of by untrustworthy lenders. Home Credit strives to broaden financial inclusion for the unbanked population by providing a positive and safe borrowing experience. In order to make sure this underserved population has a positive loan experience, Home Credit makes use of a variety of alternative data--including telco and transactional information--to predict their clients' repayment abilities.
# viết hàm tính toán
def your_function_name(arg_here=2):
return_value = 2 * arg_here
return return_value
print(your_function_name())
print(your_function_name(3))
4 6
# viết hàm anonymous
f01 = lambda x: x * 2
print(f01(2))
print(f01(3))
4 6
Những đoạn code trong notebook này đủ để bạn làm một project Data Science cơ bản. Để tìm hiểu thêm bạn có thể tham gia khoá học này https://www.codecademy.com/learn/learn-python