Day 1 : Slides for my training course, Well Grounded Python Coding. I'm using PyCharm Pro and Anaconda along the course. Not much to read but it's the main material for my teaching.
3. 3
EX01 DATA TYPES & STATEMENT
Data types
•Basic [int, float, boolean, string, char]
•Complex [set, tuple, list, dict]
•type()
Coding Language
•Comment
•Assignment
•Expression
•Blocks (if, loop)
4. 4
EX01 DATA TYPES & STATEMENT (CONT.)
Equality
•Is Operator
•Assigned to
•==
•!=
Caution!
•Variable and naming
•Indents
•Common Errors
5. 5
EX02 VIRTUAL ENVIRONMENT
Why you should use ‘virtual environment’?
•What is venv
•How to config and use venv in PyCharm
•How many of them?
•virtualenv
•conda
•pipenv
8. 8
EX01 MATH CALC 1
Write a program that calculate ‘Area of Square, Rectangle, Triangle’
•Use this formulas [ w * w, w * h, 1/2 * b * h ]
•Note about integer or float calculation.
Write a program that calculate ‘VAT’
•Use this calculation [ taxed_price = price + ( 7% of price) ]
Rewrite them again with ‘input()’
•Rewrite all programs above with user’s input for [ w, h, b, price ]
9. 9
EX02 MATH CALC 2 DIVISION
Write a program ‘Does it Odd?’
•Get one user input and show that it is an odd number or not
•Note modulus (%) may be helpful
Write a program ‘FizzBuzz’
•Get one user input and consider if it can be divided by 3 or
5 or both without remainder.
10. 10
EX03 MATH CALC 3 PARENTHESIS, ORDER
Consider this expressions
•print( 100-2/3^5 )
•print( (100-2)/3^5 )
•print( 100-(2/3)^5 )
•print( 100-2/(3^5) )
What make them different?
11. 11
EX04 MATH CALC 4 ‘MATH MODULE’
Try this ‘math’ module by yourself
•math.pi
•math.pow()
•math.random()
Can you explain ‘random()’
12. 12
STRING
What you mostly use for human
communication and presentation
String in many senses; list, chars
and know how to transform them
13. 13
EX01 ASCII, UNICODE • CHAR, STRING
Do you know ‘ASCII’ or ‘Unicode’ Character Code?
•What’s saved in computer when your text has ‘ABCD’ inside?
•Note try to find which text encoding inside your PyCharm files.
Find out more about ‘ASCII’ and ‘Unicode’ tables
•Non-printable characters. [ n, r, t ]
‘Char’ acter and ‘String’
•String made from characters.
14. 14
EX02 STRING OPERATOR
What’s possible to calculate with ‘string’?
•‘concatenate’ or ‘plus’
•‘in’ & ‘not’
•‘multiply’ ? Really?
•len()
•upcase(), lowcase()
‘slice’ is BIGGGGGGGG
•REMEMBER THIS!! [ string[start:stop:step] ]string[start:stop:step]
‘slice’ is BIGGGGGGGG
15. 15
EX03 STRING FORMAT
It’s better to use .format() than multiple plus operators
•‘The {} brown fox jumped over the lazy dog’.format(‘quick’)
•‘Only {0} lived for others is {0} {1}’.format(‘a life’,’worthwhile’}
•# - Albert Einstein
•‘Hi {name}, an announcement has been made from {teacher}, instructor
of {course} and 2 more courses.’
.format(
name=‘Worajedt’,
teacher=‘Holczer’,
course=‘Advanced Algorithms in Java, Data Structures in Java’
)
16. 16
EX04 STRING FORMAT USE CASE
•Can you create a program to print this medication label?
•Note : Use keywords to be placeholders instead of numeric
index
17. 17
SYSTEM THEORY
Do you ever heard of..
Input-Process-Output or..
Garbage in, garbage out?
Learn more
Learn more
19. 19
EX01 GRADING FUNCTION
Write a program that return grade from input score
•Grades are :
• Grade Score Range
A >= 80
B 70 - 79
C 60 - 69
D 50 = 59
F < 50
20. 20
CONDITION
When we have information,
it let us ‘make decision’.
If-else, if-elif-else and
boolean algebra come in.
21. 21
EX01 GRADING REVISIT
Enhance your grading system again with if-elif-else
•Is it a number ?
•Is it within range 0 - 100 ?
•Make your code readable
•Wrap main idea within
•if __name__ == ‘__main__’:
• xxxxx
• xxxxx
22. 22
EX02 FIZZBUZZ APP REVISIT
Enhance your FizzBuzz again with if-elif-else
•Is it a number ?
•Is it within range 0 - 100 ?
•Wrap the main logic within check_fizzbuxz()
•Make your code readable
•Wrap main idea within
•if __name__ == ‘__main__’:
• xxxxx
• xxxxx
23. 23
Information can hold in a variable. But a variable can
hold more than one information. Ordered or
Unordered.
Set, Tuple, List and Dictionary.
All of these come with different kind of
parenthesizes.
COMPLEX DATATYPES
24. 24
EX01 CREATE LIST VS TUPLELIST
What’s the different between ‘tuple’ and ‘list’ ?
•Tuple is Read Only & faster
•Both are ‘array’
•Both are ‘ordered list’
•Both are ‘zero-based index’
tp = (1,5,7,9) # create a tuple
li = [1,5,7,9] # create a list
25. 25
EX02 MODIFY LIST
List can be modified, so these are ways you can do with a list.
•Find size of list
•Pull data from each list
•Add more member(element)
•Remove member (one by one)
•Reverse all members
•Count a selected member
•Find index(position) of a member
•Find if list has this member
LIST
26. 26
EX03 OPERATIONS
We can use some operations, check it out.
•Combine lists ( and tuple! )
•Unpack members to variables
LIST
27. 27
EX04 SLICE
List has one thing you must practice, slicing the list
LIST
list[start:stop:step]
0 1 2 3 4 5 6 7 8
B U T T E R F L Y
-9 -8 -7 -6 -5 -4 -3 -2 -1
28. 28
EX05 LIST COMPREHENSION
List Comprehension helps you define members with condition(s)
•Create a list consists of members in a condition
•You can use condition to create members
•And map() object to help you modified members
•Also, you can use this comprehension with ‘tuple’
LIST
29. 29
EX06 LIST OF LISTS (2D ARRAY)
Just a simple rules, list can have any types of its member. Even list.
•Try to create a simple data made from list of lists
•How can we replace the red location?
LIST
two_d_li = [
[1,3,5,7],
[2,4,6,8],
[5,0,5,0]
]
30. 30
EX01 CREATE DICT
Unordered list of data that comes with pair of {key:value}
•They are paired { “key”: value }
•No ordered
•Access by ‘key’
•Can get a list of keys and a list of values
DICTIONARY
31. 31
EX02 MODIFY DICT
Dictionary can do mostly list can
•You can find if the key exists
•And avoid error with .get()
•Update value and append value
DICTIONARY
32. 32
EX01 COMMON STRUCTURE
The most important and common structure of ‘database’
•1 Root key (option)
•Array (list) at root level
•Consists of dictionary (same structure) as the list members
Database query result, JSON API result are the most common format like this.
LIST OF DICTIONARY
33. 33
EX02 CREATE A JSON DATA
Learn how to create a JSON data
•What’s JSON?
•Try to create a JSON data from your experience
LIST OF DICTIONARY
34. 34
FOR LOOP
Bunch of information may require the
same set of instructions on them.
For-loops have many ways to deal
with each kind of data types.
35. 35
EX01 FOR LOOP WITH COUNTER
‘for in’ LIST
If we deal with ‘ordered list’ , we can use ‘for in’
•for animal in ["dog", "cat", "mouse"]:
•for i in range(4):
•list = ["dog", "cat", "mouse"]
•for i, value in enumerate(list):
• print(i, value)
•x = 0
•while x < 4:
• print(x)
• x += 1 # or x = x+1
36. 36
EX02 FOR + IF ELSE FIZZBUZZ REVISIT
‘for in’ LIST
Can you modify your FizzBuzz?
•Create a list of number, may be from range()
•Then apply fizzbuzz() for every items
•Print the output
37. 37
EX01 FOOTBALL PLAYERS
‘for each’ DICT
Actually, there is NO ‘for each’ in Python.
•a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
•new_dict = {}
•for key, value in a_dict.items():
• new_dict[value] = key
•print(new_dict)
•Now create a dict of football players and iterates over them.
38. 38
EX02 FOR + IF ELSE
‘for each’ DICT
You can apply condition to each loop
From the dict of football players, now iterates over them,
only who are older than 30 yrs
39. 39
EX01-10 : CONTINUOUS EXERCISES
RUNNERS
Use the exercises 01-10 about runners,
complete them all!
40. 40
PYCHARM IDE
Do you really know how to use
PyCharm IDE?
I bet you’re not. Not even close.
41. 41
CODING THE RIGHT WAY
Design how your program should work.
•Start from main()
•Write something readable and not too complex
•Create pseudo function and variable then refactor to real one
•Alt+Enter | Opt+Return is god send!
•Migrate each of them to the right files/modules
•Alt+Enter | Opt+Return is god send!
42. 42
TEXT EDITING
To learn a good text editor, learn about this
•Cursor movements
•Multi-Cursor
•Column Selection Mode
•Find and Replace
•Regular-Expression ( an alien language that save your @$$)
44. 44
RUNNING & DEBUGGING
In PyCharm you can set many running configurations.
•(Watch the demo in class)
PyCharm debug features is much more readable, let’s do it!
•(Watch the demo in class)
45. 45
Do you know when your code works?
How you measure it?
Are you sure your measure tool working correctly?
If you’re sure, how long it can be working properly?
TDD techniques and testing frameworks help you sleep
better.
TEST DRIVEN DEVELOPMENT
(TDD)
46. 46
WHAT IS TDD?
• Do you know when your code works?
• How you measure it?
• Are you sure your measure tool working
correctly?
• If you’re sure, how long it can be working
properly?
48. 48
‘pytest’
‘pytest’ is one of the best testing library in Python
• Almost no configuration
• Fast running
• Many extension, even BDD (Behavior-Driven Development)
• Integrate with PyCharm (Professional)
Time to demo !
51. 51
WORKSHOP 02 TDD :
FIND THE RIGHT EAN13 BARCODE CHECK DIGIT
https://www.gs1.org/services/how-calculate-check-digit-manually
The following table gives an example to illustrate how a GTIN-13 Check Digit is calculated:
55. 55
FILE
Any of you have never worked with file?
Since you are all have worked with
it. You better know how to work
with it correctly.
None
56. 56
FILE MODES IN PYTHON
FILE
Mode Description
‘r’ This is the default mode. It Opens file for reading.
‘w’
This Mode Opens file for writing. If file does not exist, it creates a new
file. If file exists it truncates the file.
‘x’ Creates a new file. If file already exists, the operation fails.
‘a’
Open file in append mode.
If file does not exist, it creates a new file.
’t’ This is the default mode. It opens in text mode.
‘b’ This opens in binary mode.
‘+’ This will open a file for reading and writing (updating)
57. 57
EX01 OPEN AND READ A FILE
FILE
Python use concept of open and close file like we had in C, Java
• 1) Open the file in Read mode with open()
• 2) We use the mode function in the code to check that the file is
in open mode. If yes, we proceed ahead
• 3) Use f.read() or f.readline() to read file data and store it in
variable content
• 4) print contents
58. 58
EX02 WRITE A FILE CONTENT
FILE
Python use concept of open and close file like we had in C, Java
• 1) Open the file in Write/Append mode with open()
• 2) Create some content and f.write(‘content inside’)
• 3) Use f.close() to close the file (save)
• 4) To Append, process is the same except open() with ‘a+'
59. 59
EX03 READ / WRITE THE MODERN WAY
FILE
Python 3 can use ‘with’ block to read/write file
# Writing to a file
contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents)) # writes an object to a file
# Reading from a file
with open('myfile1.txt', "r+") as file:
contents = file.read() # reads a string from a file
print(contents)
# print: {"aa": 12, "bb": 21}
60. 60
CSV FILE
When we process something, data input or
output may be any formats. CSV is one of the
primitive data since the early age of computer.
And it still very important in this Big
Data Era.
61. 61
EX01 READ CSVCSV
Programming language Designed by Appeared Extension
Python Guido van Rossum 1991 .py
Java James Gosling 1995 .java
C++ Bjarne Stroustrup 1983 .cpp
• 1) import csv
• 2) Open the file in ‘rt' mode with open()
• 3) Use csv.reader() to read the file by Row
• 4) Use csv.DictReader() to read each row, column as Dictionary
62. 62
EX02 WRITE CSVCSV
• 1) import csv
• 2) Open the file in Write/Append mode with open()
• 3) Use writer = csv.writer(file, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
• 4) writer.writerow(['Programming language', 'Designed by', 'Appeared',
'Extension'])
63. 63
DATABASE
While working with CSV is pretty easy. It’s still very basic in
terms of relationship and connection between each other
entities.
Relational Database Management System (RMDB) and
Structured Query Language (SQL) seems like the
backbone of data management system.
“No matter what it takes. Learn it, you must.”
– Master Yoda
64. 64
BASIC OF RELATIONAL DATABASE Definitions
• Database
• Table
• Field (Column)
• Record (Row)
• Primary Key (PK)
• Foreign Key (FK)
• One to Many
• Many to Many
65. 65
SNIPPETS
Learn How To Create Snippets
To Save Your Time
Of programmers don’t
know How to Create
Snippets.
Is the time you may save writing
code/fix spelling/pull your hair
by using Snippets.
90%
30%
66. 66
SQL LANGUAGE WITH SQLITE
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.close()
67. 67
SQL LANGUAGE WITH SQLITE (CONT)
. . . . .
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.close()
if __name__ == '__main__':
create_connection(r"C:sqlitedbpythonsqlite.db")
68. 68
EX01 MANIPULATE TABLE
-- tasks table
-- sql_create_tasks_table =
CREATE TABLE IF NOT EXISTS tasks (
id integer PRIMARY KEY,
name text NOT NULL,
priority integer,
project_id integer NOT NULL,
status_id integer NOT NULL,
begin_date text NOT NULL,
end_date text NOT NULL,
FOREIGN KEY (project_id)
REFERENCES projects (id)
);
-- projects table
-- sql_create_projects_table =
CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
);
69. 69
EX01 MANIPULATE TABLE (CONT)
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
70. 70
EX01 MANIPULATE TABLE (CONT)
def main():
database = r"C:sqlitedbpythonsqlite.db"
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects (
sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (
# create a database connection
conn = create_connection(database)
# create tables
if conn is not None:
# create projects table
create_table(conn, sql_create_projects_table)
# create tasks table
create_table(conn, sql_create_tasks_table)
else:
print("Error! cannot create the database connection.")
71. 71
EX02 SELECT DATA
def select_all_tasks(conn):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM tasks")
rows = cur.fetchall()
for row in rows:
print(row)
72. 72
EX02 SELECT DATA (CONT)
def select_task_by_priority(conn, priority):
"""
Query tasks by priority
:param conn: the Connection object
:param priority:
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM tasks WHERE priority=?", (priority,))
rows = cur.fetchall()
for row in rows:
print(row)
73. 73
EX03 INSERT DATA
def create_task(conn, task):
"""
Create a new task
:param conn:
:param task:
:return:
"""
sql = ''' INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date)
VALUES(?,?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, task)
return cur.lastrowid
74. 74
EX03 INSERT DATA (CONT)
def main():
database = r"C:sqlitedbpythonsqlite.db"
# create a database connection
conn = create_connection(database)
with conn:
# create a new project
project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30');
project_id = create_project(conn, project)
# tasks
task_1 = ('Analyze the requirements of the app', 1, 1, project_id,
'2015-01-01', '2015-01-02')
task_2 = ('Confirm with user about the top requirements', 1, 1, project_id,
'2015-01-03', '2015-01-05')
# create tasks
create_task(conn, task_1)
create_task(conn, task_2)
75. 75
EX04 UPDATE DATA
def update_task(conn, task):
"""
update priority, begin_date, and end date of a task
:param conn:
:param task:
:return: project id
"""
sql = ''' UPDATE tasks
SET priority = ? ,
begin_date = ? ,
end_date = ?
WHERE id = ?'''
cur = conn.cursor()
cur.execute(sql, task)
conn.commit()
76. 76
EX04 UPDATE DATA (CONT)
def main():
database = r"C:sqlitedbpythonsqlite.db"
# create a database connection
conn = create_connection(database)
with conn:
update_task(conn, (2, '2015-01-04', '2015-01-06', 2))
77. 77
EX05 DELETE DATA
def delete_task(conn, id):
"""
Delete a task by task id
:param conn: Connection to the
SQLite database
:param id: id of the task
:return:
"""
sql = 'DELETE FROM tasks WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id,))
conn.commit()
def main():
database = r"C:sqlitedbpythonsqlite.db"
# create a database connection
conn = create_connection(database)
with conn:
delete_task(conn, 2);
# delete_all_tasks(conn);