<jupyter_start><jupyter_text>Python 101 : Basic Python Programming [Part 2]by <NAME>14/09/2021[datacamp] Cheat sheets http://datacamp-community-prod.s3.amazonaws.com/0eff0330-e87d-4c34-88d5-73e80cb955f2<jupyter_code>a, b = 1, "Python!"
l = [b, a, a - 1, a]
t = (0, 1, 2, 3, 4)
grade = {
    "A" : 80,
    "B" : 70,
    "C" : 60,
    "D" : 50
}<jupyter_output><empty_output><jupyter_text>Condition & Loop  If...else condition ```if Boolean-expression:  if_block_statementelse:  else_block_statement```<jupyter_code>if len(t) == 5:
  print('length is 5')
else:
  print('length not equals 5')
score = 90
if score >= grade["A"]:
  print("A")
  print("Good Job!")
elif score >= grade["B+"]:
  print("B+")
elif score >= grade["B"]:
  print("B")
elif score >= grade["C"]:
  print("C")
elif score >= grade["D"]:
  print("D")
else:
  print("F")
# Tip:
score = 80
if score >= 80:
  print('A')
if score >= 70:
  print('B')
else:
  print('F')
# Tip:
score = 80
if score >= 80:
  print('A')
elif score >= 70:
  print('B')
else:
  print('F')<jupyter_output>A<jupyter_text>While loop ```while Boolean-expression:  block statement```<jupyter_code>n = 10
count = 1
factorial = 1
while count <= n:
  factorial *= count
  count += 1

print(f'{n}! = {factorial}')<jupyter_output>10! = 3628800<jupyter_text>For loop ```for iterate_var in sequence:  statement```<jupyter_code>for item in l:
  print(item)
# List Comprehension
[i for i in t]
list(t)
[i for i in range(100)]<jupyter_output><empty_output><jupyter_text>Loop controller : break, continue & else **break**```while/for loop:  statement inside loop  if condition:    break -----------------|  statement inside loop    |statement outside loop  <--|```<jupyter_code># Simple minimization

import matplotlib.pyplot as plt

dom = [-1 + i*(0.1) for i in range(0,21)]
ran = [i**2 for i in dom]
plt.plot(dom, ran, label='y=x**2')
plt.legend()
plt.show()
x_init = -1.
plt.plot(dom, ran, label='y=x**2')
while True:
  slope_at_x = 2.*x_init
  y = [slope_at_x*(i-x_init)+x_init**2 for i in dom]
  plt.plot(dom, y, 'r-')
  plt.ylim([-0.1,1.])
  plt.scatter(x_init, x_init**2, color='r', marker='o')
  if abs(slope_at_x) < 1e-5: #Tip: slope_at_x == 0.
    break
  x_init += 0.1

print(f'solution : ({x_init},{x_init**2})')
plt.legend()
plt.show()
?ord
?chr

english_alphabet_lowercase = 'abcdefghijklmnopqrstuvwxyz'
english_alphabet_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_uppercase = [ord(t) for t in english_alphabet_uppercase]
ascii_lowercase = [ord(t) for t in english_alphabet_lowercase]
print(ascii_uppercase, ascii_lowercase, sep='\n\n')
# Word Guess

target = 'ANT' # input('Enter your word : ')
target = [ord(t) for t in target]
code_size = len(target)
data = range(65, 91) # ASCII CODE
idx_data = [0 for i in range(code_size)]
iter = 1
while True:
  letter_idx = code_size - 1
  word = [data[i] for i in idx_data]
  fitness = sum([word[i]==target[i] for i in range(code_size)])
  print('Iteration: {}\t predicted_word: {}'.format(iter, ''.join([chr(w) for w in word])))
  if fitness == code_size or letter_idx == -1:
    break
  iter += 1
  idx_data[-1] += 1
  while idx_data[letter_idx] > len(data)-1:
    idx_data[letter_idx] = 0
    letter_idx -= 1
    if letter_idx == 0:
      break
    idx_data[letter_idx] += 1<jupyter_output>Iteration: 1	 predicted_word: AAA
Iteration: 2	 predicted_word: AAB
Iteration: 3	 predicted_word: AAC
Iteration: 4	 predicted_word: AAD
Iteration: 5	 predicted_word: AAE
Iteration: 6	 predicted_word: AAF
Iteration: 7	 predicted_word: AAG
Iteration: 8	 predicted_word: AAH
Iteration: 9	 predicted_word: AAI
Iteration: 10	 predicted_word: AAJ
Iteration: 11	 predicted_word: AAK
Iteration: 12	 predicted_word: AAL
Iteration: 13	 predicted_word: AAM
Iteration: 14	 predicted_word: AAN
Iteration: 15	 predicted_word: AAO
Iteration: 16	 predicted_word: AAP
Iteration: 17	 predicted_word: AAQ
Iteration: 18	 predicted_word: AAR
Iteration: 19	 predicted_word: AAS
Iteration: 20	 predicted_word: AAT
Iteration: 21	 predicted_word: AAU
Iteration: 22	 predicted_word: AAV
Iteration: 23	 predicted_word: AAW
Iteration: 24	 predicted_word: AAX
Iteration: 25	 predicted_word: AAY
Iteration: 26	 predicted_word: AAZ
Iteration: 27	 predicted_word: ABA
Iteration: 28	 predicted_word: ABB
Iteration: 29	 predicted_word[...]<jupyter_text>**continue**```while/for loop:  statement inside loop <--|  if condition:            |    continue --------------|  statement inside loopstatement outside loop```<jupyter_code># Find factors of given number

number = int(input('Input your number : '))
factors, nonfactors = [], []
for n in range(1,number+1):
  if number%n == 0:
    factors.append(n)
    continue
  nonfactors.append(n)

print(f'Factors of {number} are {str(factors)[1:-1]}.')
print(f'{str(nonfactors)[1:-1]} are not factor of {number}.')<jupyter_output>Input your number : 10
Factors of 10 are 1, 2, 5, 10.
3, 4, 6, 7, 8, 9 are not factor of 10.<jupyter_text>**else**```while/for loop:  statement  if condition: break  if condition: continueelse:  statementstatement outside loop```<jupyter_code># Find lucky number
number = input('Enter your number : ')
for n in number:
  if n == '7':
    print(f'your number {number} is lucky number!')
    break
else:
  print('Not found lucky number!')
# Assignment : Find prime number in range(1,input_number) by using the sieve of Eratosthenes algorithm<jupyter_output><empty_output><jupyter_text>Working with Files  Write file<jupyter_code>file = open('output.csv', 'w')
file.write("date,item,price\n")
file.write("2020-02-07,Milk,26.5\n")
file.write("2020-02-08,Water,7\n")
file.close()
header = ("date", "item", "price")
content = [
    ("2020-02-07", "Milk", "26.5"),
    ("2020-02-08", "Water", "7"),
    ("2020-02-08", "Mask", "20"),
    ("2020-02-08", "Lays", "10"),
    ("2020-02-08", "Rice", "6")
]

file = open('products.csv', 'w')
file.write(",".join(header) + "\n")

for row in content:
  file.write(",".join(row) + "\n")

file.close()<jupyter_output><empty_output><jupyter_text>Read file<jupyter_code>with open("products.csv", "r") as f:
  product = f.readlines()

product<jupyter_output><empty_output><jupyter_text>Use Pandas to Read/Write file<jupyter_code>import pandas as pd

products = pd.read_csv("products.csv")
products
type(products)
products.to_csv("new_products.csv")
products<jupyter_output><empty_output><jupyter_text>Tips : JSON in Python> JSON (JavaScript Object Notation) is mainly used to convert the python dictionary above into a JSON string that can be written into a file.> JSON is MAGIC!<jupyter_code>type(grade)
import json
json.dumps(grade)
type(json.dumps(grade))
json_str = json.dumps(grade)
json.loads(json_str)
type(json.loads(json_str))
# Save to output file grade.json
json.dump(grade, open("grade.json", "w"))<jupyter_output><empty_output><jupyter_text>Function*   Standard Library**   Built-in functions [อ่านเพิ่มเติม](https://docs.python.org/3.6/library/functions.html)**   Library functions [อ่านเพิ่มเติม](https://pypi.org/)*   User defined functions  Python Packages Function $\subseteq$ Module $\subseteq$ Package $\subseteq$ Library $\subseteq$ Framework $\subseteq$ Application<jupyter_code>import __hello__
!pip list<jupyter_output>Package                       Version
----------------------------- --------------
absl-py                       0.12.0
alabaster                     0.7.12
albumentations                0.1.12
altair                        4.1.0
appdirs                       1.4.4
argcomplete                   1.12.3
argon2-cffi                   21.1.0
arviz                         0.11.2
astor                         0.8.1
astropy                       4.3.1
astunparse                    1.6.3
atari-py                      0.2.9
atomicwrites                  1.4.0
attrs                         21.2.0
audioread                     2.1.9
autograd                      1.3
Babel                         2.9.1
backcall                      0.2.0
beautifulsoup4                4.6.3
bleach                        4.0.0
blis                          0.4.1
bokeh                         2.3.3
Bottleneck                    1.3.2
branca                        0.4.2
bs4                           0.0.1
CacheControl[...]<jupyter_text>math<jupyter_code>import math

math.pi<jupyter_output><empty_output><jupyter_text>or using from statement<jupyter_code>from math import pi

pi<jupyter_output><empty_output><jupyter_text>datetime ```from datetime import datetimefrom datetime import date```<jupyter_code>from datetime import datetime

now = datetime.now()
now
from datetime import date

today = date.today()
today
current_time = datetime.now().time()
current_time<jupyter_output><empty_output><jupyter_text>```datetime(y, m, d, h, m, s)```<jupyter_code>dt1 = datetime(2021, 9, 15)
dt2 = datetime(2021, 9, 15, 9, 0, 59)

dt3 = date(2021, 9, 15)
print(dt1, dt2, dt3, sep='\n')<jupyter_output>2021-09-15 00:00:00
2021-09-15 09:00:59
2021-09-15<jupyter_text>```time(h, m, s)```<jupyter_code>from datetime import time

t1 = time(13)
t2 = time(13, 58)
t3 = time(13, 58, 59)
print(t1, t2, t3, sep='\n')<jupyter_output>13:00:00
13:58:00
13:58:59<jupyter_text>Time zone```pytz```<jupyter_code>import pytz
pytz.all_timezones
tz = pytz.timezone('Asia/Bangkok')

datetime.now(tz)
now = now.astimezone(tz)
now
from datetime import date

today = date.today()
today<jupyter_output><empty_output><jupyter_text>```.replace(year=?, month=?, day=?, hour=?, minute=?, second=?)```<jupyter_code>dt1 = dt1.replace(year=2022)
print(dt1)
t1 = t1.replace(second=20)
print(t1)<jupyter_output>13:00:20<jupyter_text>```.day.month.year.weekday()  0-6 -> Mon-Sun.hour.minute.second```<jupyter_code>dt = datetime(2021, 9, 15, 12, 22, 32)
print(dt.day, dt.month, dt.year, dt.weekday(), dt.hour, dt.minute, dt.second, sep='\n')<jupyter_output>15
9
2021
2
12
22
32<jupyter_text>```timedelta```<jupyter_code>print(dt1, dt2, sep='\n')
delta = dt1 - dt2
delta
print(delta)
(delta.seconds//60)//60, (delta.seconds//60)%60, delta.seconds%60
from datetime import timedelta

next_2_months = timedelta(days=60)
next_4_years = timedelta(days=4*365)
last_6_weeks = timedelta(weeks=-6)
next_12_5_hours = timedelta(hours=12.5)
print(dt1)
dt1.__add__(next_2_months)
dt1+next_2_months # operator overloading<jupyter_output><empty_output><jupyter_text>```isoformatstrftime```Read more: https://www.programiz.com/python-programming/datetime/strftime<jupyter_code>today
print(today)
today.isoformat()
today.strftime('%d-%m-%Y')<jupyter_output><empty_output><jupyter_text>Simple functions``` def function_name ( [parameter list] ):  statements  [ return exression ]  [VariableName =] function_name ( [argument list] )```<jupyter_code>def simplefunc():
  s = "ละแมะว่างจริงๆ อะหรือ อะหรือ... อะหรือว่ามีคนอื่น..."
  print(s)

simplefunc()<jupyter_output>ละแมะว่างจริงๆ อะหรือ อะหรือ... อะหรือว่ามีคนอื่น...<jupyter_text>Function arguments* Position arguments* Default arguments* Keyword arguments* Variable-length arguments<jupyter_code># position arguments
def circle_area(radius):
  return pi * radius * radius

circle_area(2)
def rectangle_area(height, width):
  return height * width

rectangle_area(4, 5)
# default arguments
def conversion(amount, rate=31.33):
  return amount * rate


conversion(30)
conversion(30, 33.3333)
# Keyword argument
conversion(amount= 30, rate=33.3333)
def plus(a = 1, b = 2):
  return a + b

plus(4)
# Variable-length arguments
# def functionname( [formal_args], *var_args ):
#   statement

def salesAmount(product, *sales):
  result = 0
  print("Product name : ", product)
  if len(sales) == 0:
    print("No SalesAmount")
  else:
    for var in sales:
      result += var
    print("SalesAmount = ", result)

salesAmount("Book", 10, 20, 50)<jupyter_output>Product name :  Book
SalesAmount =  80<jupyter_text>Variable scope*   Local variable*   Global variable*   Nonlocal variable * support for python3+ *<jupyter_code># Local variable
def myfuncLocal():
  s = "This is local variable"
  print(s)

myfuncLocal()
# Global variable
g = "This is global variable"
def myfuncGlobal():
  # global g
  # g = 1
  print(g)

print(g)
myfuncGlobal()
print(g)
# Nonlocal variable : เหมือนเป็น global ของ subfunction อีกที
def funcMain():
  # global x
  x = 30
  # print('Value in mainfunction : x = ', x)
  def funcSub():
    x = 19
  print("Before calling subfunction : x = ", x)
  funcSub()
  print("After calling subfunction : x = ", x)

x = 85 # define global variable
funcMain()
print("Value of x in mainfunction : x = ", x)<jupyter_output>Before calling subfunction : x =  30
After calling subfunction : x =  30
Value of x in mainfunction : x =  85<jupyter_text>Tips1 : ``return`` vs ``not return``<jupyter_code>def myfunc():
  print('Hey guy!')
  # return print('Hey guy!')

a = myfunc()
a
print(a)
def myfunc():
  return 'Hey guy!'

a = myfunc()
print(a)<jupyter_output>Hey guy!<jupyter_text>Tips2 : Lambda function``` function_name = lambda [arg1 [, arg2,..., argn]] : expression```<jupyter_code>rectangle_area = lambda height, width : height * width
rectangle_area(10, 20)
theta = lambda i : 2*i if (i < 5) else 0
THETA = [theta(i) for i in range(1, 10)]
THETA<jupyter_output><empty_output><jupyter_text>Tips3 : Decorators[อ่านเพิ่มเติม](https://medium.com/@skblackcat/decorator-%E0%B9%83%E0%B8%99-python-%E0%B8%84%E0%B8%B7%E0%B8%AD%E0%B8%AD%E0%B8%B0%E0%B9%84%E0%B8%A3-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B8%A1%E0%B8%B1%E0%B8%99%E0%B9%83%E0%B8%8A%E0%B9%89%E0%B8%97%E0%B8%B3%E0%B8%AD%E0%B8%B0%E0%B9%84%E0%B8%A3%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%9A%E0%B9%89%E0%B8%B2%E0%B8%87-ee74e35e84fb)<jupyter_code>def SayHi():
  return 'Hi!'

SayHi()
def callNameFunction(func):
  def wrapper():
    print('Calling {}'.format(func.__name__ ))
    return func()

  return wrapper
def SayHi():
  return 'Hi!'

w = callNameFunction(SayHi)
print(w())
# decorator

@callNameFunction
def SayHi():
  return 'Hi!'

SayHi()<jupyter_output>Calling SayHi
{'fraction_non_alphanumeric': 0.15544825598155088, 'fraction_numerical': 0.05145575093686942, 'mean_word_length': 4.115001842978253, 'pattern_counts': {'":': 0, '<': 105, '<?xml version=': 0, '>': 113, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '28', 'dir': 'jupyter-structured-clean-dedup', 'id': '619474', 'license': 'MIT', 'n_tokens_mistral': 5806, 'n_tokens_neox': 5339, 'n_words': 1201, 'path': 'source/full_code/basic_python_part2.ipynb', 'repo_name': 'Limpapat/Python101', 'size': '13887'}