Download as pdf or txt
Download as pdf or txt
You are on page 1of 172

Python2

 Python 2 အေႀကာင္း ဘာသာျ ပန္ note ေတြ


 အေႀကာင္းအအရာ ၄၀ ေက ာ္
 စာမ က္ႏွာာ ၁၆၀ ေက ာ္ ပန္န္႔

Raw Version translated by Han Phyo Oo


Contents
Chapter 1................................................................................................................................................. 3

Chapter 2................................................................................................................................................. 4

Chapter 3................................................................................................................................................. 6

Chapter 4............................................................................................................................................... 10

Chapter 5............................................................................................................................................... 12

Chapter 6............................................................................................................................................... 17

Chapter 7............................................................................................................................................... 18

Chapter 8............................................................................................................................................... 25

Chapter 9............................................................................................................................................... 26

Chapter 10............................................................................................................................................. 28

Chapter 11............................................................................................................................................. 30

Chapter 12............................................................................................................................................. 33

Chapter 13............................................................................................................................................. 36

Chapter 14............................................................................................................................................. 45

Chapter 15............................................................................................................................................. 46

Chapter 16............................................................................................................................................. 52

Chapter 17............................................................................................................................................. 57

Chapter 18............................................................................................................................................. 63

Chapter 19............................................................................................................................................. 65

Chapter 20............................................................................................................................................. 68

Chapter 21............................................................................................................................................. 75

Chapter 22............................................................................................................................................. 88

Chapter 23............................................................................................................................................. 91

Chapter 24............................................................................................................................................. 97

Chapter 25............................................................................................................................................. 99

Chapter 26........................................................................................................................................... 101

Chapter 27........................................................................................................................................... 105

Chapter 28........................................................................................................................................... 110

Python2(ဘာသာျ ပန္) Han Phyo Oo 1


Chapter 29........................................................................................................................................... 120

Chapter 30........................................................................................................................................... 125

Chapter 31........................................................................................................................................... 128

Chapter 32........................................................................................................................................... 131

Chapter 33........................................................................................................................................... 135

Chapter 34........................................................................................................................................... 140

Chapter 35........................................................................................................................................... 149

Chapter 36........................................................................................................................................... 152

Chapter 37........................................................................................................................................... 154

Chapter 38........................................................................................................................................... 158

Chapter 39........................................................................................................................................... 162

Chapter 40........................................................................................................................................... 165

Chapter 41........................................................................................................................................... 169

Python2(ဘာသာျ ပန္) Han Phyo Oo 2


Chapter 1
Introduction

Python ကိုေျ ာအရင္ ABC programming language ကေပနစေျ ာအရ ပမမ္္။ ဘာလိုန္႔လဆ
ဲ ိုေတာာ့
python design က ABC အရဲာ့လႊမ္းမိုးမမေတြ ပေပနလိုာ့ျ စ္ ပတမ္္။

Python ကို 1980 ေလာက္မာ concept တစ္ ိုအေပနပနဲာ့ေတာာ့အရေပန ပျ ါ္။ Guido van Rossum
ကအဲာ့ဒါအ ပန္တိုပန္းက CWI မာအရတဲာ့ Amoeba လိုာ့ေ ခတဲာ့ distributed operation system Project
တစ္ ိုမာ လို ္ကိုင္ေပန ပတမ္္။ ABC ပနဲန္႔ေအရးတာ ပ္။ Bill Venners (January 2003) ပနဲာ့
အင္တာဗ းမာ Guido van Rossum က “ ABC ပနဲန္႔ တ္သက္ျ းါ အေတြန္႔အႀကံဳေေတြ
မအရင္းလင္းတာေတြအရတမ္ဗ ္။ ဒပေႀကာင္ာ့ ABC အရဲာ့ ေကာင္းတဲအ
ာ့ က္ေတြကို ABC အရဲာ့ ျ ပနာေတြ
မအရ ဲ အသံိုးျ ဳေပနင္
ို မမ္ာ့ scripting language တစ္ ို ဒါဇင
ို း္ လို ္ န္႔ဆ
ို ိုးံ ျ တ္ ားတမ္္။ စ
ို ေအရးေပနျ ္။ါ
Virtual Machine အရးို အရးို ေလးတစ္ အရ
ို မ္ parser တစ္ အရ
ို မ္ run time တစ္ အရ
ို မ္ လို ္ ားတမ္္။
ABC က
ဲ ကၽြပနေ
္ တာ္ႀကက
ို တ
္ ာ့ဲ အ က္ေတြကို ကၽြပနေ
္ တာာ့ ပနည္း ကၽြပနေ
္ တာာ့ ဟပန္ေအရး ားတမ္္။
syntax အရးို အရးို ေလးေတြသိုးံ တမ္္။ statement ေတြ group န္႔ြဲ န္႔ို တြပနန္႔က
္ င
ြ း္ ေတြ begin-end block
ေတြအစား identation သံိုး ားတမ္ ျ းါ ေတာာ့ data type ေကာင္းတာေလးေတြလို ္ ားတမ္ a
hash table ( or dictionary, as we call it), a list, strings, and numbers.”

ဒပဆို pythonဆိုတဲာ့ပနာမည္ကေအရာ….? ေျမြလိုန္႔ င္ႀကေ မမ္ာ့ အမပန္ေတာာ့ British


ဟာသပနဲာ့ဆိုင္ ပတမ္္။ “Guido van Rossum က ၁၉၉၆ မာ ေျ ာျ ားတမ္ “
လြပန္ ဲာ့တဲာ့ေျ ာက္ပနစ္ေလာက္ ဒါဇင္ဘာ 1989မာ ကၽြပန္ေတာ္ က အရစ္စမတ္ သတင္း တ္မာ
စြစ
ဲ ြျဲ မဲျမဲေလးလို ္မမ္ာ့ hobby programming project ေလးအရာေပနတာ ္။ အရံိုးကလည္း တ္
…အမ္မာလည္း ကြပန္ ်ဴတာအရေတာာ့ လို ္စအရာလညး္သ ္မအရဘးေလ ္။ ဒပေႀကာင္ာ့
အအရင္တိုပန္းကစစ္းစား ားတဲာ့ scripting language အသစ္အတြက္ Interpreter ေလးေအရးမမ္
လိုန္႔ဆံိုးျ တ္လို္က္တမ္္။ UNIX/ C hacker ေတြအႀကိုက္ ABC ေပနာက္မ ဳေးဆက္ေ ပာ့္။ project ကို
python လိုန္႔ပနာမည္ ေ းလက
ို ္တမ္္။ လကလည္း ပနည္းပနည္းေ ပာ့ ျ ါးေတာာ့ Monty Python's Flying
Circus အ ြန္႔အရ
ဲ ဲာ့ fan တစ္ေမာက္ျ စ္ေပနတာလည္း ပ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 3


Chapter 2
Why Python?

ဘာလိုန္႔လဆ
ဲ ိုေတာာ့အမ ားႀကါး ပ ္။သင္အရတာလြမ္တမ္ powerfull ျ စ္တမ္္။ ျ ါးေတာာ့ ေကာ
ေကာင္းမြပန္တဲန္႔ hight-level datastructure ေတြအရတမ္္။ဒပေတြသံိုးျ ါး အရို ္ေ ြးတဲာ့ လို ္ငပန္းေတြကို
c,c++,java တိုန္႔ က္ပနည္းတဲာ့statement ေတြပနဲန္႔ေအရးပနင္တမ္္။ OOP သံိုးအရာမာလည္း java
က္လမ
ြ ္ တမ္္။
အရင္းလင္းျ ါး တ္အရတာလည္းလြမ္တမ္္။ general-purpose high-level programming
language တစ္ ိုလည္းျ စ္တမ္္။ OOP / Imperative/ fuctional style ေတြေအရးလိုန္႔အရတမ္္။
ဘမ္ platform မာ ဲျ စ္ျ စ္ run လိုန္႔အရတဲာ့အတြက္ portable ျ စ္တမ္္။

David Beazley က“ေျ ာစအရာေတြအမ ားႀကါးအရေ မဲာ့ အရိုးအရိုးေလးေျ ာအရအရင္ Python က


ေ ာ္စအရာေကာင္းျ ါး productive လည္းျ စ္ ပတမ္္။”

Guido van Rossum က Python ကို Netherlands က Research Institute for Mathematics
and Computer Science မာ စတင္ ဲာ့ ပတမ္္။ Python ကိုဘာေတြသေဘာက လဲလိုန္႔ Linux
jornal ကေမးျမပန္းအရာမာ “ င္အရားတဲာ့အ က္ကေတာာ့ က ပန
ြ ္ေတာ္programming style
ပနဲာ့အံကိုက္ ဗ
ဲ ္။ interpreter ပနဲာ့ interactive လို ္ေဆာင္ပနိုင္သလို စဆံိုးေအရးျ ါးလည္း ေ ပင္းစ
ေ ပင္းစ ္သံိုးပနိုင္လိုာ့ ေအရးအရတာ ျမပန္တမ္္။ တစ္ျ ားလေတြကလည္း ဒါအ က္က ို productive
ျ စ္ေစတမ္ေျ ာေကတမ္္။

Python ကို java perl အျ ား language မ ားပနင္ာ့ မစ္ႀကည္ာ့ျ င္း

University of Karlsruhe မ Prof. Lutz Prechelt က python ကို တစ္ျ ား language ေတြပနဲာ့
မစ္ျ ပတမ္္။ သန္႔ေျ ာတဲာ့အရလဒ္အက စ္း ်ဴ ္ကေတာာ့္။ “ run time ,memory consumption ,
source text length , comment density , program structure , reliability , လိုအ ္တဲာ့
effort အားလံိုး အမ ်ဴး အစား ၈၀ ေလာက္တည္ေဆာက္ႀကည္ာ့တာ့အ
ဲ ပ. String ေတြdictionary
search ေတြမာ scripting language(perl,python,rexx,tcl) ေတြက conventional language
(c,c++,java)ေတြ က္သာတမ္္။ runtime ပနဲာ့ memory consumption မာ java က္သာျ ါး
c,c++ ေလာက္ေတာာ့မဆိုး ပဘး္။ ေမဘမ ဆိုအရင္ language ေတြႀကားကြာျ ား က္ေတာာ့
သ ္မအရ ပဘး ္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 4


-တစ္ျ ားေကာင္းမြပန္တဲာ့အ က္မ ား

Python ကို embedding လို ္အရတာလြမ္ ပတမ္္။ c မာ အႀကာႀကါးေအရးအရမမ္ာ့ ဟာကို Python


သံိုးျ ါး ေအရးလအရ
ိုာ့ တာေ ပာ့္။ အဲာ့လို ဲ Pythonကို c ပနဲာ့ေအရး ားတဲာ့ Module ေတြ ည္ာ့လိုန္႔အရ ပတမ္္။
လို ္အရတဲာ့ အေႀကာင္းကေတာာ့ python ပနဲာ့ေအရးမမ္ာ့ဟာ c library အရျ ါးသားဆိုအရင္ေ ပာ့ ္။
ေပနာက္တစ္ က္ ကေတာာ့ ကို ကpythonမာ manage လို ္ပနိုင္တာ က္ ျမပန္ျမပန္ run
င္အရင္လည္း သံိုး ပတမ္္။

Python standard library မာ အသံိုး၀င္တာ့ဲ module ေတြအရျ ါးေတာာ့ Install


လို ္တာပနဲန္႔ ပျ ါးျ စ္ ပတမ္...္။ Python အတြက္ မျ စ္မေပနသသင္ာ့တာေတြသင္ျ ါးအရင္ေတာာ့ Python
standard library ေတြပနဲန္႔ အကၽြမ္းတ၀င္အရ ိုန္႔လို ပတမ္္။ဒပမ ဒါ library
ပနဲန္႔လြမ္လြမ္ေျ အရင္ပနိုင္တာ ေတြ ျ ဳေလို ္ပနိုင္မာျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 5


Chapter 3
Python installation

Python ကို platform အေတာ္မ ားမ ားအတြက္အရပနိုင္ ပတမ္ Linux and Mac OS X
အ ပအ၀င္ေ ပာ့္။ Enviromental setup လို ္ႀကည္ာ့အရေအာင္္။

Verision 2.7 ကိုသံိုး ပမမ္္။ window ကို အ


ဲ ဓက ားေျ ာ ပမမ္္။(window သံိုးေပနလိုာ့ ပ)

Local Environment Setup

Python အရမအရသ င္အရင္ အရအရင္လည္း version သအရေအာင္ terminal/cmd မာ python


လိုန္႔အရိုက္ႀကည္ာ့ ပ္။

Getting python

ေပနာက္ဆံိုး က
ြ ္ Python version ေတြ document ေတြဆိုင္အရာအားလံိုးကို
https://www.python.org/ မာ အရပနင္ ပတမ္္။

Installating python

Platform ေတြအမ ားႀကါးမိုန္႔ မမပနဲန္႔ဆိုင္အရာ Platform binary code application ကိုအရမျ ါး Install
ျ ဳေလို ္ေ းအရ ပမမ္္။

Unix and Linux Installation

1. Web browser ြင္ာ့ျ ါး https://www.python.org/downloads/ ကိုသြား ပ


2. Unix/Linux ပနဲာ့ဆိုင္အရာ source code downy ပ္။
3. Download and extract files.
4. Editing the Modules/Setup file if you want to customize some options.
5. run ./configure script
6. make
7. make install

ဒပဆိုအရင္ /usr/local/bin မာ python ကို ည္ာ့သင


ြ ္းမာျ စ္ျ ါး /usr/local/lib/pythonXX မာ python
library ေတြ ည္ာ့သြင္းမာျ စ္ ပတမ္္။ XX ကေတာာ့ version no ကိုေျ ာတာ ပ္။

Windows Installation

Window အတြက္ဆိုအရင္ေတာာ့

1. Web browser ြင္ာ့ျ ါး https://www.python.org/downloads/ ကိုသြား ပ

Python2(ဘာသာျ ပန္) Han Phyo Oo 6


2. Windows installer python-XYZ.msi file ကိုအရာ ပ XYZ က version ကိုေျ ာတာ ပ
3. python-XYZ.msi ကိုအသံိုးျ ဳေ ပနင္ေအာင္ Windows system က support Microsoft
Installer 2.0 ကို support ေ းအရ ပမမ္္။
4. Downlod လို ္ ားတဲာ့ file ကို run ပ သန္႔ default အတိုင္း ဲ next ok စတာေတြ ဲ
ပန ္သာြ း ပအဆင္ေျ ပတမ္္။

Setting up PATH(optional)

Program ေတြ executable file ေတြက directory အျမားအျ ား မ


ဲ ာ အရတဲာ့အတြက္ OS က
executable file ေတြအရာ ိုန္႔ search path ေတြ မ
ဲ ာ executable ေတြအရာ ိုန္႔ directory list
ေတြ ည္ာ့ ား ပတမ္္။

Path ကို Environmental variable မ


ဲ ာသမ္း ား ပတမ္္။ OS မ
ဲ ာသမ္း ားတဲာ့ string
တစ္ ို ပ္။ ဒါ variable မ
ဲ ာ commeand shell ေတြအျ ား program ေတြကေပန
အရမအသံိုးျ ဳေပနိုင္တာ့ဲ information ေတြအရ ပတမ္္။

Path variable ကို unix မာ PATH window မာ Path လိုာ့ေ ခ ပတမ္.(Unix က case sensitive
window ကေတာာ့ case insensitive)

Setting path at Windows(optional)

At the command prompt − type path %path%;C:\Python and press Enter.

Python Environment Variables

Python ကေပနသတဲာ့ Environemental variable ေတြအရ ပတမ္္။

PYTHONPATH- Path ပနဲန္႔တ ပတမ္္။ python program က


ဲ ို import လို ္လိုက္တဲာ့ module
ေတြ အရာ ိုန္႔ေပနအရာေျ ာျ ေ း ပတမ္္။ Python source code directory ပနဲာ့ python source code
ေတြ ပတဲာ့ directory ေတြ ပသင္ာ့ ပတမ္္။ PYTHONPATH ကို python installer
ကေပနသတ္မတ္ေ း ားတာ လည္းျ စ္ေပနပနိုင္ ပတမ္္။

PYTHONSTARTUP- Python source ပနဲန္႔ တ္သတ္တာ့ဲ initialization file


ေတြအရတဲာ့ေပနအရာ ပ ပတမ္္။ interpreter စတိုင္ run ပတမ္္။ .pythonrc.py လိုာ့ Unix
မာပနာမည္ေ း ားျ ါး utilities loading လို ္တဲာ့ commandေတြ PYTHONPATH ကျ င္တာ့ဲ
command ေတြ ပ ပတမ္္။

PYTHONCASEOK- window မာ import statement ေတြမာ case-insensitve match ေတြအရာ ိုာ့


python ကိုညႊပန္ႀကားအရင္သံိုး ပတမ္္။ activate လို ္ ိုန္႔ႏွာစ္သက္အရာတပန္ ိုး ည္ာ့ပနိုင္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 7


PYTHONHOME-module path ေတြအရာ ိုန္႔ေပနာက္တစ္ေပနအရာျ စ္ ပတမ္္။ ံိုမပန္ေတာာ့
PYTHONSTARTUP သိုန္႔ PYTHONPATH directory မ
ဲ ာ ည္ာ့ ားျ ါး module library
ေတြေျ ာင္းအရလြမ္ေအာင္လို ္ ား ပတမ္္။

Running Python

Python ကိုပနည္းလမ္းသံိုးမ ဳေးပနဲာ့စတင္ပနိုင္ runပနိုင္ ပတမ္္။

Interactive Interpreter

Command line မ
ဲ ာ python လိုန္႔အရိုက္ျ ါး enter ႏွာ ္ ပ္။ ဒပဆို စေအရးလန္႔အရ
ို ပျ ါ္။

S.No. Option & Description


-d
1
It provides debug output.
-O
2
It generates optimized bytecode (resulting in .pyo files).
-S
3
Do not run import site to look for Python paths on startup.
-v
4
verbose output (detailed trace on import statements).
-X
5
disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6.
-c cmd
6
run Python script sent in as cmd string
file
7
run Python script from given file

Script from the Command-line

Python2(ဘာသာျ ပန္) Han Phyo Oo 8


Command line ကေပန python file ကိုေ ချ ါးလည္း run ပနိုင္ ပတမ္္။
C: >python script.py

Integrated Development Environment

Python ကို GUI ပနဲန္႔လည္းသံိုးပနိုင္ ပတမ္္။

Windows – Window မာ window key ႏွာ ္ search မာ IDLE လိုန္႔အလြမ္အရာပနိုင္ ပတမ္္။

Unix − IDLE is the very first Unix IDE for Python.

Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.

Python2(ဘာသာျ ပန္) Han Phyo Oo 9


Chapter 4
Using the Python Interpreter

Python interpreter သံိုး ိုန္႔ဆိုအရင္ command prompt မာ python လိုန္႔ enter ႏွာ ္အရင္အရ ပျ ါ္။

C:\Users\minthargyi>PYTHON

ဒပဆိုအရင္ python ကေပနေအာက္ ပအတိုင္းျ ပန္ျ ပလမ္ာ့မမ္္။

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC


v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>>

Interpreter စျ ါးအရင္ python command ေတြကို “>>>” အေပနာက္မာ စတင္ေအရးလိုန္႔အရ ပျ ါ


မဆံိုး ံိုးစံအတိုင္း “Hello World” ေလး print လို ္ႀကည္ာ့အရေအာင္
>>> print "Hello World"
Hello World
လြမ္ ပတမ္ေပနာ္ ိုလမ
ြ ္ င္အရင္ print မ ပ ေ
ဲ အရးလည္းအရ ပတမ္္။ interactive python
interpretor မာ print ေအရးစအရာမလို ပဘး
>>> "Hello World"
'Hello World'
>>> 3
3
>>>
ေ ပင္းႏွာမတ္ေျမာက္စား စတာေတြ လို ္ႀကည္ာ့ ပမမ္
>>> 12 / 7
1
အႀကြင္း 1 ပ
>>> 12.0 / 7
1.7142857142857142
Float ပအရင္ float တပန္ ိုး result ြက္ ပမမ္္။

Casting လို ္မမ္

>>> float(12) / 7
1.7142857142857142
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 10


Python မာလည္း operation order အရ ပတမ္္။

1. exponents and roots


2. multiplication and division
3. addition and subtraction

စ မာ “3+(2*4)” မာဆို () ည္ာ့စအရာေတာင္မလို ပဘး


>>> 3 + 2 * 4
11
>>>
ေပနာက္ဆံိုးတြက္ က္ ဲာ့တဲာ့အေျ ကို “_” ဆိုတဲန္႔ variable name မ
ဲ ာ
သမ္း ား ပတမ္္။သ င္အရင္ ေ ခလိုက္မံို ပ ဲ
>>> _
11
>>>
Underscore ကို တစ္ျ ား variable ေတြလို ဲ သံိုးပနိုင္ ပတမ္္။
>>> _ * 3
33
>>>
Interpreter ကို တ္ င္အရင္ CTRL+Z enter or exit() enter ပ္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 11


Chapter 5
Execute a Python script

Interavtive interpreter က coding ေသးေသးေလးေတြ script ေလးေတြအတြက္


အဆင္ေျ ေ မမ္ာ့ coding မ ားလာအရင္ အဆင္မေျ ပဘး အဲာ့ဒပေႀကာင္ာ့ code ေတြကို script file

ဲ ာ သမ္း ိုန္႔လို ပတမ္္။

ဒပဆို text editor တစ္ ိုလို ပမမ္္။ အမ ားႀကါးအရတဲာ့အ မ


ဲ syntax highlighting ပနဲန္႔ဲ identation
support ေ းတာဆိုအဆင္ေျ ပတမ္္။ Pycharm community edition ကို recommend
ေ း ပတမ္္။ https://www.jetbrains.com/pycharm/download/#section=windows

မမႏွာစ္သက္အရာ editor ပနဲန္႔ print “hello world” ေလးေအရး helloworld.py လိုန္႔ desktop
ေ ခမာသမ္း ေ း ပ အဓကကေတာာ့ .py extension ျ စ္အရမာျ စ္ျ ါး မမသမ္းဆည္း ားအရာေပနအရာကို
သအရအရမာျ စ္ ပတမ္္။

ေအာက္မာ cmd ပနဲာ့ run ျ ား ပတမ္္။


Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\minthargyi>cd Desktop

C:\Users\minthargyi\Desktop>python helloworld.py
hello world
C:\Users\minthargyi\Desktop>

Python Internals

Python ကို interpreted programming သိုန္႔ scripting language လိုန္႔ေျ ာႀက ပလမ္ာ့မမ္္။ အမပန္
တာာ့ Python က interpreted ျ စ္သလို compiled language လည္းျ စ္ ပတမ္္။ ဒပေ မမ္ာ့
compiled language လိုေျ ာအရင္ပနားလည္းမမလဲပန
ြ ိုင္ ပေသးတမ္္။ compiler က python code ကို
machine language ေျ ာင္းလိုက္တမ္လိုန္႔ျမင္ႀက ပလမ္ာ့မမ္္။ python code ကို intermediate
code အအရင္ေျ ာင္း ပတမ္္။ အဲာ့ဒပကိုမ PVM လိုာ့ေ ခတဲာ့ python virtual machine မာ execute
လို ္ ပတမ္္။ java ပနဲာ့တ ပတမ္္။ python ကို Jpython သံိုးျ ါး java byte code အျ စ္ေျ ာင္း
လိုန္႔အရတဲာ့ပနည္းေတြေတာင္ အရ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 12


ေမး ြပန္းက python code ေတြကို ျမပန္ဆပန္ေအာင္ compile လို ္အရမာလား or ဘမ္လို compile
လို ္မလဲ စတာေတြ ပ္။ အေျ ကေတာာ့ ဘာမလို ္စအရာမလို ပဘး python
ကလို ္ေ းေပနတာေႀကာင္ာ့ ပ္။

ကိုက manual လို ္ င္ ပတမ္ဆိုလည္းအရ ပတမ္္။ interpreter မ


ဲ ာ py_compile module
သံိုးျ ါးလို ္ပနိုင္ ပတမ္္။
>>> import py_compile
>>> py_compile.compile('easy_to_write.py')
>>>
Cmd မာလို ္ င္အရင္

python -m py_compile helloworld.py

ဘမ္လို လ
ဲ ို ္လို ္ “helloworld.pyc” ဆိုတဲာ့ file ေလးလို ္ေ း ပလမ္ာ့မမ္္။

Directory တစ္ ို ဲမာ အရေပနတဲာ့ python file အားလံိုးကို compile လို ္ င္လည္းအရ ပတမ္္။
python -m compileall .
ဒပေ မမ္ာ့ေျ ာ ဲာ့သလို ဲ user ကလို ္စအရာမလို ပဘး္။ python program file အရတဲာ့ directory မာ
write access အရအရင္ .pyc file ေတြသမ္းတတ္ ပတမ္္။ write access မအရလည္း အလို ္လို ္ေပနမာ
ပ ဲ ္။ byte code ို ္ျ ါး program အရ ္သာြ းအရင္ က္လိုက္မာ ပ္။ python program ကို execute
လို ္တိုင္း .pyc file အရလားအအရင္ႀကည္ာ့ ပတမ္္။ ိုျမပန္တာ့အ
ဲ တြက္ အဲာ့ဒါ file ကို load လို ္ေ းမာ ပ္။
မအရဘးဆိုအရင္ေတာာ့ byte code ို ္ျ ါး execute လို ္ ပတမ္္။ Execute လို ္တမ္ဆိုတာ byte
code ေတြကို Python Virtual Machine (PVM) ေ ခမာ run တာကိုဆိုလိုတာျ စ္ ပတမ္္။

Python script execution လို ္တိုင္း byte code ိုတ္တမ္္။ module အေပနပနဲာ့သံိုးအရင္လည္း
သက္ဆိုင္အရာ .pyc file မ
ဲ ာသမ္း ားတမ္္။

ေအာက္မာ desktop ဲက file list ပ္။

C:\Users\minthargyi>cd Desktop

C:\Users\minthargyi\Desktop>dir

Volume in drive C has no label.

Volume Serial Number is 1E04-AD6F

Directory of C:\Users\minthargyi\Desktop

09/08/2017 03:12 PM <DIR> .

Python2(ဘာသာျ ပန္) Han Phyo Oo 13


09/08/2017 03:12 PM <DIR> ..

09/08/2017 01:58 PM 28,184 A Note On Pyhton 2.docx

09/07/2017 07:17 PM 37,093 A Note On Pyhton 2.pdf

09/03/2017 11:05 AM 11 hello.py

09/08/2017 02:41 PM 19 helloworld.py

07/23/2017 05:54 PM <DIR> ngtest

4 File(s) 65,307 bytes

3 Dir(s) 64,989,577,216 bytes free

C:\Users\minthargyi\Desktop>

Helloworld ကို run ႀကည္ာ့ ပမမ္္။

C:\Users\minthargyi\Desktop>python helloworld.py

hello world

C:\Users\minthargyi\Desktop>dir

Volume in drive C has no label.

Volume Serial Number is 1E04-AD6F

Directory of C:\Users\minthargyi\Desktop

09/08/2017 03:12 PM <DIR> .

09/08/2017 03:12 PM <DIR> ..

09/08/2017 01:58 PM 28,184 A Note On Pyhton 2.docx

09/07/2017 07:17 PM 37,093 A Note On Pyhton 2.pdf

09/03/2017 11:05 AM 11 hello.py

09/08/2017 02:41 PM 19 helloworld.py

07/23/2017 05:54 PM <DIR> ngtest

4 File(s) 65,307 bytes

3 Dir(s) 64,990,224,384 bytes free

Python2(ဘာသာျ ပန္) Han Phyo Oo 14


C:\Users\minthargyi\Desktop>

.pyc file မေဆာက္ေ း ပဘး

ေပနာက္တစ္ပနည္းသြားႀကည္ာ့မမ္္။

C:\Users\minthargyi\Desktop>python

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit


(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import helloworld

hello world

>>> exit()

C:\Users\minthargyi\Desktop>dir

Volume in drive C has no label.

Volume Serial Number is 1E04-AD6F

Directory of C:\Users\minthargyi\Desktop

09/08/2017 03:16 PM <DIR> .

09/08/2017 03:16 PM <DIR> ..

09/08/2017 01:58 PM 28,184 A Note On Pyhton 2.docx

09/07/2017 07:17 PM 37,093 A Note On Pyhton 2.pdf

09/03/2017 11:05 AM 11 hello.py

09/08/2017 02:41 PM 19 helloworld.py

09/08/2017 03:16 PM 121 helloworld.pyc

07/23/2017 05:54 PM <DIR> ngtest

5 File(s) 65,428 bytes

3 Dir(s) 64,998,924,288 bytes free

C:\Users\minthargyi\Desktop>

.pyc file ပလာတာသတျ ဳေမ ပလမ္ာ့မမ္ာ့

Python2(ဘာသာျ ပန္) Han Phyo Oo 15


Compiler

Compiler ကေတာာ့ programmng language တစ္ ိုကေပန အျ ားတစ္ ိုကိုေျ ာင္း


လဲေ း ပတမ္္။ source code ကေပန executable program အျ စ္ေျ ာင္းတာ
အျ စ္သံိုးႀက ပတမ္္။ hight level language(human readable ) to low level
language(machine language)

Interpreter

Programming language တစ္ ို ိုပနဲာ့ေအရး ားတဲာ့ instruction ေတြကို execute လို ္ ပတမ္္။

Source code ကို direct run တာျ စ္ပနိုင္သလို]

ိုေကာင္းတဲာ့ language တစ္ ိုအျ စ္ေျ ာင္းလဲျ ါးမ execute လို ္တာလည္းျ စ္ပနိုင္ ပတမ္္။

Help
help("execfile")

Python2(ဘာသာျ ပန္) Han Phyo Oo 16


Chapter 6
Structuring with Indentation

Programmng language ေတာ္ေတာ္မ ားမ ားမာ statement ေတြ group ြန္႔ဲ ိုာ့ character ေတြ
keyword ေတြသံိုးႀက ပတမ္္။

 begin ... end


 do ... done
 { ... }
 if ... fi

python မာ တစ္ျ ားပနည္းသံိုး ပတမ္္။ structre ကို identation (စကားလံိုးအကြာအေ၀း) သံ


သံိုးျ ါးေဆာက္ ပတမ္္။ identation တအရင္ block တတဲာ့သေဘာ ပ ဲ တစ္ျ ား language
ေတြမာ ဆိုအရင္ လေအာင္ တ္အရလြမ္ေအာင္ identation သံိုးႀကေ မမ္ာ့ python မကေတာာ့
language
လိုအ ္ က္အေပနပနဲာ့မျ စ္မေပနသံိုးေ းအရ ပမမ္္။ တ္အရပနားလည္အရလည္း ိုလြမ္ေစ ပတမ္္။

ညာဘက္ကေပန အကြာအေ၀းတ တဲာ့ statement ေတြအားလံိုး block တစ္ ို ဲမာအရ ပတမ္္။


ဆိုလိုတာကေတာာ့ block တစ္ ို ဲမာဆိုအရင္ အ က္ေအာက္စာလံိုးအစေတြညါေပန ပလမ္ာ့မမ္္။
indent လို ္တဲာ့ေပနာက္ဆံိုးလိုင္း သိုာ့ file အဆံိုးမာ block ဆံိုး ပတမ္္။ block မ
ဲ ာ ေပနာက္ ္
block ေတြ ္ ည္ာ့မမ္ဆိုလည္း ညာဘက္ကို indent ္လို ္ေ းမံို ပ ္။ဲ

တစ္ေႀကာင္းတည္းမေလာက္လိုာ့ ဆက္ေအရးမမ္ဆိုအဆံိုးမာ “\” ည္ာ့ေ းအရ ပမမ္္။

Eg

First block

Inerblock statement 1

Inerblock statement 2

Inerblock statement 3

Second block

Third block

Python2(ဘာသာျ ပန္) Han Phyo Oo 17


Chapter 7
Data Types and Variables

Python မာ powerfull ျ စ္တာ့ဲ data type ေတြ ပ၀င္တာ့အ


ဲ တြက္ေႀကာင္ာ့ ၎တိုန္႔ကို
သအရ ိုန္႔လို ပတမ္္။

Variables

Variable ကေတာာ့ ပနာမည္မာ ပသလို ဲ ေျ ာင္းလဲလိုန္႔အရဲာ့အအရာတစ္ ို ပ္။ computer memory မ


ဲ ာအရ
တဲန္႔ memory location တစ္ က
ို ိုညႊပန္း င္အရင္သံိုးတဲာ့ပနည္းလမ္းတစ္ ို ပ ဲ္။
တကမ္အရတဲာ့ေပနအရာအတြက္ အမတ္အသားေလးတစ္ ိုျ စ္ ပတမ္္။ memory location မာေတာာ့
တပန္ ိုးေတြျ စ္တာ့ဲ number,text, ပနဲာ့အျ ားအရမ ္ေ းြ တဲာ့ datatype ေတြ ပအရ ပတမ္္။

Variable ကို တပန္ ိုးေတြ သမ္း ား ိုာ့ ေပနအရာလြတ္ေလးေတြ container ေလးေတြလိုာ့ မတ္သားပနိုင္
ပတမ္္။ program run ေပန ပန္မာ တပန္ ိုးေတြအရမသံိုးစြပန
ဲ ိုင္သလို
တပန္ ိုးအသစ္ေတြ ေျ ာင္းလဲ ည္ာ့သြင္းပနိုင္ ပတမ္္။

Python ပနဲာ့အျ ား strong type language ေတြျ စ္တာ့ဲ c ,c++, java


ေတြပနဲာ့မတတဲာ့အ က္ကေတာာ့ types ေတြပနဲာ့အလို ္လို ္ ံိုကာြ တာျ စ္ ပတမ္္။ strong typed
language ေတြမာ variable ေတြက တက တဲာ့ data type တစ္ ိုအရအရ ပတမ္္။ Eg. Integer type
ဆိုအရင္ integer value ေတြ ဲသမ္းပနိုင္ ပတမ္္။ java ေအရာ c ေအရာ variable ေတြမသံိုး င္ အအရင္
ေႀကျငာ(declare)အရ ပတမ္္။ declare လို ္တမ္ဆိုတာက variable ပနဲာ့ datatype binding
လို ္တာျ စ္ ပတမ္္။

Python မာ ေတာာ့ variable declaration လို ္ ိုန္႔မလို ပဘး ္။ မမလိုတဲာ့အ ပန္ သံိုးအရိုံ ပ ဲ္။

ေပနာက္တစ္ က္က variable value ေျ ာင္းပနိုင္သလို variable data type ကိုလည္း program
run ေပန ပန္မာ ေျ ာင္းပနိုင္ ပတမ္္။ integer variable တစ္ ိုလို ္သံိုးေပနာက္လိုလာအရင္ ၎ကို
variable ကို string type အျ စ္ေျ ာင္းလဲသံိုးပနိုင္ ပတမ္္။ Eg.

>>> i=42

ဒါမာဆိုအရင္ variable i ကို 42 လိုန္႔သတ္မတ္လိုက္ ပတမ္္။ 1 ေ ပင္းႀကည္ာ့မမ္္။

>>> i=i+1
>>> print i
43
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 18


Variables vs. Identifiers

Variable ပနဲန္႔ identifier တတမ္လိုန္႔မားေျ ာႀက ပတမ္္။ အရင္းအရင္းေျ ာအရအရင္ variable အရဲန္႔ပနာမည္ ကို
identifier လိုန္႔ေ ခ ပတမ္္။ ဒပေ မမ္ာ့ variable ကအဲာ့ဒါ က္ ို ပတမ္္။ variable မာ
ပနာမည္အရမမ္္။ type အရမမ္္။ scope အရမမ္ value ေတြအရမမ္္။ ျ ါးေတာာ့ identifier ဆိုတာ
variable name အတြက္ မမဟိုတ္ ပဘး္။ အျ ား variables, types, labels, subroutines or
functions, packages စတာ ေတြအတြက္လည္းသံိုး ပေသးတမ္္။

Naming Identifiers of Variables

အျ ားprogramming language ေတြလို ဲ python မာလည္း rule ေတြအရ ပတမ္္။

Empty မဟိုတ္တာ့ဲ character sequence ေတြျ ါးေတာာ့

 "_" or a capital or lower case letter ပနဲ႕ဲ စပနိုင္တမ္္။


 အစစကားလံိုးျ ါးအရင္ ေပနာက္မာ အစစကားလံိုးမာ ြင္ာ့ျ ို ားတာေတြအျ င္ digit
ေတြ ပ ပပနိုင္ ပတမ္္။ .
 Window မာ ေတာာ့ case-sensitive ျ စ္ ပတမ္္။
 Python keywords ေတြကို သံိုးလိုန္႔မအရ ပဘး

Python Keywords

Identifier ေတြမာ Python keyword ေတြေ းလိုာ့မအရ ပဘး္။

and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for,
from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while,
with, yield

Changing Data Types and Storage Locations

အ က္မာေျ ာ ဲာ့သလို ဲ data type ေတြကို program execute


လို ္ေပန ပန္မာ ေျ ာင္းလဲပနင
ို ္ ပတမ္္။

>>> i=42
>>> i=42+0.11
>>> i="forty"
>>>

Physically ဘမ္လို ားမမ္ဆိုတာေတာာ့ python ကလို ္ေ းသြား ပတမ္္။ interger float


string စတာေတြကို ေပနအရာသ ္သ ္ဆါသမ္းေ း ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 19


Assignment လို ္တဲာ့အ ပဘာေတြျ စ္လဲ? ႀကည္န္႔အရေအာင္
>>> x = 3
>>> y = x
>>> y = 2
မ assignemet မာ ျ ပနာမအရဘး္။ x အတြက္ memory ေပနအရာတစ္ ို python
ကလို ္ေ းမမ္ ျ ါးေတာာ့ integer value 3 ကိုသမ္းလိုက္မမ္္။ ဒိုတမ မာက ေတာာ့ င္အရတာက
python က y အတြက္ memory location လို ္ျ ါး 3 ကို ကးျ ါး ည္ာ့လိုက္မမ္ လိုာ့
င္စအရာအရ ပတမ္္။ python မာ အဲာ့လိုမလို ္ ပဘး္။ value ေတြတတဲာ့အတြက္ေႀကာင္ာ့ Python က
y ကို x အရဲာ့ memory location ကို ည
ဲ ႊပန္းေ း ပတမ္္။

တတမ statement မာ ေမးစအရာေမး ြပန္းအရလာ ပျ ါ y ကို 2 လိုန္႔ ားလိုက္ ပတမ္္။ ဒပဆို x


ကဘာျ စ္သာြ းမလဲ C သမားေတြကေတာာ့ x လည္းေျ ာင္းသြားမမ္ေျ ာ ပလမ္ာ့မမ္္။ ဘာလိုန္႔လဲ
ဆိုေတာာ့ y က x အရဲာ့ memory location ကို ညႊပနး္ ားတမ္ေျ ာ ဲာ့တာကိုး္။ ဒပေ မမ္ာ့ ဒပက c
pointer မဟိုတ္ ပဘး ္။ x ပနဲံ y က value မတေတာာ့တာ့အ
ဲ တြက္ y လည္းသန္႔ကိုမ္ ိုင္ memory
location အရသြား ပတမ္္။ ဆိုေတာာ့ y က 2 x ကလည္း သာ့တပန္ ိုး 3 ပ ဲ္။

Identify function id() ပနဲန္႔ေသ ာေအာင္လို ္ႀကည္ာ့မမ္္။ instance (Object /variable )အားလံိုး
မာ identity အရ ပတမ္္။
>>> x = 3
>>> print id(x)
157379912
>>> y = x
>>> print id(y)
157379912
>>> y = 2
>>> print id(y)
157379924
>>> print id(x)
157379912
>>>

Numbers

Python အရဲာ့ built in data type ေတြကို object type လိုန္႔လည္းေ ခ ပေသးတမ္္။ number
အတြက္ 4 မ ဳေးအရ ပတမ္္။

 Integer
 Normal integers
e.g. 4321
 Octal literals (base 8)
A number prefixed by a 0 (zero) will be interpreted as an octal number
example:

Python2(ဘာသာျ ပန္) Han Phyo Oo 20


>>> a = 010
>>> print a
8 Alternatively, an octal number can be defined with "0o" as a prefix:
>>> a = 0o10
>>> print a
8
 Hexadecimal literals (base 16)
Hexadecimal literals have to be prefixed either by "0x" or "0X".
example:
>>> hex_number = 0xA0F
>>> print hex_number
2575
 Long integers
these numbers are of unlimited size
e.g.42000000000000000000L
 Floating-point numbers
for example: 42.11, 3.1415e-10
 Complex numbers
Complex numbers are written as <real part> + <imaginary part>j
examples:
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print z
(5+1j)

Strings

String ေတြကို quote “” ေလးေတြပနာ့မ


ဲ တ္ ပတမ္္။

 Wrapped with the single-quote ( ' ) character:


'This is a string with single quotes'
 Wrapped with the double-quote ( " ) character:
"Obama's dog is called Bo"
 Wrapped with three characters, using either single-quote or double-quote:
'''A String in triple quotes can extend
over multiple lines like this one, and can contain
'single' and "double" quotes.'''

Python string ေတြမာ characters , letters ,numbers, special characters


ေတြ ပ၀င္ ပတမ္္။ string ေတြကို index ပနဲသ
ာ့ ံိုးလိုန္႔လည္းအရ ပတမ္္။ c မာ လို ဲ မစလံို းက
index 0ပါ

>>> s = "A string consists of characters"

Python2(ဘာသာျ ပန္) Han Phyo Oo 21


>>> s[0]
'A'
>>> s[3]
't'

ေပနာက္ဆံိုးစာလံိုးကေတာာ့
>>> s[len(s)-1]
's'
ိုလမ
ြ ္တဲန္႔ပနည္းလမ္းက ေပနာက္ဆံိုး character ကို index -1 ဒိုတမကို -2 သံိုးပနိုင္ ပတမ္္။
>>> s[-1]
's'
>>> s[-2]
'r'
Python မာ character type မအရ ပဘး ၊ string size one ဆို character ပ ဲ

Index ေတြကို ညာ က္ကေအရတြက္ျ င္အရင္ -1 ကစ ပတမ္္။

String operators ေတြ function ေတြ

 Concatenation
Strings can be glued together (concatenated) with the + operator:
"Hello" + "World" will result in "HelloWorld"
 Repetition
String can be repeated or repeatedly concatenated with the asterisk operator "*":
"*-*" * 3 -> "*-**-**-*"
 Indexing
"Python"[0] will result in "P"
 Slicing
Substrings can be created with the slice or slicing notation, i.e. two indices in
square brackets separated by a colon:
"Python"[2:4] will result in "th"
 Size
len("Python") will result in 6

Python2(ဘာသာျ ပန္) Han Phyo Oo 22


Immutable Strings

Java ပနဲာ့တျ ါး C C++ ပနဲာ့မတတာက python string ေတြကို ေျ ာင္းလိုန္႔မအရ ပဘး္။ index postion
ေတြကို value ေျ ာင္းႀကည္ာ့အရင္ error ေ း ပလမ္ာ့မမ္္။
>>> s = "Some things are immutable!"
>>> s[-1] = "."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>

A String Peculiarity

String ေတြမာ းျ ား က္တစ္ ိုအရတမ္္။ eg/ “is” operator လို ပမမ္္။ a ပနဲန္႔ b က string
ေတြျ စ္တမ္ “a is b ” ဆိုအရင္ identity တမတစစ္တာျ စ္ ပတမ္(memory share
သံိုးႀကတမ္ေ ပာ့ )္။ “a is b” က True ဆိုအရင္ “a==b” လည္းတအရမာျ စ္ ပတမ္္။ ဒပေ မမ္ာ့
“a==b” ျ စ္မံိုပနာ့ေ
ဲ တာာ့ “a is b” က True မျ စ္ ပဘး္။ eg
>>> a = "Linux"
>>> b = "Linux"
>>> a is b
True
String အအရည္ဆိုအရင္ေအရာ ?
>>> a = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> b = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> a is b
True
အတတ ပ ဲ ိုျ မမ္ာ့ eg မာေတာာ့ မတေတာာ့ ပဘး
>>> a = "Baden-Württemberg"
>>> b = "Baden-Württemberg"
>>> a is b
False
>>> a == b
True
Special character hypen ပေပနလိုာ့ျ စ္ ပတမ္္။
>>> a = "Baden!"
>>> b = "Baden!"
>>> a is b
False
>>> a = "Baden1"
>>> b = "Baden1"
>>> a is b
True

Python2(ဘာသာျ ပန္) Han Phyo Oo 23


Escape Sequences

Escape Sequence Meaning Notes

\newline Ignored

\\ Backslash (\)

\' Single quote (')

\" Double quote (")

\a ASCII Bell (BEL)

\b ASCII Backspace (BS)

\f ASCII Formfeed (FF)

\n ASCII Linefeed (LF)

\N{name} Character named name in the Unicode database (Unicode only)

\r ASCII Carriage Return (CR)

\t ASCII Horizontal Tab (TAB)

\uxxxx Character with 16-bit hex value xxxx (Unicode only)

\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)

\v ASCII Vertical Tab (VT)

\ooo Character with octal value ooo

\xhh Character with hex value hh

Python2(ဘာသာျ ပန္) Han Phyo Oo 24


Chapter 8
Arithmetic and Comparison Operators

Operators

Operator Description Example


+, - Addition, Subtraction 10 -3
*, /, % Multiplication, Division, Modulo 27 % 7
Result: 6
// Truncation Division (also known as floordivision or >>> 10 // 3
floor division) 3 >>> 10.0 // 3
The result of this division is the integral part of the 3.0 >>>
result, i.e. the fractional part is truncated, if there is
any. If both the divident and the divisor are integers,
the result will be also an integer. If either the
divident or the divisor is a float, the result will be
the truncated result as a float.
+x, -x Unary minus and Unary plus (Algebraic signs) -3
~x Bitwise negation ~3 - 4
Result: -8
** Exponentiation 10 ** 3
Result: 1000
or, and, Boolean Or, Boolean And, Boolean Not (a or b) and c
not
in "Element of" 1 in [3, 2, 1]
<, <=, >, The usual comparison operators 2 <= 3
>=, !=, ==
|, &, ^ Bitwise Or, Bitwise And, Bitwise XOR 6^3
<<, >> Shift Operators 6 << 3

Python2(ဘာသာျ ပန္) Han Phyo Oo 25


Chapter 9
Input from Keyboard

Input Function

Python မာ keyboard ကေပန input မ ိုန္႔ input() function ပ ပတမ္္။ optional parameter
တစ္ ို ပျ ါးေတာာ့ prompt string ေလးတစ္ ိုျ ိုန္႔သံိုးပနိုင္ ပတမ္္။

Input function ကို ေ ခတဲာ့အ ပ program flow က user input မေ းမ င္းအရ ္ေပနမာ ပ္။
optional parameter ဲက string ကေတာာ့ screen မာေ ခေပနမာ ပ္။

ျ ါးေတာာ့ user input လို ္သမ ကို interpret လည္းလို ္မာ ပ္။ integer ဆိုအရင္ Integer ၊ list
ည္န္႔ အရင္ list return ျ ပန္ေ း ပတမ္္။
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + str(age) + " years old, " + name + "!")
“input_test.py” လိုန္႔သမ္းျ ါး runႀကည္ာ့ ပ္။
$ python input_test.py
What's your name? "Frank"
Nice to meet you Frank!
Your age? 30
So, you are already 30 years old, Frank!
တကမ္လိုန္႔ ကိုက name ညာ့္အရာမာ quotes ေတြက ပန္သြားအရင္ေတာာ့ error ျ ပလမ္ာ့မမ္္။
Traceback (most recent call last):
File "input_test.py", line 1, in <module>
name = input("What's your name? ")
File "<string>", line 1, in <module>
NameError: name 'Frank' is not defined
အစမာေျ ာ ဲာ့သလို ဲ input ကို interpret လို ္တဲာ့အတြက္ ေႀကာင္ာ့ quoutes မ ပအရင္ variable
အေပနပနဲာ့သတ္မတ္တာ့အ
ဲ တြက္ေႀကာင္ာ့ error ျ တာျ စ္ ပတမ္္။
>>> name = input("What's your name? ")
What's your name? "John"
>>>
>>> age = input("Your age? ")
Your age? 38
>>> print(age, type(age))
(38, <type 'int'>)
>>> colours = input("Your favourite colours? ")
Your favourite colours? ["red","green","blue"]
>>> print(colours)
['red', 'green', 'blue']
>>> print(colours, type(colours))
(['red', 'green', 'blue'], <type 'list'>)
>>>
Input with raw_input()

Python2(ဘာသာျ ပန္) Han Phyo Oo 26


Raw_input ကေတာာ့ interpret လို ္မေ း ပဘး္။ user ည္ာ့သမ အေျ ာင္းအလဲမအရ return
ျ ပန္ေ း ပတမ္္။ raw inpyt ကိုလည္း လိုအ ္သလို casting ေတြ eval function ေတြသံိုးျ ါး data
type ေျ ာင္းပနိုင္ ပတမ္္။
>>> age = raw_input("Your age? ")
Your age? 38
>>> print(age, type(age))
('38', <type 'str'>)
>>>
>>> age = int(raw_input("Your age? "))
Your age? 42
>>> print(age, type(age))
(42, <type 'int'>)
>>>
>>> programming_language = raw_input("Your favourite programming languages?
")
Your favourite programming languages? ["Python", "Lisp","C++"]
>>> print(programming_language, type(programming_language))
('["Python", "Lisp","C++"]', <type 'str'>)
>>>
>>> programming_language = eval(raw_input("Your favourite programming
languages? "))
Your favourite programming languages? ["Python", "Lisp","C++"]
>>> print(programming_language, type(programming_language))
(['Python', 'Lisp', 'C++'], <type 'list'>)
>>>
ဒပေ မမ္ာ့ list ကို casting လို ္အရင္ေတာာ့ ကၽြပန္ေတာ္တိုာ့ င္သလိုလို ္မာမဟိုတ္ ပဘး
>>> programming_language = list(raw_input("Your favourite programming
languages? "))
Your favourite programming languages? ["Python", "Lisp","C++"]
>>> print(programming_language, type(programming_language))
([' ', '[', '"', 'P', 'y', 't', 'h', 'o', 'n', '"', ',', ' ', '"', 'L',
'i', 's', 'p', '"', ',', '"', 'C', '+', '+', '"', ']'], <type 'list'>)
>>>
တစ္လံိုးျ င္းစါျ တ္ျ စ္တာေတြန္႔အရ ပလမ္ာ့မမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 27


Chapter 10
Conditional Statements

Programming language ေတြမာ conditional statement or conditional construct ေတြကို


အေျ အေပနတစ္ ိုေ ခမတည္ျ ါး တြက္ က္တာမ ဳေး ေတြလို ္အရင္သံိုး ပတမ္္။ python မာ True ပနဲာ့
False လန္႔ို ဲသံိုး ပတမ္္။

Condition ေတြစစ္တာ့အ
ဲ ပ variable ေတြ ကို comparison and arithmetic expression ေတြပနဲာ့
တြဲသံိုးႀက ပတမ္္။ ဒါ expression ေတြကို Boolean value ေတြျ စ္တာ့ဲ True or False
လားတြက္ က္ ပတမ္္။ decision လို ္ ိုန္႔ေအရးသားတဲာ့ statement ေတြကို condition statement
or conditional expressions or conditional constructs လိုန္႔ေ ခ ပတမ္္။

If-then ကို language ေတြမာသံိုးႀက ပတမ္္။ syntax ေအရးတဲာ့ ံိုစံေတာာ့ကာြ ႀက ပတမ္္။

The if Statement

မ ိုလိုေအရး ပတမ္
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
condtion 1 မပန္ အရင္ statement_block_1 မမပန္ အရင္ condition 2 ္စစ္ မပန္အရင္
statement_block_2 မားအရင္ statement_block_3 အလို ္လို ္ ပမမ္္။

Example Dog Years

ေ ြးအသက္ 1 ႏွာစ္ဆို လအသက္ 14 ႏွာစ္

ေ ြးအသက္ ၂ ႏွာစ္ဆို လအသက္ 22 ႏွာစ္

က ပန္တာက လအသက္ ၅ ႏွာစ္


age = input("Age of the dog: ")
print
if age < 0:
print "This can hardly be true!"
elif age == 1:
print "about 14 human years"
elif age == 2:
print "about 22 human years"
elif age > 2:
human = 22 + (age -2)*5
print "Human years: ", human

Python2(ဘာသာျ ပန္) Han Phyo Oo 28


True or False

True or False ဲျြ ားအရတာကို python မာ ဒါလိုသတ္မတ္ ား ပတမ္္။

ေအာက္ ပ object ေတြကို False လိုန္႔သတ္မတ္ ပတမ္္။

 numerical zero values (0, 0L, 0.0, 0.0+0.0j),


 the Boolean value False,
 empty strings,
 empty lists and empty tuples,
 empty dictionaries.
 plus the special value None.

က ပန္တာက True ပ္။

Abbreviated IF statement

If ကို အတိုေအရး င္လည္းအရ ပတမ္္။


max = a if (a > b) else b;

Python2(ဘာသာျ ပန္) Han Phyo Oo 29


Chapter 11
Loops

General Structure of a Loop

္ ပ ္ ပလို ္ေဆာင္အရမမ္ာ့ အလို ္ေတြအတြက္ loop construcet ေတြသံိုး ပတမ္္။ python


မာ loop ႏွာစ္မ ဳေး ပ ပတမ္္။ while loop ပနဲာ့ for loop တိုန္႔ျ စ္ ပတမ္္။

A Simple Example with a While Loop

1 က ေပန 100 ေ ပင္းႀကည္ာ့အရေအာင္


n = 100

sum = 0
i = 1
while i <= n:
sum = sum + i
i = i + 1

print "Sum of 1 until %d: %d" % (n,sum)

Reading Standard Input

While loop ကိုမေျ ာ င္ standard input/output ေတြေျ ာႀကည္ာ့အရေအာင္္။ standard input


ဆိုအရင္ keyboard ကိုဆိုလိုတာျ စ္ျ ါးေတာာ့ standard output ကေတာာ့ terminal သိုန္႔ console
output ေတြကိုေျ ာတာ ပ္။ error ေတြကိုလည္း ဒါမာ ဲျ အရမာ ပ္။

Python မာ ေအာက္ ပ channel ၃ ိုအရ ပတမ္္။

 standard input
 standard output
 standard error

အားလံိုးက sys ဆိုတဲာ့ Module မာ ပ ပတမ္္။ပနာမည္ေတြကေတာာ့

 sys.stdin
 sys.stdout
 sys.stderror

ေအာက္ ပ example မာ keyboard input ကို while loop သံိုး တ္ျ ား ပတမ္္။ယ္။၏
import sys

text = ""
while 1:
c = sys.stdin.read(1)
text = text + c
if c == '\n':

Python2(ဘာသာျ ပန္) Han Phyo Oo 30


break

print "Input: %s" % text

ံိုမပန္ေတာာ့ raw_input() ကို သ


ဲ ံိုးႀက ပတမ္္။
>>> name = raw_input("What's your name?\n")
What's your name?
Tux
>>> print name
Tux
>>>

The else part

If statement လို ဲ while loop မာ optional else တစ္ ို ပ ပတမ္္။ အျ ား language


ေတြပနဲာ့ ေတာာ့ ကြဲေပန ပလမ္ာ့မမ္္။ else အ ိုင္းကို while loop condition မမပန္ေတာာ့အရင္ execution
လို ္ ပတမ္္။ else ္ ပေတာာ့ ဘာ ိုေကာင္းသြားလဲသ ိုန္႔ေတာာ့ break statement လည္းသ ိုန္႔
လို ပတမ္္။

While loop ံိုစံကေတာာ့


while condition:
statement_1
...
statement_n
else:
statement_1
...
statement_n

Premature Termination of a while Loop

While loop တစ္ ိုဟာ သသတ္မတ္ ားတဲာ့ အေျ အေပနတစ္ ိုေအရာက္မ အဆံိုးသတ္ ပတမ္္။
break statement ပနဲာ့ဆိုလ င္ သတ္မတ္ က္မျ ည္ာ့မါလည္း loop ကေပန က
ြ ္သြားေအာင္ လို ္လိုာ့
အရ ပတမ္္။ break ပနဲာ့ continue ကလည္းမတ ပဘး္။ continue ကလက္အရ loop ကိုအရ ္ျ း loop
ေပနာက္တစ္ဆင္ာ့ကိုကး ပတမ္္။

တကမ္လိုန္႔ loop က break သံိုးျ ါး က


ြ ္သြားအရင္ else အ ိုင္းအလို ္မလို ္ေတာာ့ ပဘး္။

ပနံ ပတ္ ပန္ာ့မပန္းတဲာ့ game ေလးပနဲာ့အရင္းျ ား ပတမ္္။

လတစ္ေမာက္က 1 to n ႀကား ပနံ ပတ္တစ္ ို ပန္န္႔မပန္းအရမမ္္။ keyboard ကေပန input ေ းအရမမ္္။


ပန္ာ့မပန္းတာက တကမ္ာ့ ပနံ ပတ္ က္ ႀကါးလား ငမ္လား တလားဆိုတာကို program က
အသေ းအရမမ္္။ တကမ္လိုန္႔အအရံိုးေ း င္အရင္ ၀ or အပနတ္ကပန္းတစ္ ို ည္ာ့ေ းအရမမ္္။

Random no လို ္ ိုန္႔ “random” modul လို ပတမ္္။


import random

Python2(ဘာသာျ ပန္) Han Phyo Oo 31


n = 20
to_be_guessed = int(n * random.random()) + 1
guess = 0
while guess != to_be_guessed:
guess = input("New number: ")
if guess > 0:
if guess > to_be_guessed:
print "Number too large"
else:
print "Number too small"
else:
print "Sorry that you're giving up!"
break
else:
print "Congratulation. You made it!"

Python2(ဘာသာျ ပန္) Han Phyo Oo 32


Chapter 12
For Loops

Introduction

For loop statement ကလည္း C C++ ပနဲန္႔ကြဲ ပတမ္္။ batsh shell loop ပနဲန္႔ဆင္ ပတမ္္။

တစ္ ပတစ္အရံ list ေတြ number အမ ားႀကါးေတြပနဲာ့ operation ေတြလို ္အရတာအရ ပတမ္္။ python
for statement က ဒါလို list ေတြ range type ေတြအမ ားႀကါးအတြက္ အဆင္ေျ ပတမ္္။

Syntax of the For Loop


for variable in sequence:
Statement1
Statement2
...
Statementn
else:
Else-Statement1
Else-Statement2
...
Else-Statementm

Example of a for loop in Python:


>>> languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print x
...
C
C++
Perl
Python
>>>

The range() Function

Number sequence ေတြပနဲာ့ iteration ေတြလို ္မမ္ဆိုအရင္ range() function


ကအဆင္ေျ ပတမ္္။ သက arithmetic progession list ေတြ ို ္ေ း ပတမ္္။
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(n) ဆိုအရင္ 0 ကေပန စျ ါး (n-1) အ ို ္ေ း ပတမ္္။

range() ကို argument ႏွာစ္ ိုပနဲာ့လည္းအသံိုးျ ဳေပန္ိုင္ ပတမ္္။


range(begin,end)
အစကေပန အဆံိုး က္ 1 ိုေလ ာာ့ ိုတ္ေ းမာ ပ္။ default increment က ၁ ပ္။
အဲာ့တာကိုျ င္ င္ အရင္ တတမ argument ည္ာ့ေ းအရ ပမမ္္။ step လိုန္႔ေ ခ ပတမ္ non-zero
ျ စ္အရ ပမမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 33


range(begin,end, step)
Example with step:
>>> range(4,10)
[4, 5, 6, 7, 8, 9]
>>> range(4,50,5)
[4, 9, 14, 19, 24, 29, 34, 39, 44, 49]
range() function က loop ပနဲာ့သံိုးအရင္ အလြပန္အသံိုး၀င္ ပတမ္္။ ေအာက္ ပစ မာမာ range()
function က number 1 to 100 for loop ကို ိုတ္ေ း ပတမ္္။
n = 101
sum = 0
for i in range(1,n):
sum = sum + i
print sum

Calculation of the Pythagorean Numbers

Pythagorean definition က a2+b2=c2 ျ စ္ ပတမ္္။


from math import sqrt
n = raw_input("Maximal Number? ")
n = int(n)+1
for a in range(1,n):
for b in range(a,n):
c_square = a**2 + b**2
c = int(sqrt(c_square))
if ((c_square - c**2) == 0):
print a, b, c

Iterating over Lists with range()

List index ေတြကိုသ င္အရင္ for loop သံိုးအရတာအဆင္မေျ ပဘး္။ element


ေတြကိုသပနိုင္ေ မမ္္။ ဆိုင္ အရာ index ေတြကိုမသပနိုင္ ပဘး္။ index ေအရာ value ေအရာ သ င္အရင္
range() ပနဲာ့ Len() တြဲသံိုးေ းအရ ပမမ္္။
fibonacci = [0,1,1,2,3,5,8,13,21]
for i in range(len(fibonacci)):
print i,fibonacci[i]
print
len() က list ေတြ tuple ေတြမာ ပတဲာ့ element အေအရအတြက္ကိုလို င္အရင္သံိုး ပတမ္္။

List iteration with Side Effects

List ေတြကို interation လို ္အရင္ list ကို loop body မာ ေျ ာင္းလဲတာေတြမလို ္တာေကာင္း
ပတမ္္။ eg.

Python2(ဘာသာျ ပန္) Han Phyo Oo 34


colours = ["red"]
for i in colours:
if i == "red":
colours += ["black"]
if i == "black":
colours += ["white"]
print colours
ဘာ print ိုတ္မလဲဆိုေတာာ့
['red', 'black', 'white']

အဲာ့လိုမျ စ္ေအာင္ slicing operator သံိုးျ ါး list ကို copy ြားျ ါးသံိုးပနိုင္ ပတမ္္။
colours = ["red"]
for i in colours[:]:
if i == "red":
colours += ["black"]
if i == "black":
colours += ["white"]
print colours
ဒါတစ္ ပ print ိုတ္မာက
['red', 'black']
“colours” list ကိုေျ ာင္းေ မမ္ာ့လည္း loop က element ကမေျ ာင္းတဲာ့အတြက္ လို င္တဲာ့
result က
ြ ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 35


Chapter 13
Formatted Output

Many Ways for a Nicer Output

Python မာ လလ print လို ္ ိုန္႔ပနည္းလမ္းေတြအမ ားႀကါးအရ ပတမ္္။ string class အရဲာ့ format
method ကိုေတာာ့သံိုးသင္ာ့ ပတမ္္။

Value ႏွာစ္ ို က္ ိုတာေတြ print ို ္ င္အရင္ ႏွာစ္မ ဳေးသံိုး ာ့ႀဲ က ပတမ္္။

 အလြမ္ဆံိုးကေတာာ့ values ေတြႀကားမာ , ံျ ါး print ိုတ္တာျ စ္ ပတမ္္။ default


အေပနပနဲံေတာာ့ blank ေတြႀကား မ
ဲ ာ ည္ာ့ေ း ပတမ္ ္။ sep keyword သံိုးျ ါး
ႀကဳေက္တာသတ္ မတ္ င္လညး္အရ ပတမ္္။
>>> q = 459
>>> p = 0.098
>>> print(q, p, p * q)
459 0.098 44.982
>>> print(q, p, p * q, sep=",")
459,0.098,44.982
>>> print(q, p, p * q, sep=" :-) ")
459 :-) 0.098 :-) 44.982
>>>
 ေပနာက္တစ္ပနည္းကေတာာ့ string concatenation operator သံိုးတာျ စ္ ပတမ္္။
>>> print(str(q) + " " + str(p) + " " + str(p * q))
459 0.098 44.982
>>>
ဒိုတမပနည္းက ိုေကာင္း ပတမ္္။

The Old Way or the non-existing printf and sprintf

Python မာ c လို printf မ ပေ မမ္ာ့ printf function ေတြ ပ ပတမ္္။အဲာ့ဒါအတြက္ modulo


operator % ကို string class က string formatting ေတြလို ္ ိုန္႔ overload လို ္ ား ပတမ္္။
တစ္ ပတစ္အရံ string modulo operator လိုန္႔လည္းေ ခႀက ပတမ္္။ ေပနာက္တစ္ ိုက string
interpolation လိုာ့လည္းေျ ာႀက ပတမ္္။ ဘာလိုာ့လည္းဆိုေတာာ့ အမ ဳေးမ ဳေးေသာ data type ေတြ(
int float and so on) ေတြကို formatted string ေတြအျ စ္ေျ ာင္းလဲေ ပင္းစ ္ ေ းလိုာ့
ေ းလိုာ့ျ စ္ ပတမ္္။ string interpolation သံိုးျ ါး ျ ဳေလို ္လို ္တဲာ့ string ေတြကို
ျ ားတဲာ့အသံိုးျ ဳေ ံိုပနဲာ့သံိုးႀက ပတမ္္။ database ဲ ကို format မပန္မပန္ ကပန္ကပန္
ပန္တါး ိုန္႔လည္းသံိုး ပတမ္္။ ဒပေ မမ္ာ့ python 2.6 ကေပနစတင္ျ ါးေတာာ့ ဒါပနည္းလမ္းအစား string
mehto format ကိုသံိုးသင္ာ့ ပတမ္္။ ဆိုးတာက string module % က python 3
မာလည္း ပသလို က မ္က မ္ျ ပန္ာ့ျ ပန္ာ့လည္းသံိုးေပနတံိုး ပ ဲ္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 36


>>>print(“Art:%5d,price per Unit : %8.2f” %(453,59.058))
Art: 453,price per Unit : 59.06

Formatted place holder အရဲာ့ေအရးတဲာ့ ံိုစံက

%[flags][width][.precision]type

Eg ေအရးျ ားတဲာ့ဆါမာ ဒိုတမ “%8.2f” က float number အတြက္ ပ္။ တစ္ျ ား place holder
ေတြလို ဲ % ပနဲာ့စ ပတမ္္။ ေပနာက္မာက string မာ ပမမ္ာ့ digit အေအရအတြက္ .
ေပနာက္မာ ပတာကေတာာ့ float point ေပနာက္က number အေအရအတြက္ျ စ္ ပတမ္္။ f ကေတာာ့
place holder သည္ float ျ စ္ေႀကာင္းေျ ာ ပတမ္္။

Output ကိုႀကည္ာ့မမ္ဆိုအရင္ digit 3 ိုကို round မ ားတာေတြာ့ ပမမ္္။ ျ ါးေတာာ့ေအရာ့မာ blank 3


ေပနအရာလည္း ပ ပမမ္္။

“%5d” ကေတာာ့ content tuple ဲက 453 အတြက္ ပ္။ character 5 လံိုးပနဲာ့အရိုက္ ပမမ္္။ 453 က
3 လံိုး ဲ ပေတာာ့ ေအရာ့မာ black 2 လံိုး ပ ပမမ္္။

Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Obsolete and equivalent to 'd', i.e. signed integer decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).

Python2(ဘာသာျ ပန္) Han Phyo Oo 37


Conversion Meaning
% No argument is converted, results in a "%" character in the result.

Examples
>>> print("%10.3e"% (356.08977))
3.561e+02
>>> print("%10.3E"% (356.08977))
3.561E+02
>>> print("%10o"% (25))
31
>>> print("%10.3o"% (25))
031
>>> print("%10.5o"% (25))
00031
>>> print("%5x"% (47))
2f
>>> print("%5.4x"% (47))
002f
>>> print("%5.4X"% (47))
002F
>>> print("Only one percentage sign: %% " % ())
Only one percentage sign: %
>>>
Flag Meaning
# Used with o, x or X specifiers the value is preceded with 0, 0o, 0O, 0x or 0X
respectively.
0 The conversion result will be zero padded for numeric values.
- The converted value is left adjusted

If no sign (minus sign e.g.) is going to be written, a blank space is inserted before the
value.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

Examples:
>>> print("%#5X"% (47))
0X2F
>>> print("%5X"% (47))
2F
>>> print("%#5.4X"% (47))
0X002F
>>> print("%#5o"% (25))
0o31
>>> print("%+d"% (42))
+42
>>> print("% d"% (42))
42
>>> print("%+2d"% (42))
+42

Python2(ဘာသာျ ပန္) Han Phyo Oo 38


>>> print("% 2d"% (42))
42
>>> print("%2d"% (42))
42

String modulo operator % ကို print ပနဲာ့တသ


ြဲ ံိုးေပနေ မမ္ာ့ မဆိုင္ႀက ပဘး ၊ string တစ္ ိုကို
string modulo operator ပနဲာ့ apply လို ္အရင္ string ိုတ္ေ းမာ ဲျ စ္ ပတမ္္။
>>> s = "Price: $ %8.2f"% (356.08977)
>>> print(s)
Price: $ 356.09
>>>

The Pythonic Way: The string method "format"


Format method ကို python 2.6 မာ စ ည္ာ့ ဲာ့ ပတမ္္။ ံိုစံက
template.format(p0, p1, ..., k0=v0, k1=v1, ...)

template ဆိုတာက format codes ေတြ ပတဲာ့ string ျ စ္ျ ါးေတာာ့ text
ေတြ မ
ဲ ာ ည္ာ့ ားမာ ျ စ္ ပတမ္္။ အစား ိုးမမ္ာ့ စာေတြကိုေတာာ့ {} မ
ဲ ာ ည္ာ့ ား ပတမ္္။
{} ပနဲန္႔ အတ အ မ
ဲ ာ အရတဲာ့ code ေတြကို formatted value အရတဲာ့ arugument ပနဲန္႔
အစား ိုးမာျ စ္ ပတမ္္။ {} မ
ဲ မ ပတာေတြကေတာာ့ ံိုမပန္ စာေႀကာငး္လို ဲ ေျ ာင္းလဲမိုမအရ print
လို ္ ပမမ္္။ {} ေတြ print လို ္ ိုန္႔ လိုလာအရင္ေတာာ့ 2 ိုေအရးျ ါး escape လို ္ေ းအရ ပမမ္ {{ ပနဲာ့ }}

.format method အတြက္ argument ႏွာစ္မ ဳေးအရ ပတမ္္။ 0 ကေပနစတဲာ့ positional arugment list
(p0,p1,….) အဲန္႔ေပနာက္မာ keyword argument ေတြက name=value ံိုစံပနဲာ့အရ ပမမ္္။

.format() method အရဲာ့ Positional parameter ေတြကို လို င္အရင္ eg.{0} {1}စသျ င္ာ့ အသံိုးျ ဳေ
ပနိုင္ ပတမ္္။ string modulo operator % မာလို ဲ index ေပနာက္မာ : ံျ ါး format string ေတြ
ည္ာ့ပနိုင္ ပေသးတမ္္။ eg {0:5d}

Format method ဲ က positional parameter ေတြကို အစစ္အတိုင္း ဲဆိုအရင္ {} ဲက


positional argument specifier ေတြကို မေအရးလဲအရ ပတမ္္။ ဆိုလိုတာက “{}{}{}” ဆိုတာ
“{0}{1}{2}” ပ ဲ္။ ေပနအရာတလြေ
ဲ တြ ားအရင္ေတာာ့လို ပတမ္္။
>>>“Art:{0:5d}, Price per Unit:{1:8.2f}”.format(453,59.058)
Art: 453, Price per Unit: 59.06
Examples
>>> "First argument: {0}, second one: {1}".format(47,11)
'First argument: 47, second one: 11'
>>> "Second argument: {1}, first one: {0}".format(47,11)
'Second argument: 11, first one: 47'
>>> "Second argument: {1:3d}, first one: {0:7.2f}".format(47.42,11)
'Second argument: 11, first one: 47.42'
>>> "First argument: {}, second one: {}".format(47,11)

Python2(ဘာသာျ ပန္) Han Phyo Oo 39


'First argument: 47, second one: 11'
>>> # arguments can be used more than once:
...
>>> "various precisions: {0:6.2f} or {0:6.3f}".format(1.4148)
'various precisions: 1.41 or 1.415'
>>>

ေအာက္ ပ စ မာမာ keyword parameter သံိုးတဲာ့ ံိုစံျ ား ပတမ္္။


>>> "Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058)
'Art: 453, Price: 59.06'
>>>
Format method ပနဲန္႔ left right justify လို ္ပနိုင္ ပတမ္္။ left justify အတြက္ “<” right justify
အတြက္ “>” ကို : ေပနာက္က format string အစမာ ည္ာ့ေ းပနိုင္ ပတမ္္။
>>> "{0:<20s} {1:6.2f}".format('Spam & Eggs:', 6.99)
'Spam & Eggs: 6.99'
>>> "{0:>20s} {1:6.2f}".format('Spam & Eggs:', 6.99)
' Spam & Eggs: 6.99'

Option Meaning

'<'
The field will be left-aligned within the available space. This is usually the default
for strings.

'>'
The field will be right-aligned within the available space. This is the default for
numbers.

If the width field is preceded by a zero ('0') character, sign-aware zero-padding for
numeric types will be enabled.
>>> x = 378
'0' >>> print("The value is {:06d}".format(x))
The value is 000378
>>> x = -378
>>> print("The value is {:06d}".format(x))
The value is -00378

This option signals the use of a comma for a thousands separator.


>>> print("The value is {:,}".format(x))
The value is 78,962,324,245
',' >>> print("The value is {0:6,d}".format(x))
The value is 5,897,653,423
>>> x = 5897653423.89676
>>> print("The value is {0:12,.3f}".format(x))
The value is 5,897,653,423.897

Forces the padding to be placed after the sign (if any) but before the digits. This is
'=' used for printing fields in the form "+000000120". This alignment option is only
valid for numeric types.
'^' Forces the field to be centered within the available space.

Minimum field width မသတ္မတ္ ားအရင္ field width အျမဲတေပနတဲာ့အတြက္ေႀကာင္ာ့


alignment option က အသံိုးမ၀င္ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 40


Number type ေတြအတြက္လည္း sign option အရ ပေသးတမ္္။

Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.

'-'
indicates that a sign should be used only for negative numbers, which is the default
behavior.

indicates that a leading space should be used on positive numbers, and a minus sign
space
on negative numbers.

Using dictionaries in "format"


Format လို ္မမ္ာ့ value ကိုႏွာစ္မ ဳေး access လို ္ပနိုင္ေႀကာင္းေျ ာ ဲာ့ျ းျ စ္ ပတမ္္။

 sing the position or the index:


>>> print("The capital of {0:s} is {1:s}".format("Ontario","Toronto"))
The capital of Ontario is Toronto
>>>
{} ည္း ဲေအရး င္လည္းအရ ပတမ္္။

 Using keyword parameters:


>>> print("The capital of {province} is
{capital}".format(province="Ontario",capital="Toronto"))
The capital of Ontario is Toronto
>>>
ဒိုတမပနည္းကို dictionary သံိုးျ ါးလို ္လိုာ့အရ ပေသးတမ္္။
>>> data = dict(province="Ontario",capital="Toronto")
>>> data
{'province': 'Ontario', 'capital': 'Toronto'}
>>> print("The capital of {province} is {capital}".format(**data))
The capital of Ontario is Toronto
Asterisk * ႏွာစ္ ို ည္ာ့ ားအရင္ data ကို 'province="Ontario",capital="Toronto"' ံိုစံ ေျ ာ
ေျ ာင္းေ း ပတမ္္။
capital_country = {"United States" : "Washington",
"US" : "Washington",
"Canada" : "Ottawa",
"Germany": "Berlin",
"France" : "Paris",
"England" : "London",
"UK" : "London",
"Switzerland" : "Bern",
"Austria" : "Vienna",

Python2(ဘာသာျ ပန္) Han Phyo Oo 41


"Netherlands" : "Amsterdam"}

print("Countries and their capitals:")


for c in capital_country:
print("{country}: {capital}".format(country=c,
capital=capital_country[c]))

result က
Countries and their capitals:
United States: Washington
Canada: Ottawa
Austria: Vienna
Netherlands: Amsterdam
Germany: Berlin
UK: London
Switzerland: Bern
England: London
US: Washington
France: Paris

Dictionary ပနဲန္႔ေအရးလည္းအရ ပတမ္္။


capital_country = {"United States" : "Washington",
"US" : "Washington",
"Canada" : "Ottawa",
"Germany": "Berlin",
"France" : "Paris",
"England" : "London",
"UK" : "London",
"Switzerland" : "Bern",
"Austria" : "Vienna",
"Netherlands" : "Amsterdam"}

print("Countries and their capitals:")


for c in capital_country:
format_string = c + ": {" + c + "}"
print(format_string.format(**capital_country))

Using Local Variable Names in "format"

“local”ဆိုတာ function တစ္ ို ပ ္။ local scope ဲက variable ေတြကို dictionary အေပနပနဲာ့


return ျ ပန္ေ း ပတမ္္။ local variable ေတြက dictionary အတြက္ key ျ စ္ျ ါး value ကေတာာ့
၎ variable value ေတြျ စ္ ပတမ္္။
>>> a = 42
>>> b = 47
>>> def f(): return 42
...
>>> locals()
{'a': 42, 'b': 47, 'f': <function f at 0xb718ca6c>, '__builtins__': <module
'builtins' (built-in)>, '__package__': None, '__name__': '__main__',
'__doc__': None}
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 42


Locals() ကအရလာတဲာ့ dictionary ကို string format မာသံိုးပနိုင္တမ္္။
>>> print("a={a}, b={b} and f={f}".format(**locals()))
a=42, b=47 and f=<function f at 0xb718ca6c>

Other string methods for Formatting

String class မာ အျ ား method ေတြအရ ပေသးတမ္္။ ၎ တက


ိုန္႔ ို format string လို ္ ိုန္႔သံိုး
ပနိုင္ ပတမ္္။ ljust, rjust, center and zfill

S ဆိုတဲာ့ string တစ္ ိုပနဲန္႔စမ္းႀကည္ာ့ ပမမ္္။

 enter(...):
S.center(width[, fillchar]) -> str
Return S centred in a string of length width. Padding is done using the specified fill
character. The default value is a space.

Examples:
>>> s = "Python"
>>> s.center(10)
' Python '
>>> s.center(10,"*")
'**Python**'
 ljust(...):
S.ljust(width[, fillchar]) -> str
Return S left-justified in a string of length "width". Padding is done using the
specified fill character. If none is given, a space will be used as default.

Examples:
>>> s = "Training"
>>> s.ljust(12)
'Training '
>>> s.ljust(12,":")
'Training::::'
>>>
 rjust(...):
S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is done using the
specified fill character. The default value is again a space.

Examples:
>>> s = "Programming"
>>> s.rjust(15)
' Programming'
>>> s.rjust(15, "~")
'~~~~Programming'
>>>
 zfill(...):
S.zfill(width) -> str

Python2(ဘာသာျ ပန္) Han Phyo Oo 43


Pad a string S with zeros on the left, to fill a field of the specified width. The string S
is never truncated. This method can be easily emulated with rjust.

Examples:
>>> account_number = "43447879"
>>> account_number.zfill(12)
'000043447879'
>>> # can be emulated with rjust:
...
>>> account_number.rjust(12,"0")
'000043447879'
>>>

Formatted String Literals

Python 3.6 မာ formatted string leterals မ ား ပလာ ပတမ္္။ ‘f’ ပနဲန္႔စ ပတမ္္။ str.format()
ကလက္ ံ တဲာ့ formatting syntax ပနဲန္႔တ ပတမ္္။ format method အရဲာ့ format string လို ဲ {} ပနဲန္႔
အစား ိုးမမ္ာ့ေပနအရာေတြ ပတမ္္။ eg.
>>> price = 11.23
>>> f"Price in Euro: {price}"
'Price in Euro: 11.23'
>>> f"Price in Swiss Franks: {price * 1.086}"
'Price in Swiss Franks: 12.195780000000001'
>>> f"Price in Swiss Franks: {price * 1.086:5.2f}"
'Price in Swiss Franks: 12.20'
>>> for article in ["bread", "butter", "tea"]:
... print(f"{article:>10}:")
...
bread:
butter:
tea:

Python2(ဘာသာျ ပန္) Han Phyo Oo 44


Chapter 14
Output With Print

Program ေတြအားလံိုးပနါး ပး အျ င္ေလာက ပနဲ န္႔ဆက္သြမ္ ျ ါး input>>process>>output ံိုစံ


အလို ္လို ္ႀက ပတမ္္။ result ကိုေတာာ့ ို ္ျ အရမာျ စ္ ပတမ္္။ python မာ ေျမာက္ျမားစြာ ဲမ
တစ္ ိုကေတာာ့ print ျ စ္ ပတမ္္။
>>> print "Hello User"
Hello User
>>> answer = 42
>>> print "The answer is: " + str(answer)
The answer is: 42
>>>
() မ
ဲ ာ parameter ေတြလည္း ည္ာ့ေ းပနိုင္ ပတမ္္။
>>> print("Hallo")
Hallo
>>> print("Hallo","Python")
('Hallo', 'Python')
>>> print "Hallo","Python"
Hallo Python
>>>
Output ိုတ္ေ းတဲာ့ ံိုစံလည္းေျ ာင္းသြား ပတမ္္။ အေအရးႀကါးတာကေတာာ့ python version 2.x
ပနဲ႕ 3.x လည္းကြာ ပတမ္္။
$ python3
Python 3.2.3 (default, Apr 10 2013, 05:03:36)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello")
Hello
>>> print("Hello","Python")
Hello Python
>>>
Python 3 မာလို ဲျ စ္ င္အရင္ေတာာ့ “future” ဆါကေပန import လို ္ျ ါးသံိုးအရ ပမမ္္။

Import from future: print_function

Python program အ ဳေမာ ေအာက္ ပline ေလး ပ ပလမ္ာ့မမ္ာ့္။


from __future__ import print_function

မအရင္းတာေတြအရ ပလ္မ္ာ့မမ္္။ “print_function” ကို import လို ္ေပနတမ္ င္ ပလ္မ္ာ့မမ္္။ အမပန္


ေတာာ့ flag ေလးတစ္ ိုလို ္လိုက္တာ ပ္။ ဒါလို flag ေလးလို ္လိုက္အရင္ interpreter က print
function ကိုသံိုးလိုန္႔အရေအာင္လို ္ေ း ပတမ္္။

Import လို ္ေ းတာက python 3 အတြက္လည္း အဆင္ေျ ေစတာေႀကာင္ာ့ လို ္သင္ာ့ ပတမ္္။

Note//python n 3 မာ print statement မ ပေတာာ့ ဲ print function ဲ ပ ပေတာာ့တမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 45


Chapter 15
Sequential Data Types

Strings

String ေတြ character အတြဲလိုက္ေတြအေပနပနဲာ့ျမင္ပနိုင္ ပတမ္္။အမ ဳေးမ ဳေးေ ာ္ျ ပနိုင္ ပတမ္္။

 single quotes (')


'This a a string in single quotes'
 double quotes (") "Miller's dog bites"
 triple quotes(''') or (""") '''She said: "I don't mind, if Miller's dog bites"'''

Indexing strings

“Hello World” ဆိုတဲာ့ string တစ္ ိုမာ character ေတြကို ဘမ္မညာသိုန္႔ 0 ကေပနစျ ါး
enumeration လို ္ ပတမ္္။ ညာဘက္ကေပနဆိုအရင္ -1 ကစ ပတမ္္။

String ဲက character တစ္ ိုျ င္းဆါကို string name ပနဲာ့ [index no] သံိုးျ ါး အသံ
အသံိုးျ ဳေ ပနိုင္ ပတမ္္။

>>> txt = "Hello World"


>>> txt[0]
'H'
>>> txt[4]
'o'

Negative index value ေတြလည္းအသံိုးျ ဳေပနင္တမ္္။ညာဘက္ကေပန -1 ပနဲာ့စ ပတမ္္။

>>> txt[-1]
'd'
>>> txt[-5]
'W'
Python Lists

Pythonမာ list ကေတာာ့ versatile data type တစ္ျ စ္ ပတမ္။ versatile ဆိုတာကေတာာ့ type
အမ ဳေးေျ ာင္းလဲအသံိုးျ ဳေပနင
ို ္တာျ စ္ ပတမ္္။eg. integer list , string list. List ေတြေအရးတဲာ့အ ပ [
[] ဲမာ comma sepatater value(CSV) အေပနပနဲန္႔ေအရးပနိုင္ ပတမ္္။ c,c++,java တန္႔ဆ
ို ါက array
ပနဲာ့တေ မဲာ့ ံိုမပန္ classical array ေတြ က္ ိုျ ါး flexible ျ စ္ ပတမ္္။ စ မာ list ဲက item
ေတြက type မတလည္းအရ ပတမ္္။ ျ ါးေတာာ့ list size က ္ ာ့လ
ဲ ိုန္႔အရ ပတမ္္။ array မာလို
အေသမဟိုတ္ ပဘး္။

An example of a list:

Python2(ဘာသာျ ပန္) Han Phyo Oo 46


languages = ["Python", "C", "C++", "Java", "Perl"]

list itemေတြကို သံိုးစြဲ ိုန္႔(access)လို ္ ိုန္႔ ပနည္းအမ ဳေးမ ဳေးအရ ပတမ္္။ အလြမ္ဆံိုးကေတာာ့ index
သံိုးတာ ပ္။
>>> languages = ["Python", "C", "C++", "Java", "Perl"]
>>> languages[0]
'Python'
>>> languages[1]
'C'
>>> languages[2]
'C++'
>>> languages[3]
'Java'
ိုျ ားတဲာ့ဆါမာ data type တ ပတမ္္။ မတလဲအရ ပတမ္္။
group = ["Bob", 23, "George", 72, "Myriam", 29]

Sublists

List မ
ဲ ာ sublist ေတြအရပနိုင္ ပတမ္္။ sublist မ
ဲ ာ sublist အရပနိုင္ ပေသးတမ္္။
>>> person = [["Marc","Mayer"],["17, Oxford Str", "12345","London"],"07876-
7876"]
>>> name = person[0]
>>> print name
['Marc', 'Mayer']
>>> first_name = person[0][0]
>>> print first_name
Marc
>>> last_name = person[0][1]
>>> print last_name
Mayer
>>> address = person[1]
>>> street = person[1][0]
>>> print street
17, Oxford Str

ိုမိုအရ ္ေ းြ တဲာ့ ံိုစံေလးျ ား ပတမ္္။


>>> complex_list = [["a",["b",["c","x"]]]]
>>> complex_list = [["a",["b",["c","x"]]],42]
>>> complex_list[0][1]
['b', ['c', 'x']]
>>> complex_list[0][1][1][0]
'c'

Tuples

Python2(ဘာသာျ ပန္) Han Phyo Oo 47


Tuples ေတြကေတာာ့ immutable list ေတြျ စ္ ပတမ္္။ တည္ေဆာက္ျ ါးအရင္ ေျ ာ
ေျ ာင္းလဲလိုန္႔မအရ ပဘး tuples ပနဲာ့ list ပနဲာ့သေဘာတအရားအေပနပနဲာ့တေ မဲာ့ tuple က () သံိုးျ ါး list က
[] သံိုး ပတမ္္။ index rule ေတြလည္းအတတ ပ ဲ ္။ tuple တစ္ ိုတည္ေဆာက္ျ ါးအရင္ item
ေတြ ည္ာ့လိုာ့ျ ဳေတ္လိုန္႔ မအရေတာာ့ ပဘး

Tuple အက ိုးေက းဇးမ ား

 Tuple က list က္ျမပန္ ပတမ္္။


 မမအရဲာ့ data ကေျ ာင္းစအရာမလိုေတာာ့ဘးဆိုတာသအရင္ tuple သံိုးသင္ာ့ ပတမ္္။ မေတာ္တဆ
data ေျ ာင္းသြားတာမ ဳေးကေပနကာကြမ္ပနိုင္ ပတမ္္။
 Tuple ကို dictionary ေတြမာ key အေပနပနဲာ့သံိုးပနိုင္ ပတမ္္။ list ကေတာာ့မအရ ပဘး

Tuple examples/ data ေျ ာင္းလဲ ိုန္႔ေကိုးစားတဲာ့အ ပ error ေ းမာ ပ္။


>>> t = ("tuples", "are", "immutable")
>>> t[0]
'tuples'
>>> t[0]="assignments to elements are not possible"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Generalization

List ေတြ string ေတြမာ common properties ေတြအရ ပတမ္္။ eg.list item ေတြ string
character ေတြကို အစစ္လိုက္အရျ ါးေတာာ့ Index ပနဲာ့အသံိုးျ ဳေပနိုင္ ပတမ္္။ tuple လိုတစ္ျ ား data
type ေတြအရ ပေသးတမ္္။(buffer and xrange) "sequence data types" or "sequential data
types"လိုန္႔ေ ခ ပတမ္္။

"sequence data types" အတြက္ operator ေတြ method ေတြကေတာာ့ အတတ ပ ဲ္။

Slicing

String က
ဲ တစ္စတ္တစ္ ိုင္း , list ဲက တစ္စတ္တစ္ ိုင္း လို င္အရင္ slice operator
သံိုး ပတမ္္။ range တစ္ ိုပနဲာ့ မတဲာ့သေဘာ ပ ဲ ္။ eg
>>> str = "Python is great"
>>> first_six = str[0:6]
>>> first_six
'Python'
>>> starting_at_five = str[5:]
>>> starting_at_five
'n is great'
>>> a_copy = str[:]
>>> without_last_five = str[0:-5]
>>> without_last_five
'Python is '
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 48


List မာလဲဒါသေဘာ ပ ဲ
>>> languages = ["Python", "C", "C++", "Java", "Perl"]
>>> some_languages = languages[2:4]
>>> some_languages
['C++', 'Java']
>>> without_perl = languages[0:-1]
>>> without_perl
['Python', 'C', 'C++', 'Java']
>>>
Slicing ကို argument သံိုး ိုပနာ့သ
ဲ ံိုး င္အရင္လည္းအရ ပတမ္္။ step ပ
s[begin: end: step]
third parameter ဲ ပအရင္ အစကေပနအဆံိုးကို third parameter ေ း ားတဲာ့အတိုင္း
မသြားမာ ပ္။
>>> str = "Python under Linux is great"
>>> str[::3]
'Ph d n e'
ဒါမာ 3 ိုျ ား မတာေတြန္႔မာ ပ္။

Length

Sequence အရဲာ့ length ကိုေျ ာတာ ပ္။ list, string , tuple ေတြအရဲာ့ length ကို len()
သံိုးျ ါးသပနင္ ပတမ္္။ string မာဆိုအရင္ character ေတြကိုေအရတြက္ျ ါးေတာာ့ list,tuple
ေတြမာေတာာ့ element ေတြကိုေအရတြက္ ပတမ္္။ sublist ေတြကို 1 element
အေပနပနဲန္႔ေအရတြက္ ပတမ္္။
>>> txt = "Hello World"
>>> len(txt)
11
>>> a = ["Swen", 45, 3.54, "Basel"]
>>> len(a)
4

Concatenation of Sequences

Sequences ေတြကိုေ ပင္းစ ္တာ ဟာ ဂဏပန္း ႏွာစ္လံိုးေ ပင္းသလို ပ ဲ္။ operator sign
လည္းတ ပတမ္္။
>>> firstname = "Homer"
>>> surname = "Simpson"
>>> name = firstname + " " + surname
>>> print name
Homer Simpson
>>>
List အတြက္လည္းအတတ ပ ဲ
>>> colours1 = ["red", "green","blue"]
>>> colours2 = ["black", "white"]
>>> colours = colours1 + colours2

Python2(ဘာသာျ ပန္) Han Phyo Oo 49


>>> print colours
['red', 'green', 'blue', 'black', 'white']

“+=” operator ကလည္း sequences မာအလို ္လို ္ ပတမ္္။


s += t
ေအာက္ ပ ံိုစံပနဲအ
ာ့ တတ ပ ဲ
s = s + t
စာအေပနပနဲာ့တေ မဲာ့ ေပနာက္ကမ
ြ ္ကအလို ္လို ္ ံိုေတာာ့ကဲြ ပတမ္္။ မမာေတာာ့
ဘမ္ က္အတြက္ တစ္ ပ ဲႀကည္ာ့စအရာ (evaluate)လို ပတမ္္။ argument assignment ကို
mutable object ေတြမာ optimizing ေကာင္း ိုန္႔သံိုးႀက ပတမ္္။

Checking if an Element is Contained in List

Item တစ္ ို sequence မ


ဲ ာ ပမ ပ စစ္ ိုန္႔လြမ္ ပတမ္္။ “in” သိုန္႔ “not in” operator ေတြသံိုးပနိုင္
ပတမ္္။
>>> abc = ["a","b","c","d","e"]
>>> "a" in abc
True
>>> "a" not in abc
False
>>> "e" not in abc
False
>>> "f" not in abc
True
>>> str = "Python is easy!"
>>> "y" in str
True
>>> "x" in str
False
>>>

Repetitions

Sequences အတြက္ + operator ေတြသံိုး ဲာ့တမ္္။ “*”


လည္းအရ ပတမ္္။ ေျမာက္တာမဟိုတ္ ပဘး အႀကမ္အေအရအတြက္တစ္ ို
္ ပ ္ ပ ြားအရင္သံိုး ပတမ္္။
str * 4
ဆိုတာက
str + str + str + str

Further examples:
>>> 3 * "xyz-"
'xyz-xyz-xyz-'

Python2(ဘာသာျ ပန္) Han Phyo Oo 50


>>> "xyz-" * 3
'xyz-xyz-xyz-'
>>> 3 * ["a","b","c"]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
“*=” လည္းသံိုးပနိုင္ ပတမ္္။

The Pitfalls of Repetitions

Repetition ကို အရိုးအရိုး list မာသံိုးပနင္သလို nested list အတြက္လည္းသံိုးပနိုင္ ပတမ္္။


>>> x = ["a","b","c"]
>>> y = [x] * 4
>>> y
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> y[0][0] = "p"
>>> y
[['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c']]
အရလာတဲာ့ result က စေလာ့လာတဲာ့သဆိုအရင္ အံံာ့ႀသစအရာ ပ္။ y အရဲာ့ first sublist အရဲာ့ first element ကို
တပန္ ိုး အသစ္ ည္ာ့လိုက္ ပတမ္္။ ဆိုလိုတာက y[0][0] ကို ေျ ာင္းလိုက္တာ့အ
ဲ ပ တစ္ျ ား
sublist အရဲာ့ first element ေတြ y[1][0], y[2][0], y[3][0] ေတြ ပလိုက္ေျ ာင္းသြား ပတမ္္။

အေႀကာင္းျ က္ကေတာာ့ * operator က list အတြက္ reference 4 ိုလို ္လိုက္လိုန္႔ ပ္။


ဒပေႀကာင္ာ့ ကို က တစ္ ို ဲေျ ာင္းတမ္ င္ေ မမ္ာ့ 4 ိုကreference လို ္ ားတဲာ့အတြက္ 4
ိုလံိုးေျ ာင္းသြား တာ ပ္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 51


Chapter 16
Dictionaries

List ေတြအေႀကာင္းျ ါးေတာာ့ dictionary ေတြအေႀကာင္း ပ္။ Dictionary က list လို ဲ runtime မာ
ေျ ာင္းလဲတာေတြလို ္ပနိုင္ ပတမ္္။ list မ
ဲ ာ dictionary အရပနိုင္သလို dictionary မ
ဲ ာ လညး္ list
ေတြ ပ၀င္ပနိုင္ ပတမ္္။ကြာျ ား က္က list ေတြက ordered sets ေတြျ စ္ျ ါးေတာာ့ dictionary
ေတြကေတာာ့ unordered sets ေတြျ စ္ ပတမ္္။ ျ ါးေတာာ့ dictionary ေတြမာ item ေတြကို
position ပနဲာ့မဟိုတ္ ဲ key ပနဲန္႔ access လို ္တာျ စ္ ပတမ္္။Associative array (hashes)
လိုန္႔လည္းေ ခ ပတမ္္။ dictionary မာ key ပနဲန္႔ value ကိုmapping ား ပတမ္္။ dicationay
value က python data type ႀကက္တာျ စ္ပနိုင္ ပတမ္္။ dictionary ေတြက unordered key-
value-pairs ေတြျ စ္ ပတမ္္။

Dictionary ေတြက string , list , tuple ေတြလို sequence operation လို ္မအရ ပဘး ္။

Examples of Dictionaries

Dictionary အလြတ္တစ္ ို
>>> empty = {}
>>> empty
{}
Eg continue
>>> food = {"ham" : "yes", "egg" : "yes", "spam" : "no" }
>>> food
{'egg': 'yes', 'ham': 'yes', 'spam': 'no'}
>>> food["spam"] = "yes"
>>> food
{'egg': 'yes', 'ham': 'yes', 'spam': 'yes'}
>>>
German-English dictionary:
# -*- coding: iso-8859-1 -*-

en_de = {"red" : "rot", "green" : "grün", "blue" : "blau", "yellow":"gelb"}


print en_de
print en_de["red"]
မline က german စကားလံိုးေတြအတြက္ ပ္။ ေ း ားတဲာ့ code type ပနဲာ့ save ေ းအရ ပမမ္္။

German-french
# -*- coding: iso-8859-1 -*-

en_de = {"red" : "rot", "green" : "grün", "blue" : "blau", "yellow":"gelb"}


print en_de
print en_de["red"]
de_fr = {"rot" : "rouge", "grün" : "vert", "blau" : "bleu", "gelb":"jaune"}
print "The French word for red is: " + de_fr[en_de["red"]]

Python2(ဘာသာျ ပန္) Han Phyo Oo 52


value ကိုႀကဳေက္တာ့ဲ data type ားပနိုင္ေ မမ္ာ့ key အတြက္ေတာာ့ ကပန္ာ့သတ္ က္ေတြအရ ပတမ္္။
Immutable data type ေတြကို ဲ key အေပနပနဲာ့သံိုးပနိုင္ ပတမ္္။ Mutable data type သံိုးအရင္
error ေ း ပလမ္ာ့မမ္္။
>>> dic = { [1,2,3]:"abc"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
Tuples ေတြကိုလည္း key အေပနပနဲာ့သံိုးပနိုင္ ပတမ္.
>>> dic = { (1,2,3):"abc", 3.1415:"abc"}
>>> dic
{3.1415: 'abc', (1, 2, 3): 'abc'}

More
# -*- coding: iso-8859-1 -*-

en_de = {"red" : "rot", "green" : "grün", "blue" : "blau", "yellow":"gelb"}


de_fr = {"rot" : "rouge", "grün" : "vert", "blau" : "bleu", "gelb":"jaune"}

dictionaries = {"en_de" : en_de, "de_fr" : de_fr }


print dictionaries["de_fr"]["blau"]

Operators on Dictionaries

Operator Explanation
len(d) returns the number of stored entries, i.e. the number of (key,value) pairs.
del d[k] deletes the key k together with his value
k in d True, if a key k exists in the dictionary d
k not in d True, if a key k doesn't exist in the dictionary d

Accessing non Existing Keys

မအရတဲာ့ key ကို access လို ္အရင္ error ျ ပလမ္ာ့မမ္.


>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'

“in” operator ပနဲန္႔ error မတတ္ေအာင္လို ္ပနိုင္ ပတမ္္။


>>> if "car" in words: print words["car"]
...
>>> if "cat" in words: print words["cat"]
...
Katze

Python2(ဘာသာျ ပန္) Han Phyo Oo 53


Important Methods

Dictionary ေတြကို copy() method သံိုးျ ါး ကးပနိုင္ ပတမ္္။


>>> w = words.copy()
>>> words["cat"]="chat"
>>> print w
{'house': 'Haus', 'cat': 'Katze'}
>>> print words
{'house': 'Haus', 'cat': 'chat'}

Clear() method ပနဲd


န္႔ ictionary အရ
ဲ တာေတြအရင္းပနိုင္ ပတမ္္။ dictionary ကို က္တာ မဟိုတ္ေ မဲာ့
empty dictionary ျ စ္သြား ပတမ္္။
>>> w.clear()
>>> print w
{}

Update: Merging Dictionaries

Dictionary ေတြကိုေ ပင္းစ ္ပနိုင္ ပတမ္္။ key တတာေတြ ပအရင္ေတာာ့ over write လို ္မာ ပ္။
>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w1 = {"red":"rouge","blau":"bleu"}
>>> w.update(w1)
>>> print w
{'house': 'Haus', 'blau': 'bleu', 'red': 'rouge', 'cat': 'Katze'}

Iterating over a Dictionary

Dictionary ေတြကို iterate လို ္ ိုန္႔ သါးသပန္ာ့ method ေတြမလို ပဘး


for key in d:
print key
iterkeys()ကိုေတာာ့သံိုးပနိုင္ ပတမ္္။
for key in d.iterkeys():
print key
values ေတြအတြက္ဆိုအရင္ေတာာ့ itervalues() method ကအသံိုး၀င္ ပတမ္္။
for val in d.itervalues():
print val
အတတ ပ ဲ
for key in d:
print d[key]

Python2(ဘာသာျ ပန္) Han Phyo Oo 54


Connection between Lists and Dictionaries

List ကေပန dictionary ၊ dictionary ကေပန list ေျ ာင္းတာေတြလို ္ပနို္င္ ပတမ္္။

dictionary
{"list":"Liste", "dictionary":"Wörterbuch", "function":"Funktion"}

List
[("list","Liste"),("dictionary","Wörterbuch"), ("function","Funktion")]

Lists from Dictionaries

Items(),keys(),values() methods ေတြသံိုးျ ါး dictionary ကေပန list ေျ ာင္းလဲပနိုင္ ပတမ္္။


>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w.items()
[('house', 'Haus'), ('red', 'rot'), ('cat', 'Katze')]
>>> w.keys()
['house', 'red', 'cat']
>>> w.values()
['Haus', 'rot', 'Katze']

Dictionary from list

ဟင္း ဲြေတြပနာ့ဲ သက္ဆိုင္အရာ ပနိုင္ငံ list ႏွာစ္ ိုအရမမ္္။


>>> dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
>>> countries = ["Italy", "Germany", "Spain", "USA"]

Zip() method သံိုးျ ါး list ႏွာစ္ ိုေ ပင္း မမ္


>>> country_specialities = zip(countries, dishes)
>>> print country_specialities
[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'),
('USA', 'Hamburger')]
>>>
အ ို country_specialities အ မ
ဲ ာ 2-tuple list ံိုစံအရေပနမမ္္။ဒါ ိုစ
ံ ံကေပန dictionary အျ စ္ dict()
function သံိုးျ ါးေျ ာင္းမမ္္။
>>> country_specialities_dict = dict(country_specialities)
>>> print country_specialities_dict
{'Germany': 'sauerkraut', 'Spain': 'paella', 'Italy': 'pizza', 'USA':
'Hamburger'}
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 55


Zip() function ပနဲာ့ တ္သတ္ျ ါး ေမးစအရာအရတာက list တစ္ ိုကတစ္ျ ားတစ္ ို က္ element
ေတြ ိုေပနအရင္ဘာျ စ္မလဲ/ list size မတအရင္ဘာျ စ္မလဲေ ပာ့္။ လြမ္ ပတမ္
ိုေပနတဲာ့ဘက္ကဟာေတြ မသံိုး ပဘး္။
>>> countries = ["Italy", "Germany", "Spain", "USA", "Switzerland"]
>>> dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
>>> country_specialities = zip(countries,dishes)
>>> print country_specialities
[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'),
('USA', 'Hamburger')]

Python2(ဘာသာျ ပန္) Han Phyo Oo 56


Chapter 17
Sets and Frozensets

Sets in Python

“set” data type က collection type ျ စ္ျ ါးေတာာ့ python 2.4 ကစ ပလာ ပတမ္္။ set မ
ဲ ာ
immutable object ေတြ ပ ပတမ္္။ Set data type က mathematic set ကို python အေပနပနဲာ့
အသံိုးျ ဳေပနိုင္ေအာင္ေအရးသား ားတာ ဲျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ set မာ list ေတြ tuple ေတြလို
element ေတြ မ ္ ပဘး္။

Creating Sets

Set တစ္ ို ပန္တါး င္အရင္ sequence တစ္ ို သိုန္႔ Iterable obect တစ္ ိုကို set function သံိုးျ ါး
ပန္တါးပနင္ ပတမ္္။
>>> x = set("A Python Tutorial")
>>> x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'])
>>> type(x)
<type 'set'>
>>>

List ေတြလည္း set function မ


ဲ ာသံိုးပနိုင္ ပတမ္္။
>>> x = set(["Perl", "Python", "Java"])
>>> x
set(['Python', 'Java', 'Perl'])
>>>

တညါတဲာ့ item/element ေတြ ပအရင္ဘာျ စ္မလဲႀကည္ာ့ႀကည္ာ့ ပ္။


>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
>>> cities
set(['Paris', 'Birmingham', 'Lyon', 'London', 'Berlin'])
>>>
္တဲာ့ data ေတြေ ာက္သာြ းတာေတြန္႔မာ ပ္။

Immutable Sets

Set မ
ဲ ာ mutable object ေတြ ပလိုန္႔မအရ ပဘး္။ eg.
>>> cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
>>> cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 57


Frozensets

Set မ
ဲ ာ mutable Object ပလိုန္႔မအရေ မမ္ာ့္။ set ကေတာာ့ mutable ျ စ္ ပတမ္္။
>>> cities = set(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
>>> cities
set(['Freiburg', 'Basel', 'Frankfurt', 'Strasbourg'])
>>>

Frozen set ကေတာာ့ ေျ ာင္းလဲလိုန္႔မအရတာကလြလ


ဲ ိုန္႔ set ပနဲာ့အတတ ပ ္။ဲ
>>> cities = frozenset(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>

Simplified Notation

Python 2.6 ကေပနစျ ါးေတာာ့ set function မသံိုး ဲ set ေတြ ပန္တါးပနိုင္ ပတမ္္။ {}သံိုး ပတမ္္။
>>> adjectives = {"cheap","expensive","inexpensive","economical"}
>>> adjectives
set(['inexpensive', 'cheap', 'expensive', 'economical'])
>>>

Set Operations

add(element)

element ေတြ ္ေ ပင္း င္အရင္သံိုး ပတမ္္။


>>> colours = {"red","green"}
>>> colours.add("yellow")
>>> colours
set(['green', 'yellow', 'red'])
>>> colours.add(["black","white"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
ပနဂိုအရျ ါးသား data ပနဲာ့တေပန ာ ္ ည္ာ့အရင္ေတာာ့ ဘာမျ စ္မာမဟိုတ္ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 58


clear()

set ဲက elements ေတြအရင္း င္အရင္သံိုး ပတမ္္။


>>> cities = {"Stuttgart", "Konstanz", "Freiburg"}
>>> cities.clear()
>>> cities
set([])
>>>

copy

shallow copy လို ္ေ း ပတမ္.


>>> more_cities = {"Winterthur","Schaffhausen","St. Gallen"}
>>> cities_backup = more_cities.copy()
>>> more_cities.clear()
>>> cities_backup
set(['St. Gallen', 'Winterthur', 'Schaffhausen'])
>>>
Assignment operator ေလးသံိုးမံိုပနာ့အရ
ဲ တမ္ င္ ပလမ္ာ့မမ္္။
>>> more_cities = {"Winterthur","Schaffhausen","St. Gallen"}
>>> cities_backup = more_cities
>>> more_cities.clear()
>>> cities_backup
set([])
"cities_backup = more_cities"ဆိုတဲာ့ statement က data တစ္ေပနအရာ ည္းကို ဲ
ညႊပန္းေ းသြား တာျ စ္ ပတမ္္။

difference()

set ေတြႀကား က
ဲ ျ ားပနားမကို set အသစ္တစ္ ိုအေပနပနဲာ့ ိုတ္ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> z = {"c","d"}
>>> x.difference(y)
set(['a', 'e', 'd'])
>>> x.difference(y).difference(z)
set(['a', 'e'])
>>>
“-“ operator သံိုးလည္းအရ ပတမ္္။
>>> x - y
set(['a', 'e', 'd'])
>>> x - y - z
set(['a', 'e'])
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 59


difference_update()

Set တစ္ ို ဲက element ကို အျ ား set တစ္ ို ဲက element ေတြ မ္ျ င္အရင္သံိုး ပတမ္ ္။

x=x-y ပနဲာ့တ ပတမ္္။


>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> x.difference_update(y)
>>>
>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> x = x - y
>>> x
set(['a', 'e', 'd'])
>>>

discard(el)

element တစ္ ိုကို set က


ဲ ေပန မ္အရား င္အရင္သံိုး ပတမ္္။ မ ပအရင္ေတာာ့ ဘာမမျ စ္ ပဘး္။
>>> x = {"a","b","c","d","e"}
>>> x.discard("a")
>>> x
set(['c', 'b', 'e', 'd'])
>>> x.discard("z")
>>> x
set(['c', 'b', 'e', 'd'])
>>>

remove(el)

discard() ပနဲာ့တ ပတမ္္။ ဒပေ မမ္ာ့ သက မ္ င္တာ့ဲ element မ ပအရင္ KeyError ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> x.remove("a")
>>> x
set(['c', 'b', 'e', 'd'])
>>> x.remove("z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>

intersection(s)

Set ေတြႀကား တညါမေတြကို set အသစ္လို ္ေ း ပတမ္္။


>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}

Python2(ဘာသာျ ပန္) Han Phyo Oo 60


>>> x.intersection(y)
set(['c', 'e', 'd'])
>>>
“&” operator သံိုးလည္းအရ ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x.intersection(y)
set(['c', 'e', 'd'])
>>>
>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x & y
set(['c', 'e', 'd'])
>>>

isdisjoint()

Set ႏွာစ္ ို intersection (တညါတဲာ့ element) မ ပအရင္ True ိုတ္ေ း ပတမ္္။

issubset()

x.issubset(y) က True ိုတ္ေ း ပလမ္ာ့မမ္္။ x က y အရဲာ့ subset ဆိုအရင္ေ ပာ့ ္။ "<=" ဆိုအရင္
subset of “>=” ဆိုအရင္ superset of “<” ကေတာာ့ subset ျ စ္မျ စ္စစ္ င္အရင္သံိုး ပတမ္္။ eg
က ိုအရင္း ပလမ္ာ့မမ္္။
>>> x = {"a","b","c","d","e"}
>>> y = {"c","d"}
>>> x.issubset(y)
False
>>> y.issubset(x)
True
>>> x < y
False
>>> y < x # y is a proper subset of x
True
>>> x < x # a set can never be a proper subset of oneself.
False
>>> x <= x
True
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 61


issuperset()

သကေတာာ့ super set အတြက္ ပ္။


>>> x = {"a","b","c","d","e"}
>>> y = {"c","d"}
>>> x.issuperset(y)
True
>>> x > y
True
>>> x >= y
True
>>> x >= x
True
>>> x > x
False
>>> x.issuperset(x)
True
>>>

pop()

Set element ေတြကိုတစ္ ို င္း ိုတ္ေ း မ္ေ း ပတမ္္။ Empty ျ စ္သာြ းအရင္ေတာာ့ KeyError
ိုတ္ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> x.pop()
'a'
>>> x.pop()
'c'

Python2(ဘာသာျ ပန္) Han Phyo Oo 62


Chapter 18
Shallow and Deep Copy

Data Types and Variables အ ပန္းမာေျ ာ ဲာ့သလို integer / string ေတြလို data type
အရိုးအရိုးေလးေတြ assignment လို ္တာ copy လို ္တာမာ တစ္ျ ား programming language
ေတြပနဲာ့စာအရင္ python မာ ျ ားတဲာ့ ံိုစံေတြအရ ပတမ္္။ shallow ပနဲာ့ deep copying ကေတာာ့ list
လို class instance(object) လို object မ
ဲ ာ object ပတာေတြမာ အသံိုးျ ဳေ ိုန္႔သင္န္႔ေတာ္ ပတမ္္။

ေအာက္မာျ ားသလို y က x ပနဲန္႔ memory location တစ္ေပနအရာ က


ဲ ျ ေပန ပတမ္္။ y
ကတ
ို စ္ျ ားတပန္ ိုး ေျ ာင္းလိုက္အရင္ေတာာ့ ေပနအရာေျ ာင္းသြား ပတမ္္။ "Data Types and
Variables" ပန္းမာေျ ာသလို Y ကmemory ေပနာက္တစ္ေပနအရာအရသြား ပတမ္္။
>>> x = 3
>>> y = x
အတြင္း ိုင္း(internal) လို ္ေဆာင္ က္ေတြ က းဆပန္းေ မဲာ့ , ဘာ result
အရလာမမ္ဆိုတာေတာာ့ သပနိုင္ ပတမ္္။list လို dictionary လို mutable object ေတြ copy
လို ္အရင္ေတာာ့ ျ ပနာကေတာာ့အရပနင္ ပတမ္္။

Programmer ကေတာင္းဆိုမသာ တကမ္ copy ကးေ းမာျ စ္ ပတမ္္။

List ေတြ dictionary လို က mutable object ေတြ copy လို ္အရင္ဘာျ စ္မလဲႀကည္ာ့အရေအာင္

Copying a list
>>> colours1 = ["red", "green"]
>>> colours2 = colours1
>>> colours2 = ["rouge", "vert"]
>>> print colours1
['red', 'green']
colours1 က
ဲ ို list တစ္ ိုျ း ည္ာ့ colour2 ဲကို colour1 assign လို ္ ား ပတမ္္။ ျ ါးေတာာ့
colour2 က
ဲ ို list အသစ္တစ္ ို assign လို ္ ပတမ္္။

ေမ ာ္လင္ာ့ ားသလို ဲ colour1 တပန္ ိုးကမေျ ာင္း ပဘး္။ "Data types and variables" တိုပန္းက
လို ဲ colours2 အတြက္ memory location အသစ္တစ္ ိုေ းသြား ပတမ္္။ ဘာလိုန္႔လဆ
ဲ ိုေတာာ့
ကြ ပန္ေတာ္တိုန္႔ colours2 ကို assign ္လို ္လို္က္တာက list အသစ္တစ္ ိုျ စ္ေပနလိုန္႔ ပ္။
>>> colours1 = ["red", "green"]
>>> colours2 = colours1
>>> colours2[1] = "blue"
>>> colours1
['red', 'blue']
ဒါမာေမးစအရာစလာ ပျ ါ္။ colour2 သိုန္႔ colour1 ဲက element တစ္ ိုကိုေျ ာင္းလိုက္အရင္ေအရာ?

Python2(ဘာသာျ ပန္) Han Phyo Oo 63


ဒါအေ ခက example မာ colour2 အရဲာ့ ဒိုတမ element ကို တပန္ ိုးအသစ္ေျ ာင္းလိုက္ ပတမ္္။
colour1 အရဲာ့ list လဲေျ ာင္းလဲသာြ းတာကိုလည္းေတြန္႔ ပလမ္ာ့မမ္္။

List အသစ္တစ္ ို assign လို ္တာမဟိုတ္ ဲ္။ list ဲက element တစ္ ိုကို ဲ
ေျ ာင္းလိုက္တာေႀကာင္ာ့ ျ စ္ ပတမ္္။

Copy with the Slice Operator

List ေတြ copy ကး ိုန္႔ slice operator ကိုသံိုးပနိုင္ ပတမ္္။


>>> list1 = ['a','b','c','d']
>>> list2 = list1[:]
>>> list2[1] = 'x'
>>> print list2
['a', 'x', 'c', 'd']
>>> print list1
['a', 'b', 'c', 'd']
>>>
ဒပေ မမ္ာ့ list မာ sublist ေတြ ပလာအရင္ေတာာ့ ျ ပနာအရတိုပန္း ပ ဲ ္။ sublist ေတြအရဲာ့ pointer
ေတြ ဲ ပလာတာမိုန္႔ ပ္။
>>> lst1 = ['a','b',['ab','ba']]
>>> lst2 = lst1[:]
Lists ေတြအရဲာ့ element တစ္ ိုျ င္းကို ျ င္အရင္ ျ ပနာမအရေ မမ္ာ့ ္။ sublist ဲက element
တစ္ ိုကို ေျ ာင္းလဲမမ္ဆိုအရင္ေတာာ့ ျ ပနာအရ ပတမ္္။
>>> lst1 = ['a','b',['ab','ba']]
>>> lst2 = lst1[:]
>>> lst2[0] = 'c'
>>> lst2[2][1] = 'd'
>>> print(lst1)
['a', 'b', ['ab', 'd']]
Using the Method deepcopy from the Module copy

ဒါလိုမျ စ္ေအာင္ “copy” module ကိုသံိုးအရ ပမမ္္။ သန္႔မာ list ေတြအတြက္ “copy” method
ပ ပတမ္္။
from copy import deepcopy
lst1 = ['a','b',['ab','ba']]
lst2 = deepcopy(lst1)
lst2[2][1] = "d"
lst2[0] = "c";
print lst2
print lst1

file ကို save ျ ါး cmd မာ runႀကည္ာ့ ပ္။


$ python deep_copy.py
['c', 'b', ['ab', 'd']]
['a', 'b', ['ab', 'ba']]

Python2(ဘာသာျ ပန္) Han Phyo Oo 64


Chapter 19
Functions

Syntax

Function ေတြကေတာာ့ structure program ေတြအတြက္ construct (ideal element


)ေတြျ စ္ ပတမ္္။ subroutines or procedure လိုန္႔လည္းေ ခႀက ပတမ္္။ function ေတြမသံိုး ဲ
code ေတြျ ပန္သံိုး င္အရင္ေတာာ့ copy paste လို ္မ ဲအရ ပမမ္္။

Python မာ function ကို def statement ပနဲန္႔သတ္မတ္ ပတမ္္။


def function-name(Parameter list):
statements, i.e. the function body

Parameter list ကေတာာ့ ဘာမမ ပတာျ စ္ပနိုင္လို တစ္ ို က္ ိုတာလဲျ စ္ပနိုင္ ပတမ္္။ function
call လို ္အရင္ parameter ေတြကို argument လိုန္႔လည္းေ ခ ပတမ္္။ function body မ
ဲ ာေတာာ့
indent လို ္ ားတဲန္႔ statement ေတြ ပ ပတမ္္။ function call လို ္တိုင္း function body ဲက
statement ေတြ execute လို ္ ပတမ္္။ paramameter ေတြက mandatory(မ ပမျ စ္)
ျ စ္ပနင္သလို optional(ေအရြး မ္ပနိုင္) လည္းျ စ္ပနိုင္ ပတမ္္။ optional parameter ေတြက
mandatory parameter ေပနာက္မာအရအရ ပမမ္္။

Function body မာ return statement ပပနိုင္ ပတမ္္။ function body


မည္ာ့သည္ာ့ ေပနအရာမာမဆို ျ စ္ပနိုင္ ပတမ္္။ return statement ေအရာက္အရင္ function call execution
ကိုအရ ္ျ ါး result (အရလဒ္) ကို return ျ ပန္ေ း ပတမ္္။ return statement မ ပအရင္ေတာာ့ function
body အဆံိုးေအရာက္အရင္ function အဆံိုးသတ္ ပတမ္္။
>>> def add(x, y):
... """Return x plus y"""
... return x + y
...
>>>
Function သတ္မတ္ျ ါး ပျ ါ္။ ျ ပန္သိုးံ ႀကည္ာ့ ပမမ္္။
>>> add(4,5)
9
>>> add(8,3)
11
>>>

Example of a Function with Optional Parameters


>>> def add(x, y=5):
... """Return x plus y, optional"""
... return x + y
...

Python2(ဘာသာျ ပန္) Han Phyo Oo 65


>>>

Function call ျ ပန္လို ္မမ္္။


>>> add(4)
9
>>> add(8,3)
11
>>>

Docstring

Function body အရဲာ့ မဆံိုး statement က string တစ္ေႀကာင္း ားတတ္ ပတမ္္။ အဲာ့ဒါ string
ကို function_name.__doc_ ပနဲန္႔အရမသံိုးစြဲပနိုင္ ပတမ္္။ Docstring လိုန္႔ေ ခ ပတမ္္။
>>> execfile("function1.py")
>>> add.__doc__
'Returns x plus y'
>>> add2.__doc__
'Returns x plus y, optional'
>>>

Keyword Parameters

Fuction call လို ္အရာမာ Keyword parameter ေတြအသံိုးျ ဳေပနိုင္ ပတမ္္။


def sumsub(a, b, c=0, d=0):
return a - b + c - d
Keyword parameter ေတြက positional argument အျ စ္မသံိုးတာေတြ ဲျ စ္ပနိုင္ ပတမ္္။
>>> execfile("funktion1.py")
>>> sumsub(12,4)
8
>>> sumsub(12,4,27,23)
12
>>> sumsub(12,4,d=27,c=23)
4

Arbitrary Number of Parameters

Parameter အေအရအတြက္ဘမ္ေလာက္ျ စ္မမ္ဆိုတာ ေျ ာမအရပနိုင္တန္႔အ


ဲ ေျ အေပနျ စ္ပနိုင္ ပတမ္္။
ဒပကို tuple reference သံိုးျ ါးေျ အရင္းပနိုင္ ပတမ္္။ “*” ကို tuple reference အျ စ္သတ္မတ္အရာမာ
သံိုး ပတမ္္။ C မာ ေတာာ့ “*” ကို pointer အေပနပနဲန္႔သံိုး ပတမ္္။
def arbitrary(x, y, *more):
print "x=", x, ", y=", y
print "arbitrary: ", more
x,y ကေတာာ့ ံိုမပန္ parameter ေတြျ စ္ျ ါးေတာာ့ *more ကေတာာ့ tuple reference ျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 66


>>> execfile("funktion1.py")
>>> arbitrary(3,4)
x= 3 , x= 4
arbitrary: ()
>>> arbitrary(3,4, "Hello World", 3 ,4)
x= 3 , x= 4
arbitrary: ('Hello World', 3, 4)

Python2(ဘာသာျ ပန္) Han Phyo Oo 67


Chapter 20
Recursive Functions

Definition

Recursive ဆိုတာကေတာာ့ latin verb “recurrere”ကေပနဆင္းသက္လာျ ါးေတာာ့ “ျ ပန္လာတမ္”


ဆိုတဲာ့ အဓ ၸာမ္အရ ပတမ္္။ recursive function ဆိုတာလည္းဒါသေဘာ ပ ဲ function တစ္ ိုက
မမကိုမ္တိုင္ ကို function call ျ ပန္လို ္အရင္ recursive ျ စ္တမ္ေျ ာအရ ပမမ္္။
n! = n * (n-1)!, if n > 1 and f(1) = 1

Definition of Recursion

Function တစ္ ိုက မမကိုမ္ကို function call ျ ပန္လို ္မမ္္။ function call လို ္တဲာ့ value ကို
return ျ ပန္ေ း ပတမ္္။

Termination condition:

Recursive သံိုးအရင္ အဆံိုးသတ္ေ း (ိုန္႔ terminate) လို ္ေ း န္႔လ


ို ို ပတမ္္။ သတ္မတ္ ားတဲာ့
အေျ အေပနတစ္ ိုမာ recursive function အဆံိုးသတ္ ပတမ္ base case လိုန္႔ေ ခတမ္္။
function call လို ္တဲာ့အ ပ base case မာ သတ္မတ္ ားတဲာ့
အေျ အေပနမေအရာက္ပနိုငဘ
္ းဆိုအရင္ ေတာာ့ infinite loop ျ စ္သာြ း ပလမ္ာ့မမ္္။
Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1

အစား ိုး
4! = 4 * 3 * 2 * 1

ေမဘမ ေျ ာအရင္ recursive ဆိုတာက ျ ပနာတစ္ ိုကို


အ ိုင္းေလးေတြ ဲြေျ အရင္းတာျ စ္ ပတမ္္။

Recursive Functions in Python

Python မာ implementation လို ္မမ္ဆိုအရင္ေတာာ့


def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

Python2(ဘာသာျ ပန္) Han Phyo Oo 68


ဘမ္လိုအလို ္လို ္တမ္သအရေအာင္ Print function ေလးေတြ ည္ာ့ႀကည္ာ့မမ္္။
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "):
",res)
return res

print(factorial(5))

result က
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120

Factorial ကို iterative ပနဲန္႔ေအရးႀကည္ာ့မမ္္။


def iterative_factorial(n):
result = 1
for i in range(2,n+1):
result *= i
return result

The Pitfalls of Recursion

Fibonacci numbersေတြကေတာာ့
0,1,1,2,3,5,8,13,21,34,55,89, .

သတိုန္႔ကိုသတ္မတ္တာကေတာာ့
Fn = Fn-1 + Fn-2
with F0 = 0 and F1 = 1

Fibonacci ကို fibonacci လိုန္႔လသမ ားတဲာ့ သ ာ်ာၤ ညာအရင္ Leonardo of Pisa


ပနာမည္ေ း ားတာ ပ္။ သန္႔အရန္႔ဲ "Liber Abaci" (publishes 1202) စာအို ္ မ
ဲ ာ မိုပန္

Python2(ဘာသာျ ပန္) Han Phyo Oo 69


ေတြပနဲန္႔ တ္သတ္ျ ါး ေလာ့က င္ာ့ ပန္း အေပနပနဲာ့ ကပန္းစစ္တပန္းတစ္ ိုေ ာ္ျ ဲာ့ ပတမ္္။ modern
mathematic sequences ေတြက F0=0 ကစေ မဲာ့ သန္႔အရာ့ဲ Fibonacci sequence မာေတာာ့ F1=1
ကေပနစ ပတမ္္။

မိုပန္ေ ပက္ ာြ းမျ ပနာေလးအတြက္ အေျ အေပနက

 မိုပန္ ါးတစ္ေကာင္ မိုပန္မတစ္ေကာင္ကေပနစမမ္


 အသက္တစ္လ မာမတ္လို္က္မမ္ ဒိုတမလမာ မိုပန္ေပနာ ္တစ္စံို( ါး/မ) ္တိုးမမ္္။
 မိုပန္ေတြကမေသဘး
 မိုပန္တစ္စံိုတိုင္း( ါး/မ) တစ္စံိုတိုင္းက ဒိုတမလ ကေပနစျ ါးေတာာ့ လတိုင္း တစ္စံို
္ေ ပာက္မမ္္။

Fibonacci number ကေတာာ့ n month ျ ါးအရင္အရတဲာ့ မိုပန္ အစံိုအေအရအတြက္ ပျ စ္ ပတမ္္။ ၁၀


လဆိုအရင္ F10ျ စ္ ပတမ္္။
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

iterative solution
def fibi(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
fibi() က fib() က္ ိုျမပန္ ပတမ္္။ ဘမ္ေလာက္ျမပန္လသ
ဲ င္အရင္ timeit module သံိုးအရ ပမမ္္။
from timeit import Timer
from fibo import fib

t1 = Timer("fib(10)","from fibo import fib")

for i in range(1,41):
s = "fib(" + str(i) + ")"
t1 = Timer(s,"from fibo import fib")
time1 = t1.timeit(3)
s = "fibi(" + str(i) + ")"
t2 = Timer(s,"from fibo import fibi")
time2 = t2.timeit(3)
print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i,
time1, time2, time1/time2))
time1 ကေတာာ့ fib() အတြက္ time2 ကေတာာ့ fibi() အတြက္ျ စ္ ပတမ္္။ result ကိုႀကည္ာ့အရင္
fib(20) ကို ၃ ပေ ခအရင္ 14 milliseconds ႀကာတမ္္။ fibi(20) ကေတာာ့ ၃ ႀကမ္ေ ခအရာမာ 0.011
milliseconds ဲလို ပတမ္္။ ဒပေႀကာင္ာ့ fibi(20) က fib(20) က္ အဆ ၁၃၀၀ ျမပန္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 70


fib(40) ကသံိုးႀကမ္အတြက္ 215 second ႀကာ ပတမ္္။ fibi(40)ကေတာာ့ 0.016 milisecond
ဲလို ပတမ္္။ fibi(40) က fib(40) က္ 13 millions ဆျမပန္ ပတမ္္။
n= 1, fib: 0.000004, fibi: 0.000005, percent: 0.81
n= 2, fib: 0.000005, fibi: 0.000005, percent: 1.00
n= 3, fib: 0.000006, fibi: 0.000006, percent: 1.00
n= 4, fib: 0.000008, fibi: 0.000005, percent: 1.62
n= 5, fib: 0.000013, fibi: 0.000006, percent: 2.20
n= 6, fib: 0.000020, fibi: 0.000006, percent: 3.36
n= 7, fib: 0.000030, fibi: 0.000006, percent: 5.04
n= 8, fib: 0.000047, fibi: 0.000008, percent: 5.79
n= 9, fib: 0.000075, fibi: 0.000007, percent: 10.50
n=10, fib: 0.000118, fibi: 0.000007, percent: 16.50
n=11, fib: 0.000198, fibi: 0.000007, percent: 27.70
n=12, fib: 0.000287, fibi: 0.000007, percent: 41.52
n=13, fib: 0.000480, fibi: 0.000007, percent: 69.45
n=14, fib: 0.000780, fibi: 0.000007, percent: 112.83
n=15, fib: 0.001279, fibi: 0.000008, percent: 162.55
n=16, fib: 0.002059, fibi: 0.000009, percent: 233.41
n=17, fib: 0.003439, fibi: 0.000011, percent: 313.59
n=18, fib: 0.005794, fibi: 0.000012, percent: 486.04
n=19, fib: 0.009219, fibi: 0.000011, percent: 840.59
n=20, fib: 0.014366, fibi: 0.000011, percent: 1309.89
n=21, fib: 0.023137, fibi: 0.000013, percent: 1764.42
n=22, fib: 0.036963, fibi: 0.000013, percent: 2818.80
n=23, fib: 0.060626, fibi: 0.000012, percent: 4985.96
n=24, fib: 0.097643, fibi: 0.000013, percent: 7584.17
n=25, fib: 0.157224, fibi: 0.000013, percent: 11989.91
n=26, fib: 0.253764, fibi: 0.000013, percent: 19352.05
n=27, fib: 0.411353, fibi: 0.000012, percent: 34506.80
n=28, fib: 0.673918, fibi: 0.000014, percent: 47908.76
n=29, fib: 1.086484, fibi: 0.000015, percent: 72334.03
n=30, fib: 1.742688, fibi: 0.000014, percent: 123887.51
n=31, fib: 2.861763, fibi: 0.000014, percent: 203442.44
n=32, fib: 4.648224, fibi: 0.000015, percent: 309461.33
n=33, fib: 7.339578, fibi: 0.000014, percent: 521769.86
n=34, fib: 11.980462, fibi: 0.000014, percent: 851689.83
n=35, fib: 19.426206, fibi: 0.000016, percent: 1216110.64
n=36, fib: 30.840097, fibi: 0.000015, percent: 2053218.13
n=37, fib: 50.519086, fibi: 0.000016, percent: 3116064.78
n=38, fib: 81.822418, fibi: 0.000015, percent: 5447430.08
n=39, fib: 132.030006, fibi: 0.000018, percent: 7383653.09
n=40, fib: 215.091484, fibi: 0.000016, percent: 13465060.78

recursion မာဘာေတြမားေပနလဲ binary tree ဆြဲႀကည္န္႔အရင္ subtree ေတြကို ္ ပ ္ ပတြက္


ားတာကိုေတြန္႔မာျ စ္ ပတမ္္။ recursion
မာတြက္ျ ါးသားေတြကိုမတ္မ ားတဲာ့အတြက္ ျ စ္ ပတမ္္။

တြက္ျ ါးသားေတြမတ္မပနိုင္ေအာင္ “memory” ကို dictionary သံိုးျ ါး implement


လို ္ပနိုင္ ပတမ္္။
memo = {0:0, 1:1}
def fibm(n):

Python2(ဘာသာျ ပန္) Han Phyo Oo 71


if not n in memo:
memo[n] = fibm(n-1) + fibm(n-2)
return memo[n]

fibi():မစ္ႀကည္ာ့အရေအာင္
from timeit import Timer
from fibo import fib

t1 = Timer("fib(10)","from fibo import fib")

for i in range(1,41):
s = "fibm(" + str(i) + ")"
t1 = Timer(s,"from fibo import fibm")
time1 = t1.timeit(3)
s = "fibi(" + str(i) + ")"
t2 = Timer(s,"from fibo import fibi")
time2 = t2.timeit(3)
print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i,
time1, time2, time1/time2))
iterative က္ေတာင္ ိုျမပန္တာေတြန္႔ ပလမ္ာ့မမ္္။
n= 1, fib: 0.000011, fibi: 0.000015, percent: 0.73
n= 2, fib: 0.000011, fibi: 0.000013, percent: 0.85
n= 3, fib: 0.000012, fibi: 0.000014, percent: 0.86
n= 4, fib: 0.000012, fibi: 0.000015, percent: 0.79
n= 5, fib: 0.000012, fibi: 0.000016, percent: 0.75
n= 6, fib: 0.000011, fibi: 0.000017, percent: 0.65
n= 7, fib: 0.000012, fibi: 0.000017, percent: 0.72
n= 8, fib: 0.000011, fibi: 0.000018, percent: 0.61
n= 9, fib: 0.000011, fibi: 0.000018, percent: 0.61
n=10, fib: 0.000010, fibi: 0.000020, percent: 0.50
n=11, fib: 0.000011, fibi: 0.000020, percent: 0.55
n=12, fib: 0.000004, fibi: 0.000007, percent: 0.59
n=13, fib: 0.000004, fibi: 0.000007, percent: 0.57
n=14, fib: 0.000004, fibi: 0.000008, percent: 0.52
n=15, fib: 0.000004, fibi: 0.000008, percent: 0.50
n=16, fib: 0.000003, fibi: 0.000008, percent: 0.39
n=17, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=18, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=19, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=20, fib: 0.000003, fibi: 0.000010, percent: 0.29
n=21, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=22, fib: 0.000004, fibi: 0.000010, percent: 0.40
n=23, fib: 0.000004, fibi: 0.000010, percent: 0.40
n=24, fib: 0.000004, fibi: 0.000011, percent: 0.35
n=25, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=26, fib: 0.000004, fibi: 0.000011, percent: 0.34
n=27, fib: 0.000004, fibi: 0.000011, percent: 0.35
n=28, fib: 0.000004, fibi: 0.000012, percent: 0.32
n=29, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=30, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=31, fib: 0.000004, fibi: 0.000012, percent: 0.34
n=32, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=33, fib: 0.000004, fibi: 0.000013, percent: 0.30
n=34, fib: 0.000004, fibi: 0.000012, percent: 0.34
n=35, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=36, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=37, fib: 0.000004, fibi: 0.000014, percent: 0.29

Python2(ဘာသာျ ပန္) Han Phyo Oo 72


n=38, fib: 0.000004, fibi: 0.000014, percent: 0.29
n=39, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=40, fib: 0.000004, fibi: 0.000014, percent: 0.29

Exercises

1. Think of a recusive version of the function f(n) = 3 * n, i.e. the multiples of 3


2. Write a recursive Python function that returns the sum of the first n integers.
(Hint: The function will be similiar to the factorial function!)
3. Write a function which implements the Pascal's triangle:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

4. You find further exercises on our Python3 version of recursive functions, e.g. creating the
Fibonacci numbers out of Pascal's triangle or produce the prime numbers recursively, using
the Sieve of Eratosthenes.

Solutions to our Exercises

1. Solution to our first exercise on recursion:


Mathematically, we can write it like this:
f(1) = 3,
f(n+1) = f(n) + 3

A Python function can be written like this:


2. def mult3(n):
3. if n == 1:
4. return 3
5. else:
6. return mult3(n-1) + 3
7.
8. for i in range(1,10):
9. print(mult3(i))
10. Solution to our second exercise:
11. def sum_n(n):
12. if n== 0:
13. return 0
14. else:
15. return n + sum_n(n-1)
16. Solution for creating the Pacal triangle:
17. def pascal(n):
18. if n == 1:
19. return [1]
20. else:
21. line = [1]
22. previous_line = pascal(n-1)
23. for i in range(len(previous_line)-1):

Python2(ဘာသာျ ပန္) Han Phyo Oo 73


24. line.append(previous_line[i] + previous_line[i+1])
25. line += [1]
26. return line
27.
28. print(pascal(6))

Alternatively, we can write a function using list comprehension:

def pascal(n):
if n == 1:
return [1]
else:
p_line = pascal(n-1)
line = [ p_line[i]+p_line[i+1] for i in range(len(p_line)-1)]
line.insert(0,1)
line.append(1)
return line

print(pascal(6))

Python2(ဘာသာျ ပန္) Han Phyo Oo 74


Chapter 21
Python Tests

Errors and Tests

Debugging and testing ဆိုတာလည္း programmer မ ားအ ပန္မ ားမ ားေ းအရတဲာ့ အဆင္ာ့ ပ ဲ္။
အမ ဳေးမ ဳေးေသာအေႀကာင္း အအရာေတြေ ခမတည္တာ့အ
ဲ တြက္ လည္း ဘမ္ေလာက္အ ပန္ေ းအရမမ္ာ့
ဆိုတာေျ ာအရ က္ ပတမ္္။

Kinds of Errors

Error အမ ်ဴးမ ဳေးအရ ပတမ္္။ typo error မ ဳေး စကားလံိုးေတြမားတာ က ပန္တာ ေတြကို syntactical
error လိုန္႔ေ ခ ပတမ္္။

Syntactical error ေတြကျ င္အရလြမ္ ပတမ္္။ Semantic error ကေတာာ့ စကားလံိုးေတြ


codeေတြက syntactically မပန္ေ မမ္ာ့ ကိုမ္လို င္သလိုအလို ္မလို ္တာေတြ ျ စ္တာေႀကာင္ာ့
အရာေ ြအရ က္ ပတမ္္။ စ မာ x ကို 1 တိုး င္တဲာ့အ ပ x+=1 လိုန္႔ေအရးအရမမ္ာ့အစား x=1
လိုန္႔ေအရးမတာမ ဳေး ္။example
x = int(input("x? "))
y = int(input("y? "))

if x > 10:
if y == x:
print("Fine")
else:
print("So what?")

တစ္ ိုပနဲန္႔တစ္ ို ္ ားတဲာ့ (nested) if statement ႏွာစ္ေႀကာင္းေတြန္႔ ပလမ္ာ့မမ္္။ syntactically


အအရေတာာ့မပန္ ပတမ္္။ ဒပေ မမ္ာ့ ေအရးတဲာ့သက “so what”ဆိုတာ ဲ ိုတ္ င္တမ္ဆိုမ ပ္။ x က 10
က္လည္းႀကါးမမ္ာ့ y ပနဲန္႔လည္းမတမ “so what”ကို ိုတ္ င္အရင္ေတာာ့ ေအာက္ ပ ံိုစံအတိုင္း ျ စ္အရ
ျ စ္အရ ပမမ္္။

x = int(input("x? "))
y = int(input("y? "))

if x > 10:
if y == x:
print("Fine")
else:
print("So what?")

ႏွာစ္ ိုစလံိုးက syntactically မပန္ ပတမ္္။ ဒပေ မမ္ာ့ တစ္ ိုက လို င္သလို
(semantic)အလို ္မလို ္ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 75


ေပနာက္တစ္ ိုႀကည္ာ့အရေအာင္
>>> for i in range(7):
... print(i)
...
0
1
2
3
4
5
6
>>>
Syntactically မပန္တာ့အ
ဲ တြက္ Error မတက္ ဲ run ပလမ္ာ့မမ္္။ ဒပေ မမ္ာ့ programmer
ကဘာကို output ိုတ္ေ း င္တာလဲ (semantic) ကိုမသပနိုင္ ပဘး္။ 1 to 7
ို ္ င္တာလည္းျ စ္ပနိုင္ ပတမ္္။ ဒါမာေတာာ့ ေအရးတဲာ့ သက range function
ကိုေသ ာမသ ပဘး္။

ဒပေႀကာင္ာ့ semantic error ကိုႏွာစ္မ ဳေး ြျဲ ားပနိုင္ ပတမ္္။

 language ေအရးသားတဲာ့ ံိုစံကိုပနားမလည္တာ


 Code ေတြေအရးတဲန္႔အ ပ logically မားတာ

Unit Tests

Code ေတြ က
ဲ တစ္စတ္တစ္ ိုင္းေတြျ စ္တာ့ဲ class ေတြ function ေတြ စမ္းအရင္သံိုး ပတမ္္။
သေဘာကေတာာ့ system ႀကါးကို unit ေလးေတြအျ စ္ ိုင္းျ ါး စစ္ေဆးတာျ စ္ ပတမ္္။ ဒါလို
စမ္းသ ္ ိုန္႔အတြက္ လည္း program ေတြကို စမ္းသ ္လိုန္႔အရတဲာ့ unit ေတြ ြျဲ ားအရ ပတမ္္။

Module Tests with __name__

Module တိုင္းမာ ပနာမည္ အရ ပတမ္္။ built in attribute တစ္ ိုျ စ္တာ့ဲ __name__ ပနဲန္႔သတ္မတ္
ား ပတမ္္။ xyz ဆိုတဲန္႔ module ေအရးျ ါး xyz.py လိုန္႔သမ္း ားတမ္ဆို ပစိုန္႔္။ “import xyz” ပနဲန္႔
import လို ္တဲာ့အ ပ __name__ က
ဲ ို xyz ဆိုတဲာ့ string ေအရာက္သြား ပတမ္္။ xyz.py ကို
standalone သံိုးမမ္ဆိုအရင္ေတာာ့
$python xyz.py
__name__ မ
ဲ ာအရမမမ္ာ့တပန္ ိုး က '__main__' ဆိုတဲာ့ string တပန္ ိုးျ စ္မာ ပ္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 76


ေအာက္ ပ Module က Fibonacci တပန္ ိုးတြက္ ိုန္႔ ပ္။ module ဘာလို ္တမ္ဆိုတာ
အေအရးေကါးတမ္ ေျ ာ င္တာမဟိုတ္ ပဘး္။ modul မ
ဲ ာ module test ဘမ္လိုလို ္တမ္
ဆိုတာ demonstration လို ္ျ င္လိုန္႔ ပ္။ module ကို standalone သံိုးတာလား import
လို ္တာလား ဆံိုးျ တ္ င္အရင္ _name_ က
ဲ တပန္ ိုးကိုစစ္အရ ပတမ္္။

ေအာက္ေ ာ္ျ ပ code ကို “fibonacci.py” ပနဲာ့သမ္း ပမမ္္။


def fib(n):
""" Calculates the n-th Fibonacci number iteratively """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a

def fiblist(n):
""" creates a list of Fibonacci numbers up to the n-th generation """
fib = [0,1]
for i in range(1,n):
fib += [fib[-1]+fib[-2]]
return fib
Python shell မာ ဒါModule ကိုစမ္း င္အရင္လည္းအရ ပတမ္္။
>>> from fibonacci import fib, fiblist
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fiblist(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fiblist(-8)
[0, 1]
>>> fib(-1)
0
>>> fib(0.5)
Traceback (most recent call last):
File "", line 1, in
File "fibonacci.py", line 6, in fib
for i in range(n):
TypeError: 'float' object cannot be interpreted as an integer
>>>
Positive integer ေတြ ဲဆိုအရင္ေတာာ့ မပန္ေပနတာ ေတြန္႔ ပလမ္ာ့မမ္္။ negative input ဆို fib
function က 0 return ျ ပန္ျ ါး fiblist က [0,1] ဲ return ျ ပန္ ပလမ္ာ့မမ္္။ float
ည္ာ့ေ းအရင္ေတာာ့ ႏွာစ္ ိုလံိုးက error ျ ပလမ္ာ့မမ္္။

Module test လို ္ ိုန္႔အတြက္ fib() ပနဲန္႔ fiblist() ကို ပနံ ပတ္ေတြပနဲrာ့ eturn
ေတြအသံိုးျ ဳေစစ္ေဆးပနိုင္ ပတမ္္။
if fib(0) == 0 and fib(10) == 55 and fib(50) == 12586269025:
print("Test for the fib function was successful!")
else:
print("The fib function is returning wrong values!")
standalone သံိုးအရင္ေအာက္ ပအတိုင္းျမင္အရ ပလ္မ္ာ့မမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 77


python fibonacci.py
Test for the fib function was successful!

Error ေတြ ည္ာ့ႀကည္န္႔အရေအာင္


a, b = 0, 1
ကို
a, b = 1, 1
fib function ကတြက္ေတာာ့တြက္ေ းေပနတိုပန္း ပ ဲ ္။ဒပေ မမ္ာ့ “n+1”အတြက္
တြက္ေ းေပနတာျ စ္တာ့ဲ အတြက္ေႀကာင္ာ့ call လို ္အရင္ေအာက္ ပအတိုင္းအရ ပလမ္ာ့မမ္္။
python fibonacci.py
"The fib function is returning wrong values!

ဒါလိုေအရး ားတာမေကာင္းတာတစ္ ိုအရ ပတမ္္။ module import လို ္အရင္ test


လို ္တာအဆင္ေျ ေႀကာင္း output အျမဲေတြန္႔ ပလမ္ာ့မမ္္။ ဒပေ မမ္ာ့ ကၽြပန္ေတာတိုန္႔ က module
import လို ္အရင္ ဒပကိုမျမင္ င္ ပဘး္။
>>> import fibonacci
Test for the fib function was successful!
အေႏွာာက္အမက္လည္းျ စ္သလို္။module import လို ္အရင္ silent ျ စ္ေပနသင္ာ့ ပတမ္္။

ဒပကိုေျ အရင္း င္အရင္ေတာာ့ _name_ ကိုစစ္အရ ပမမ္္။

def fib(n):
""" Calculates the n-th Fibonacci number iteratively """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a

def fiblist(n):
""" creates a list of Fibonacci numbers up to the n-th generation """
fib = [0,1]
for i in range(1,n):
fib += [fib[-1]+fib[-2]]
return fib

if __name__ == "__main__":
if fib(0) == 0 and fib(10) == 55 and fib(50) == 12586269025:
print("Test for the fib function was successful!")
else:
print("The fib function is returning wrong values!")
ဒပဆို module import လို ္အရင္ျမင္အရေတာာ့မာမဟိုတ္ ပဘး္။အအရင္းဆံိုး module test ပ ဲ
အေကာင္း ဆံိုးေတာာ့မဟိုတ္ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 78


doctest Module

unittest က္စာအရင္ doctest ကို အ


ို သံိုးမ ားႀက ပတမ္္။ python ပနဲန္႔တြဲ က္ ပ၀င္လာတဲာ့ test framework
ျ စ္ ပတမ္္။ doctest ကmodule အရဲာ့ documentation ဲမာ interactive python session ပနဲန္႔တတဲာ့
အစတ္အ င
ို ္းေတြအရာျ းါ ေတာာ့ run တာေတြတလားစစ္ ပလမ္ာ့မမ္္။ module document ဲမာ sample
run ားတာေလးေတြကို doctest ကျ ပန္စမ္းႀကည္န္႔ ျ ါး အေျ တမတ စစ္ေဆးတာျ စ္ ပတမ္္။
doctest ကိုသိုးံ န္႔ို import လို ္ေ းအရ ပမမ္္။ သက္ဆင
ို အရ
္ ာ function အရဲာ့ docstrin မ
ဲ ာ စမ္းသ တ
္ ဲာ့ python
interactive session ေတြ ည္ာ့ေ းအရ ပမမ္္။example
import doctest

def fib(n):
""" Calculates the n-th Fibonacci number iteratively """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
import လို ္ျ ါးစမ္းႀကည္ာ့ ပမမ္္။
>>> from fibonacci import fib
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>
စမ္း ားတဲာ့ တစ္ ိုလံိုးကို function အရဲာ့ docstring မ
ဲ ာ ည္ာ့ ပမမ္္။ test လို ္တဲာ့အ ပမာ module
ကို srandalone သံိုးအရင္ေတာာ့ testmod() ကို ေ ခေ းအရ ပမမ္္။
import doctest

def fib(n):
"""
Calculates the n-th Fibonacci number iteratively

>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>

"""
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a

if __name__ == "__main__":
doctest.testmod()

Python2(ဘာသာျ ပန္) Han Phyo Oo 79


python fibonacci_doctest.py
လိုန္႔စမ္းသ ္ႀကည္ာ့အရင္ error မအရတဲာ့အတြက္ output ဘာမအရမာမဟိုတ္ ဘး္။

မားတဲာ့အ ပဘမ္လို error ျ မလဲသအရေအာင္


a, b = 0, 1
ကို
a, b = 1, 1
ေျ ာင္းႀကည္န္႔အရေအာင္

Module ကို run ႀကည္ာ့အရင္ေအာက္ ပအတိုင္းေတြန္႔အရ ပလမာ့္မမ္္။


$ python fibonacci_doctest.py
**********************************************************************
File "fibonacci_doctest.py", line 8, in __main__.fib
Failed example:
fib(0)
Expected:
0
Got:
1
**********************************************************************
File "fibonacci_doctest.py", line 12, in __main__.fib
Failed example:
fib(10)
Expected:
55
Got:
89
**********************************************************************
File "fibonacci_doctest.py", line 14, in __main__.fib
Failed example:
fib(15)
Expected:
610
Got:
987
**********************************************************************
1 items had failures:
3 of 4 in __main__.fib
***Test Failed*** 3 failures.
Error ပတဲာ့ call အားလံိုးကိုေ ာ္ျ ေ းတာေတြန္႔ ပလမ္ာ့မမ္္။ "Failed example:" ဆိုတဲာ့ line
ေပနာက္မာ argument ပနဲန္႔ call ားတာေတြေတြန္႔ ပလမ္ာ့မမ္္။
"Expected:"ေပနာက္မာေတာာ့ ျ စ္အရမမ္ာ့ value ေတြ ပ ပတမ္္။ "Got:" ေပနာက္မာေတာာ့
တကမ္အရလာတဲာ့ တပန္ ိုးျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 80


Test-driven Development (TDD)

ေအရးျ ါးသား function ေတြကိုေတာာ့စမ္းသ ္ျ ါး ပျ ါ္။ မေအရးအရေသးတဲာ့ implement မလို ္အရေသးတဲာ့


function ေတြဆိုအရင္ေအရာ? မျ စ္ပနိုင္ဘး င္ ပသလား test-drive development ကဒါအတြက္သံိုး
ပတမ္္။

ဒါပနည္းလမ္းအတြက္ က္ တ
ဲ ာက သင္ေလ ာ္တာ့ဲ test case ေတြျ စ္ ပတမ္္။ အေကာင္းဆံိုး test
case ကေတာာ့ ျ စ္ပနိုင္တာ့ဲ input အားလံိုးပနဲo
ာ့ utput ေတြကို စစ္ေဆး ပလမ္ာ့မမ္္။ လက္ေတြန္႔မာေတာာ့
မျ စ္ပနိုင္ ပဘး္။

ေအာက္ေ ာ္ျ ပ စ မာ မာ return value ကို 0 သတ္မတ္ေ း ား ပတမ္္။


import doctest

def fib(n):
"""
Calculates the n-th Fibonacci number iteratively

>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>

"""

return 0

if __name__ == "__main__":
doctest.testmod()
ဒပေႀကာင္ ာ့fib(0) အတြက္ကလြျဲ ါးက ပန္တာေတြကို error ေတြေ း ပလမ္ာ့မမ္္။
$ python3 fibonacci_TDD.py
**********************************************************************
File "fibonacci_TDD.py", line 10, in __main__.fib
Failed example:
fib(1)
Expected:
1
Got:
0
**********************************************************************
File "fibonacci_TDD.py", line 12, in __main__.fib
Failed example:
fib(10)
Expected:
55
Got:
0
**********************************************************************
File "fibonacci_TDD.py", line 14, in __main__.fib
Failed example:

Python2(ဘာသာျ ပန္) Han Phyo Oo 81


fib(15)
Expected:
610
Got:
0
**********************************************************************
1 items had failures:
3 of 4 in __main__.fib
***Test Failed*** 3 failures.
ဒါcodeကို test ကို pass မျ စ္မ င္း ေျ ာင္းလဲေအရးသားေ းအရမာျ စ္ ပတမ္္။

ဒပေႀကာင္ာ့ ဒပကို test driven software development လိုန္႔ေ ခႀက ပတမ္္။

Unittest

Python module တစ္ ိုျ စ္တာ့ဲ unittest ကေတာာ့ unit testing framework တစ္ ိုျ စ္ျ ါး Erich
Gamma's JUnit and Kent Beck's Smalltalk testing framework ေ ခမာ အေျ ံ
တည္ေဆာက္ ား ပတမ္္။ ဒါmodule မ
ဲ ာ test case and suits ေတြ ၊ test ေတြ လို ္ ိုန္႔ text-
based utility class ေတြ result ေတြ ၊report လို ္ ိုန္႔ေတြ(TextTestRunner) ေတြ ပ၀င္ ပတမ္္။

“doctest” ပနဲန္႔မတတာတစ္ ိုကေတာာ့ စမ္းသ ္မည္ာ့ Module မ


ဲ ာ ည္ာ့ န္႔မ
ို လို ပဘး္။ အဓက
အက ဳေးေက းဇးကေတာာ့ program အရဲာ့ description ပနဲာ့ test description
ကို ဲြျ ားလိုက္တာ ျဲ စ္ ပတမ္္။ test case ေတြေတာာ့ ိုလို ္ေ းအရ ပမမ္္။

Unittest မာလို ဲ fobonacci module ကို သ


ဲ ံိုးျ ါးစမ္း ပမမ္္။ fibonacci_unittest.py လို ္မမ္္။
ဒါ မ
ဲ ာ unittest ေတြစမ္းမည္ာ့ module ေတြ import လို ္ ိုန္႔လို ပတမ္္။

ျ ါးေတာာ့ unittest.TestCase ကို inherit လို ္ ားတဲာ့ class တစ္ ိုလိုမမ္ “FibonacciTest”
လိုန္႔ေ ခ ပမမ္္။ test case ေတြကို ဒါ class မ
ဲ ာ method ေတြသံိုးျ ါးသတ္မတ္ ပမမ္္။ method
name ေတြကႀကိုက္တာျ စ္လိုန္႔အရေ မမ္ာ့ test ပနဲန္႔စအရ ပမမ္္။ "testCalculation" မ
ဲ ာ TestCase.
assertEqual class ဲက assertEqual method ကိုသံိုး ား ပတမ္္။ “first” expression ပနဲာ့
“second” expression တလားစစ္တာ ပ္။ မတအရင္ msg ကို output ိုတ္ေ း ပလမမ္ာ့မမ္္။
import unittest
from fibonacci import fib

class FibonacciTest(unittest.TestCase):

def testCalculation(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(5), 5)
self.assertEqual(fib(10), 55)
self.assertEqual(fib(20), 6765)

if __name__ == "__main__":
unittest.main()

Python2(ဘာသာျ ပန္) Han Phyo Oo 82


ဒါ test case ကိုစမ္းအရင္ေအာက္ ပအတိုင္းအရ ပလမ္ာ့မမ္္။
$ python3 fibonacci_unittest.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
လို င္တဲာ့ result ပ ဲ ္။ error ေတြစမ္းႀကည္ာ့ ပမမ္္။
a, b = 0, 1
ကို ေ
ဲ ျ ာင္းႀကည္ာ့ ပစါးမမ္္။
a, b = 1, 1
ဒပဆိုအရင္ေတာာ့
$ python3 fibonacci_unittest.py
F
======================================================================
FAIL: testCalculation (__main__.FibonacciTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fibonacci_unittest.py", line 7, in testCalculation
self.assertEqual(fib(0), 0)
AssertionError: 1 != 0

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)
testCalculation အရဲာ့ မဆံိုးအေႀကာင္းမာ error ျ ပတမ္္။ တစ္ျ ား assertEqual ေတြက
execute မလို ္ေသး ပဘး္။ error ကိုျ င္ျ ါ ေပနာက္တစ္ ိုလို ္ႀကည္ာ့အရေအာင္္။ ဒါတစ္ ပက 20
အတြက္ကလဲြျ ါး က ပန္တာ မပန္ ပလမ္ာ့မမ္္။
def fib(n):
""" Iterative Fibonacci Function """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
if n == 20:
a = 42
return a
ဒါတစ္ ပမာေတာာ့
$ python3 fibonacci_unittest.py
blabal
F
======================================================================
FAIL: testCalculation (__main__.FibonacciTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fibonacci_unittest.py", line 12, in testCalculation
self.assertEqual(fib(20), 6765)
AssertionError: 42 != 6765

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Python2(ဘာသာျ ပန္) Han Phyo Oo 83


testCalculation အရဲာ့statement ေတြအားလံိုး execute လို ္ေ မမ္ာ့ အားလံိုးက
အဆင္ေျ ေပနတဲာ့အတြက္ output ေတြန္႔အရမာ မဟိုတ္ ပဘး္။
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(5), 5)

Methods of the Class TestCase

Method Meaning

Hook method for setting up the test fixture before


setUp() exercising it. This method is called before calling the
implemented test methods.

tearDown()
Hook method for deconstructing the class fixture after
running all tests in the class.

assertEqual(self, first, The test fails if the two objects are not equal as
second, msg=None) determined by the '==' operator.

The test fails if the two objects are unequal as


determined by their difference rounded to the given
number of decimal places (default 7) and comparing
to zero, or by comparing that the between the two
assertAlmostEqual(self,
first, second, places=None,
objects is more than the given delta.
msg=None, delta=None) Note that decimal places (from zero) are usually not
the same as significant digits (measured from the most
significant digit).
If the two objects compare equal then they will
automatically compare almost equal.

An unordered sequence comparison asserting that the


same elements, regardless of order. If the same
element occurs more than once, it verifies that the
elements occur the same number of times.
self.assertEqual(Counter(list(first)),
assertCountEqual(self, first, Counter(list(second)))
second, msg=None) Example:
[0, 1, 1] and [1, 0, 1] compare equal, because
the number of ones and zeroes are the same.
[0, 0, 1] and [0, 1] compare unequal, because
zero appears twice in the first list and only once in the
second list.

assertDictEqual(self, d1, d2, Both arguments are taken as dictionaries and they are
msg=None) checked if they are equal.
assertTrue(self, expr,
msg=None) Checks if the expression "expr" is True.

assertGreater(self, a, b, Checks, if a > b is True.

Python2(ဘာသာျ ပန္) Han Phyo Oo 84


Method Meaning
msg=None)

assertGreaterEqual(self, a,
b, msg=None) Checks if a ≥ b

assertFalse(self, expr,
msg=None) Checks if expression "expr" is False.

assertLess(self, a, b,
msg=None) Checks if a < b

assertLessEqual(self, a, b,
msg=None) Checks if a ≤ b

assertIn(self, member,
container, msg=None) Checks if a in b

assertIs(self, expr1, expr2,


msg=None) Checks if "a is b"

assertIsInstance(self, obj,
cls, msg=None) Checks if isinstance(obj, cls).

assertIsNone(self, obj,
msg=None) Checks if "obj is None"

assertIsNot(self, expr1,
expr2, msg=None) Checks if "a is not b"

assertIsNotNone(self, obj,
msg=None) Checks if obj is not equal to None

assertListEqual(self, list1,
list2, msg=None) Lists are checked for equality.

assertMultiLineEqual(self,
first, second, msg=None) Assert that two multi-line strings are equal.q

assertNotRegexpMatches(self,
text, unexpected_regexp,
Fails, if the text Text "text" of the regular expression
msg=None) unexpected_regexp matches.

assertTupleEqual(self,
tuple1, tuple2, msg=None) Analogous to assertListEqual

Python2(ဘာသာျ ပန္) Han Phyo Oo 85


setUp ပနဲ႕ a tearDown methodေတြ ္ ည္ာ့မမ္္။
import unittest
from fibonacci import fib

class FibonacciTest(unittest.TestCase):

def setUp(self):
self.fib_elems = ( (0,0), (1,1), (2,1), (3,2), (4,3), (5,5) )
print ("setUp executed!")

def testCalculation(self):
for (i,val) in self.fib_elems:
self.assertEqual(fib(i), val)

def tearDown(self):
self.fib_elems = None
print ("tearDown executed!")

if __name__ == "__main__":
unittest.main()
result ကေတာာ့
$ python3 fibonacci_unittest2.py
setUp executed!
tearDown executed!
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
TestCase methods ေတြေတာ္ေတာ္မ ားမ ားမာ optional parameter “msg” ပ ပတမ္္။ msg ပနဲာ့
error အတြက္အေႀကာင္းအအရာေတြ ္ ည္ာ့ေ းလိုန္႔အရ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 86


Exercises

1. Exercise:

Can you find a problem in the following code?


import doctest

def fib(n):
""" Calculates the n-th Fibonacci number iteratively

>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(40)
102334155
>>>

"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

if __name__ == "__main__":
doctest.testmod()

Answer:

The doctest is okay. The problem is the implementation of the fibonacci function. This recursive
approach is "highly" inefficient. You need a lot of patience to wait for the termination of the test.
The number of hours, days or weeks depend on your computer.☺

Python2(ဘာသာျ ပန္) Han Phyo Oo 87


Chapter 22
Memoization with Decorators

Memoization ဆိုတာကေတာာ့ computing မာ programေတြျမပန္ဆပန္ေအာင္လို ္တဲာ့


ပနည္းတစ္ ို ပ္။ funcation call result လိုမ ်ဴး တြက္ က္မအရလဒ္ေတြကို သမ္း ားတာျ စ္ ပတမ္္။
တညါတဲာ့ input ေတြ function call ေတြအတြက္ ဆိုအရင္ မသမ္း ားတဲာ့ result
ေတြ ို ္ေ းျ ါး မလိုအ ္တာ့ဲ တြက္ က္တာေတြကို မ္အရားေ းပနိုင္ ပတမ္္။ result
ေတြသမ္း ိုန္႔အတြက္ array ကို ဲ အသံိုးမ ားေ မမ္ာ့ တစ္ျ ား structure ေတြျ စ္တာ့ဲ associative
array ေတြလည္းသံိုးပနိုင္ ပတမ္္။

Memoization ကို programmer ကိုမ္တိုင္လို ္ပနိုင္သလို python လို language မ ဳေးမာေတာာ့


meoization လို ္ ိုန္႔ Mechanism ေတြ ပ ပတမ္္။

Memoization with Function Decorators

Recursive function အ ပန္းမာ Fibonacci number ေတြကို iterative ေတြ recursive


ေတြသံိုးျ ါး တြက္ ာ့ဲ ပတမ္္။ recursive functionပနဲာ့ေအရးတာက exponential behavior
ျ စ္တာလည္းသျ ါး ျ စ္ ပလမာ့္မမ္္။
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

dictionary သံိုးျ ါး function မာ တြက္ ာ့တ


ဲ ာေတြမတ္မေအာင္လို ္ျ ါး ျမပန္
ျမပန္ေအာင္လို ္တာလည္း ေျ ာျ ဲာ့ ပတမ္္။ ဒပကေတာာ့ memoization
ကိုကိုမ္တိုင္လို ္ ဲာ့တာျ စ္ ပတမ္္။ မေကာင္းတာက ေတာာ့အရင္းလင္းမေတြ recursive
အရဲာ့ ံိုစံေတြေ ာက္သြားတာျ စ္ ပတမ္္။

ျ ပနာက recursive fib function ကို ျ င္လိုက္လိုန္႔ျ စ္တာ ပ္။ ေအာက္ေ ာ္ျ ပ code မာေတာာ့
fib function ကိုမျ င္ ား ပဘး္။ ဒပေႀကာင္ာ့ memoize ဆိုတဲာ့ function တစ္ ိုသံိုး ား ပတမ္္။
memoize() က function တစ္ ိုကို argument အေပနပနဲာ့လက္ ံေ း ပတမ္္။ memoize()
function က “memo” ဆိုတဲာ့ dictionary သံိုးျ ါး result ေတြကိုမတ္ ပတမ္္။ “memo”ေအရာ “f”
ေအရာ local value ေတြဆိုေ မမ္ာ့ helper method ေတြသံိုးျ ါး return ျ ပန္ ပတမ္္။
memoize(fib) ကိုေ ခတဲာ့ အ ပမာ helper() အရဲာ့ referenceအရမ္ တြက္ ားတဲာ့ result သမ္း ားတဲာ့
wrapper အရမ္ျ ပန္ေ း ပတမ္္။
def memoize(f):
memo = {}
def helper(x):

Python2(ဘာသာျ ပန္) Han Phyo Oo 88


if x not in memo:
memo[x] = f(x)
return memo[x]
return helper

def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

fib = memoize(fib)
print(fib(40))
fib ကa
ို rgument အေပနပနဲာ့သံိုး ားတဲာ့ အေႀကာင္းကိုႀကည္ာ့အရေအာင္
fib = memoize(fib)
ဒပဆိုအရင္ memoize က decorator ျ စ္သာြ း ပတမ္္။ fib = memoize(fib) အလို ္မလို ္ င္
function name ေတြက သတိုန္႔ body ကို ဲ reference လို ္ ပတမ္္။
fib = memoize(fib)ကို execute လို ္ျ ါးတဲာ့အ ပန္မာေတာာ့ fib က helper function body ကို
ညြပန္း ပတမ္္။ မလ fib function ကိုလဲ helper အရဲာ့ f function ကေပနမတဆင္ာ့သာြ းလိုန္႔အရေတာာ့မာ ျ
ျ စ္ ပတမ္္။ fib အတြက္ တစ္ျ ား reference မအရေတာာ့ ပဘး္။ decorate လို ္ ားတဲာ့ Fibonacci
function ကို return fib(n-1) + fib(n-2)ပနဲန္႔ေ ခ ား ပတမ္္။ memorize ကေပန return
ျ ပန္လာ တဲာ့ helper function ကိုေျ ာတာျ စ္ ပတမ္္။
decorator ဲက context ေတြကအျ ား အဓ ၸာမ္အရ ပေသးတမ္္။ function
ေတြအျမားႀကါးေအရးမည္ာ့ အစား”memorize” ပနဲာ့ decorate လို ္တာျ စ္ ပတမ္္။
fib = memoize(fib)
func1 = memoize(func1)
func2 = memoize(func2)
func3 = memoize(func3)
# and so on
Decorator ကို python မာေအရးသလိုေအရးမ ား ပဘး္။ေအာက္ ပအတိုင္းေအရးမမ္ာ့အစား
fib = memoize(fib)
fib ကို “decorated” လို ္သင္ာ့ ပတမ္္။
@memoize
ဒပေ မမ္ာ့ ဒါစာေႀကာင္းက decorated function ေအရာ့မာအရအရမာ ပ္။
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper

@memoize
def fib(n):
if n == 0:
return 0

Python2(ဘာသာျ ပန္) Han Phyo Oo 89


elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)

print(fib(40))
Using a Class Decorator for Memoization

Object orientation မသေသးအရင္ဒါအ ိုင္းေက ာ္သာြ းလိုန္႔အရ ပတမ္္။

Result catching ကို class မ


ဲ ာလည္လို ္ပနိုင္ ပတမ္္။
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if args not in self.memo:
self.memo[args] = self.fn(*args)
return self.memo[args]

@Memoize
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
dictionary သံိုးတဲာ့အတြက္ေႀကာင္ာ့ mutable argument ေတြသိုးံ လိုန္႔မအရ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 90


Chapter 23
Parameter Passing

"call by value" and "call by name"

Function ေတြအတြက္ argument passing လို ္တဲာ့အ ပ ႏွာစ္မ ိုးသံိုးႀက ပတမ္္။

 Call by Value

အသံိုးအမ ားဆံိုးကေတာာ့ call by value သိုန္႔ pass-by-value ျ စ္ ပတမ္္။ call-by-value


မာေတာာ့ arugment expression ကိုအအရင္တက
ြ ္ ျ ါးမ အရလာတဲာ့ result ကို function

ဲ ာ အရတဲာ့သက္ဆိုင္အရာ variable ပနဲန္႔ တ္ေ း ပတမ္္။ expression က variable ဆိုအရင္
တပန္ ိုးကို local copy လို ္ျ ါးသံိုး ပတမ္္။အဲာ့ဒပေႀကာင္ာ့ function call လို ္တဲာ့ဘက္မာ
variable အေျ ာင္း အလဲမအရ ပဘး္။

 Call by Reference

Call by reference သိုန္႔ pass-by-reference လိုန္႔သႀက ပတမ္္။ function က argument


ေတြအရဲာ့ value ေတြအစား reference ေတြသိုးံ ျ ါးအလို ္လို ္ ပတမ္္။ အရလဒ္အေပနပနဲာ့
function ကေပနျ ါးေတာာ့ argument
ကိုေျ ာင္းလဲျ င္ဆင္ပနိုင္ျ င္း ဲျ စ္ ပတမ္္။ ေကာင္းတာ တစ္ က္က argument ေတြcopy
ြားစအရာမလိုတာ ပ္။ မေကာင္းတာကေတာာ့ မေတာတဆ ျ င္ဆင္မတာေတြျ စ္ပနိုင္ ပတမ္္။

and what about Python?

Python မာတာာ့ call-by-object ကိုသံိုး ပတမ္္။ "Call by Object Reference" or "Call by


Sharing" လိုန္႔လည္းေ ခႀက ပတမ္္။

Immutable argument ေတြျ စ္တာ့ဲ ntegers, strings or tuples to a function ေတြပနဲာ့ဆိုအရင္


call-by-value ံိုစံအလို ္လို ္ ပတမ္္။ function parameter က
ဲ ို object reference
ေတြေအရာက္သြား ပတမ္္။ သတိုန္႔ကိုေျ ာင္းလဲလိုန္႔လံိုး၀မအရတဲာ့အတြက္ေႀကာင္ာ့ function

ဲ ာလည္း ေျ ာင္းလိုန္႔မအရ ပဘး(immutable)္။ mutable argument ေတြဆိုအရင္ေတာာ့ ေျ ာ
ေျ ာင္းလဲလိုန္႔အရသြား ပတမ္.္။ function က
ဲ ို list ိုန္႔ င္အရင္ ပနစ္မ ဳေးစစ္းစား ိုန္႔လို ပတမ္္။ list
ကိုေျ ာငး္ လဲလိုန္႔အရတမ္္။ အသစ္ ည္ာ့ေ းမမ္ဆိုအရင္ေတာာ့ list အေဟာင္းကိုသက္ေအရာက္မမအရ
ပဘး္။

Integer value ကိုအအရင္ႀကည္ာ့အရေအာင္္။ function ဲက parameter သည္ parameter


မေျ ာင္း မ င္း argument variable အရဲာ့ reference အျ စ္အရ ပတမ္္။
တပန္ ိုးအသစ္တစ္ ိုေျ ာင္းလဲလိုက္မမ္ ဆိုအရင္ေတာာ့ python က Local variable

Python2(ဘာသာျ ပန္) Han Phyo Oo 91


အသစ္တစ္ ို ပန္တါး ပလမာ့္မမ္္။ function call လို ္တဲာ့ (caller) ဘက္က variable
ကေျ ာင္းမာမဟိုတ္ေတာာ့ ပဘး္။

def ref_demo(x):

print "x=",x," id=",id(x)


x=42
print "x=",x," id=",id(x)
ေ ာ္ျ ပ စ မာမာ id() function ကိုသံိုး ား ပတမ္္။ သက object တစ္ ိုကို parameter
အျ စ္သံိုး ပတမ္္။ id(obj) ဆိုအရင္ “obj” အရဲာ့ “identity”ကို return ျ ပန္ေ း ပတမ္္။ identity
ဆိုတာကေတာာ့ object အတက္ သါးသပန္ာ့ Integer တပန္ ိုန္႔တစ္ ိုျ စ္ျ ါး unique and constant
ျ စ္ ပတမ္္။ life time (non-overlapping lifetime)မ ္တဲာ့ မတညါတာ့ဲ object ႏွာစ္ ိုဟာ
identity တတာမ ဳေးျ စ္ပနိုင္ ပတမ္္။

ေအာက္ ပအတိုင္း စစ္ႀကည္န္႔အရင္ “x” က main scope မာ id 41902552 အရ ပတမ္္။ ref_demo()


function အရဲာ့ မဆံိုးအေႀကာင္းမာလည္း identity ကိုစစ္တဲာ့အ ပမာလည္း
တေပနတဲာ့အတြက္ေႀကာင္ာ့ main scope က x ကိုအသံိုးျ ဳေတိုပန္း ပ ဲ္။ x ကို တပန္ ိုးအသစ္ျ စ္တဲန္႔ 4
42 ေ းလိုက္တာ့အ
ဲ ပမာေတာာ့ identity အသစ္အျ စ္ 41903752 ကိုေျ ာင္းလဲသာြ း ပတမ္္။
global မာအရတဲာ့ x ပနဲန္႔ memory location မတေတာာ့တာျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ main scope
ကိုျ ပန္လာႀကည္ာ့ တဲန္႔အ ပ x ကပနဂိုတပန္ ိုး 9 ကေပနမေျ ာင္းလဲ ဲအရေပနတာေတြန္႔ပနိုင္ ပတမ္္။

ဆိုလိုတာက python ကအစတိုပန္းက call-by-reference ံိုစံမ ဳေးလို ္ေဆာင္ေ မမ္ာ့္။ variable


value ကိုေျ ာင္းလဲတာပနဲာ့ call-by-value ံိုစံျ စ္သြား ပတမ္္။
>>> x = 9
>>> id(x)
41902552
>>> ref_demo(x)
x= 9 id= 41902552
x= 42 id= 41903752
>>> id(x)
41902552
>>>

Side effects

Function တစ္ ိုမာ တပန္ ိုးတစ္ ို ိုတ္ေ းတာအျ င္ caller environement


ကိုေျ ာင္းလဲတာ ေတြျ စ္ေစအရင္ side effet အရတမ္ဆို ပတမ္္။ စ မာ- function က
global/staitic variable ေတြကိုျ င္တာ္။ argument ေတြကိုျ င္တာ္။ exception ေတြျ စ္တာ္။
display ေတြ file ေတြကို data ေတြ ည္ာ့တာစတာေတြျ စ္ ပတမ္္။

မ ားေသာအားျ င္ာ့ ဒပေတြကို function လိုအ ္ က္အေပနပနဲန္႔အသံိုးျ ဳေႀက ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 92


List ကို function တစ္ ိုဆါ ိုာ့တမ္ဆို ပစိုန္႔္။ function က list ကိုေျ ာင္းလဲမေတြမလ ္ဘးလန္႔ို
မဆမမ္္။ side effect မအရတာအအရင္ႀကည္ာ့မမ္္။ func1() အရဲာ့ parameter list ကို list
အသစ္တစ္ ို သတ္မတ္ေ းလိုက္တာ့အ
ဲ တြက္ memory location
အသစ္တစ္ ိုတည္ေဆာက္ေ း ပတမ္္။
>>> def func1(list):
... print list
... list = [47,11]
... print list
...
>>> fib = [0,1,1,2,3,5,8]
>>> func1(fib)
[0, 1, 1, 2, 3, 5, 8]
[47, 11]
>>> print fib
[0, 1, 1, 2, 3, 5, 8]
>>>

ဒပေ မမ္ာ့ List မာ “+=” သံိုးအရင္တစ္မ ဳေးျ စ္သာြ း ပျ ါ္။ example


>>> def func2(list):
... print list
... list += [47,11]
... print list
...
>>> fib = [0,1,1,2,3,5,8]
>>> func2(fib)
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 47, 11]
>>> print fib
[0, 1, 1, 2, 3, 5, 8, 47, 11]
>>>
ဒပကိုေအရာင္အရား င္အရင္ေတာာ့ list ကို copy ကးျ ါး function ပနဲာ့အသံိုးျ ဳေအရမာ ပ္။ဒါမာေတာာ့ shallow
copy ပနဲာ့လံိုေလာက္ ပတမ္္။
>>> def func2(list):
... print list
... list += [47,11]
... print list
...
>>> fib = [0,1,1,2,3,5,8]
>>> func2(fib[:])
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 47, 11]
>>> print fib
[0, 1, 1, 2, 3, 5, 8]
>>>

Command Line Arguments

Python script ကို command line argument ေတြသံိုးျ ါးေအရးပနိုင္ ပတမ္္။ python script
ေတြကို shell ကေပနအသံိုးျ ဳေတာ့အ
ဲ ပမာ argument ေတြက script name

Python2(ဘာသာျ ပန္) Han Phyo Oo 93


ေပနာက္မာအရ ပတမ္္။ ျ ါးေတာာ့ argument ေတြႀကား မ
ဲ ာ space ံ ပတမ္္။ script ဲကေပန ဒါ
argument ေတြကို သံိုး င္တမ္ ဆိုအရင္ေတာာ့ sys.argv ဆိုတဲာ့ list variable ကိုသံိုးအရမာ ပ္။
sys.argv[0] မာ script name ၊ sys.argv[1] မာ first parameter ၊ sys.argv[2]မာ second
parameter စသျ င္ာ့ ပ ပတမ္္။

ေအာက္ေ ာ္ျ ပ (arguments.py)မာ ပတာေတြျ စ္ ပတ.မ္


# Module sys has to be imported:
import sys

# Iteration over all arguments:


for eachArg in sys.argv:
print eachArg

shell/cmd ကေပနေ ခႀကညာ့္မမ္္။


python argumente.py python course for beginners
က
ြ ္လာတဲာ့ output ကေတာာ့
argumente.py
python
course
for
beginners

Variable Length of Parameters

Argument ေတြအမ ားႀကါးလက္ ံပနိုင္တဲာ့ function ေတြအေႀကာင္းေျ ာ ပမမ္္။ Python မာ “*”


ကို variable argument ေတြကိုသတ္မတ္အရင္သံိုး ပတမ္္။
>>> def varpafu(*x): print(x)
...
>>> varpafu()
()
>>> varpafu(34,"Do you like Python?", "Of course")
(34, 'Do you like Python?', 'Of course')
>>>
ဒါမာ function က
ဲ ိုေအရာက္လာတာေတြကို tuple အေပနပနဲာ့လက္ ံတာေတြန္႔အရ ပလမ္ာ့မမ္္။
argument မ ပအရင္ေတာာ့ empty tuple ဲျ စ္ ပလမ္ာ့မမ္္။

တစ္ ပတစ္အရံ an arbitrary number of parameters(variable မ ား) ေပနာက္မာ positional


parameter ေတြ ပတာမ ဳေးအရပနိုင္ ပတမ္္။ျ စ္ပနင္တမ္ဆိုေ မမ္ာ့ positional parameter က
arbitrary parameter ေအရာ့မာအျမဲအရအရ ပမမ္္။ ေအာက္ေ ာ္ျ ပ စ မာမာ “city” ဆိုတဲာ့ positional
parameter ပျ ါးေတာာ့ ၎ေပနာက္မာ arbitrary parameter ေတြ ပ၀င္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 94


>>> def locations(city, *other_cities): print(city, other_cities)
...
>>> locations("Paris")
('Paris', ())
>>> locations("Paris", "Strasbourg", "Lyon", "Dijon", "Bordeaux",
"Marseille")
('Paris', ('Strasbourg', 'Lyon', 'Dijon', 'Bordeaux', 'Marseille'))
>>>
List ပနဲာ့သံိုး င္အရင္ေတာာ့ function call လို ္အရာမာ “*” ည္ာ့ေ းအရ ပမမ္္။

* in Function Calls

“*” က function call လို ္အရာမာလည္း ပလာပနိုင္ ပတမ္္။ tuple ေတြ List ေတြဆိုအရင္ singular
ံိုစံေျ ာင္းသြား ပတမ္္။
>>> def f(x,y,z):
... print(x,y,z)
...
>>> p = (47,11,12)
>>> f(*p)
(47, 11, 12)
ေအာက္ ပ ံိုစံအတိုင္းလည္းအရ ပတမ္္။
>>> f(p[0],p[1],p[2])
(47, 11, 12)
>>>

Arbitrary Keyword Parameters

Arbitrary number of keyword parameter ေတြအတြက္လည္း mechanism ေတြအရ ပတမ္္။


“**” ကိုသံိုး ပတမ္္။
>>> def f(**args):
... print(args)
...
>>> f()
{}
>>> f(de="German",en="English",fr="French")
{'fr': 'French', 'de': 'German', 'en': 'English'}
>>>

Double Asterisk in Function Calls

“**”ကို function call မာသံိုးတဲာ့ ံိုစံ


>>> def f(a,b,x,y):
... print(a,b,x,y)
...
>>> d = {'a':'append', 'b':'block','x':'extract','y':'yes'}
>>> f(**d)
('append', 'block', 'extract', 'yes')

Python2(ဘာသာျ ပန္) Han Phyo Oo 95


“*” ပနဲာ့တသ
ြဲ ံိုးတဲာ့ ံိုစံ
>>> t = (47,11)
>>> d = {'x':'extract','y':'yes'}
>>> f(*t, **d)
(47, 11, 'extract', 'yes')
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 96


Chapter 24
Namespaces and Scopes

Namespaces

Namespace ဆိုတာကေတာာ့ system မ


ဲ ာ တစ္ ိုပနန္႔တ
ဲ စ္ ိုမအရို ္ေ းြ ေအာင္(ambiguity)
ပနာမည္ေတြကို unique( ္တမအရတာ) ျ စ္ေအာင္လို ္တာျ စ္ ပတမ္္။ လေတြမာလည္း
ပနာမည္တအရင္ေတာင္ family name (surname)ပနဲာ့ ဲြႀက ပတမ္္။ network ေတြမာဆိုအရင္ လည္း
တ္ဆက္မည္ာ့ device တစ္ ိုျ င္းဆါမာ unique name/ip address ေတြအရ ပတမ္္။ ေပနာက္တစ္ ို
က file system ေတြအရဲာ့ directory structure ပ္။ file name တအရင္ေတာင္ directory မတအရင္သံိုး
လိုန္႔အရ ပတမ္္။ programming language ေတြမာလည္း identifier ေတြကို namespace
ေတြ မ
ဲ ာ သတ္မတ္ပနိုင္ ပတမ္္။ တညါတဲာ့ indentifier ေတြကိုလည္း မတညါတာ့ဲ namespace
ေတြ မ
ဲ ာ အသံိုးျ ဳေပနိုင္ ပတမ္္။

Python မာ namespace ေတြကို python dictionaries ေတြပနဲာ့အသံိုးျ ဳေ ပတမ္္။ names(keys)


object(values)အျ စ္mapping လို ္ ားတာျ စ္ ပတမ္္။ အသံိုးျ ဳေသအေပနပနဲာ့ေတာာ့ program

ဲ ာ namespace ေတြအသံိုးျ ဳေ ိုန္႔ ဒပေတြသစအရာမလို ပဘး္။

 global names of a module


 local names in a function or method invocation
 built-in names: this namespace contains built-in functions (e.g. abs(), cmp(), ...) and
built-in exception names

Lifetime of a Namespace

Script သိုန္႔ program မ


ဲ ာသံိုး ားတဲာ့ namespace ေတြကို
သံိုး င္တဲာ့အ ပန္သံိုးလိုန္႔ေတာာ့မအရ ပဘး္။ namespace ပန္တါး ဲာ့တဲာ့အ ပန္ေတြမတညါတံအ
ဲ တြက္
မတညါတာ့ဲ Lifetime ေတြအရႀက ပတမ္္။ အစကေပနအဆံိုး အ အရေပနတဲာ့ namespace
တစ္ ိုေတာာ့အရ္ ပတမ္္။ built-in name ေတြ ပတဲာ့ namespace ကေတာာ့ python interpreter စ
run က
ဲ တည္အရျ ါး ဘမ္ေတာာ့မမ က္ ပဘး္။ module တစ္ ိုကိုစတင္အလို ္လို ္တာ့ဲ အ ပ ၎
module အရဲာ့ global namespace ို ္ေ း ပတမ္္။ module namespace ေတြကေတာာ့ script
မဆံိုးမျ င္း interpreter ကေပနမ က
ြ ္မျ ငး္ ေတာာ့အရေပနတတ္ ပတမ္္။ function တစ္ ိုကို
callလို ္အရာမာ လည္း ၎ function အတြက္ local namespace တစ္ ိုျ ဳေလို ္ေ း ပတမ္္။
function ဆံိုးသြားအရင္ေတာာ့ က္ ပတမ္္။

Scopes

Scope ကေတာာ့ namespace တစ္ ိုကိုတိုက္အရိုက္အသံိုးျ ဳေပနိုင္တာ့ဲ


ပနမ္ မ္တစ္ ိုျ စ္ ပတမ္္။ ေပနာက္တစ္မ ဳေးေျ ာအရအရင္ ေတာာ့ scope ဆိုသည္မာ name တစ္ ိုကို
ambigus မအရ ဲ အသံိုးျ ဳေပနိုင္ေသာေပနအရာျ စ္ ပတမ္္။ name တစ္ ိုအရဲာ့ namespace ဆိုတာကေတာာ့

Python2(ဘာသာျ ပန္) Han Phyo Oo 97


သန္႔အရာ့ဲ scope ပနဲာ့ အတတ ပ ဲ.္။ scope ေတြက static အျ စ္သတ္မတ္ ားေ မမ္ာ့ dynamic
သံိုးေက ပတမ္္။

Program execution လို ္အရာမာ အရတဲာ့ nested scope ေတြကေတာာ့

 အတြင္းအက ဆံိုး scope မာ အအရင္အရာျ ါးေတာာ့ ၎မာ local name ေတြ ပ ပတမ္္။
 တကမ္လိုန္႔ တစ္ျ ား scope တစ္ ို ဲမာအရတမ္ဆိုအရင္လည္း အပနါးဆံိုးကို အအရင္အရာ ပတမ္္။
 ေပနာက္ scope ေတြမာေတာာ့ လက္အရ Module အရဲာ့ global name ေတြ ပ ပတမ္္။
 အျ င္အက ဆံိုးပနဲာ့ ေပနာက္ဆံိုးကေတာာ့ built-in name ေတြ ပတဲာ့ namespace ျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 98


Chapter 25
Global and Local Variables

Global and local Variables in Functions

ေအာက္ ပ function ကိုႀကည္ာ့ႀကည္ာ့ ပ္။


def f():
print s
s = "I hate spam"
f()
variable s ကို “I hate spam” လိုန္႔ function f() ကိုမေ ခ င္သံိုး ား ပတမ္္။ f() ဲ မာက
“print s” တစ္ေႀကာင္း ဲအရ ပတမ္္။ s ဆိုတဲာ့ local variable မအရတဲာ့အတြက္ global variable s
ကိုအသံိုးျ ဳေ ပလမ္ာ့မမ္္။ ဒပေႀကာင္ာ့ output က “I hate spam”ျ စ္ ပတမ္္။ function f() မ
ဲ ာs
ကိုေျ ာင္းလဲ မေတြလို ္အရင္ဘာျ စ္မလဲ
def f():
s = "Me too."
print s

s = "I hate spam."


f()
print s
အရလဒ္ကေတာာ့
Me too.
I hate spam.
မ စ မာ ပနဲာ့ဒိုတမစ မာေ ပင္းေအရးႀကည္ာ့မမ္္။ အအရင္ ဆံိုး s ကိုမသံိုးမမ္ ျ ါးမ တပန္ ိုးအသစ္
assign လို ္မမ္္။
def f():
print s
s = "Me too."
print s

s = "I hate spam."


f()
print s
ဒပဆိုအရင္ေတာာ့ error ျ ပလ္မ္ာ့မမ္
UnboundLocalError: local variable 's' referenced before assignment
Pythonက f() မ
ဲ ာ s ကို assignment လို ္ ားတာေတြ႕တဲာ့အတြက္ေႀကာင္ာ့ local variable
ကိုသံိုး င္တာလိုန္႔မဆ ပလမ္ာ့မမ္္။ function မ
ဲ ာ ပန္တါးသမ variable အားလံိုးက Local
ဲျ စ္ ပတမ္္။ global ကသ
ို ံိုး င္တမ္ဆိုအရင္ေတာာ့ “global” keyword ကိုသံိုးေ းအရ ပမမ္္။
def f():
global s
print s
s = "That's clear."
print s

s = "Python is great!"

Python2(ဘာသာျ ပန္) Han Phyo Oo 99


f()
print s
ဒပဆိုအရင္ေတာာ့ ambiguity မအရေတာာ့ ပ္။
Python is great!
That's clear.
That's clear.
Function ဲက local variable ကိုလည္း အျ င္ကေပန သံိုးလိုန္႔မအရ ပဘး္။
def f():
s = "I am globally not known"
print s

f()
print s
run ႀကည္ာ့အရင္ error ျ ပလမ္ာ့မမ္္။
I am globally not known
Traceback (most recent call last):
File "global_local3.py", line 6, in <module>
print s
NameError: name 's' is not defined

Global ပနဲာ့ local variable သံိုး ားတဲာ့ example


def foo(x, y):
global a
a = 42
x,y = y,x
b = 33
b = 17
c = 100
print a,b,x,y

a,b,x,y = 1,15,3,4
foo(17,4)
print a,b,x,y
The output of the script above looks like this:
42 17 4 17
42 15 3 4

Python2(ဘာသာျ ပန္) Han Phyo Oo 100


Chapter 26
File I/O

Working with Files

File ဆိုတာကေတာာ့ program ေတြကေပန data ေတြinformation ေတြစို ားတဲာ့ computer file
ေတြျ စ္ ပတမ္္။ file ေတြကို durable storage ေတြမာသမ္း ပတမ္္။ လေတြ program
ေတြကေပန file ေတြကို တ္အရျ င္ဆင္ တာေတြလို ္ ိုန္႔အတြက္ unique name ပနဲာ့ path
ေတြအသံိုးျ ဳေႀက ပတမ္္။

“file” ဆိုတဲာ့ အသံိုးအႏွာိုံးကေတာာ့ punch card အသံိုးျ ဳေ ဲ 1952 က


ဲ ေ ခေ ပက္ ဲာ့ ပတမ္္။

အ က္အလက္ေတြကို သမ္းဆည္းမေတြ ျ ပန္လည္အသံိုးျ ဳေမေတြမလို ္ပနိုင္တာ့ဲ programming


language တစ္ ိုကသ ္အသံိုးမ၀င္ပနင္ ပဘး္။

File manipulation မာ ပတဲာ့ အဓကလို ္ေဆာင္ က္ေတြကေတာာ့ file ေတြကေပန data ေတြ
တ္တာေတြ data ေတြျ ပန္ ည္ာ့တာ ္ေ ပာင္းတာေတြျ စ္ ပတမ္္။

File ကေပန data တ္ႀကည္ာ့ ပတမ္္။ မ parameter ကေတာာ့ အသံိုးျ ဳေမမ္ာ့ file name
ျ စ္ျ ါးေတာာ့ ဒိုတမ parameter ကေတာာ့ “r” လိုန္႔ေ း ားျ ါး read
လို ္မမ္လိုာ့ေျ ာတာျ စ္ ပတမ္္။
fobj = open("ad_lesbiam.txt", "r")
file ပနဲာ့ တ္သတ္တာ့ဲ အလို ္ေတြလို ္ျ ါးအရင္ေတာာ့ close လို ္ေ းအရ ပမမ္္။
fobj.close()
examples
fobj = open("ad_lesbiam.txt")
for line in fobj:
print line.rstrip()
fobj.close()
“file_read.py”လိုန္႔သမ္းျ ါး runႀကည္ာ့အရင္
$ python file_read.py
V. ad Lesbiam

VIVAMUS mea Lesbia, atque amemus,


rumoresque senum severiorum
omnes unius aestimemus assis!
soles occidere et redire possunt:
nobis cum semel occidit breuis lux,
nox est perpetua una dormienda.
da mi basia mille, deinde centum,
dein mille altera, dein secunda centum,
deinde usque altera mille, deinde centum.
dein, cum milia multa fecerimus,
conturbabimus illa, ne sciamus,
aut ne quis malus inuidere possit,

Python2(ဘာသာျ ပန္) Han Phyo Oo 101


cum tantum sciat esse basiorum.
(GAIUS VALERIUS CATULLUS)

Writing into a File

Write လို ္တာလည္းလြမ္ ပတမ္္။ writeလို ္ ိုန္႔ file ကို င


ြ ္ာ့မမ္ဆိုအရင္ second parameter ကို
“r” အစား “w”ေျ ာင္းေ းအရ ပမမ္္။ data write လို ္ ိုန္႔ file object အရဲာ့ write() method
ကိုသံိုးအရ ပမမ္္။
fobj_in = open("ad_lesbiam.txt")
fobj_out = open("ad_lesbiam2.txt","w")
i = 1
for line in fobj_in:
print line.rstrip()
fobj_out.write(str(i) + ": " + line)
i = i + 1
fobj_in.close()
fobj_out.close()
input text file အရဲာ့ စာေႀကာင္းတိုင္းမာ line number ေလးပနဲာ့စ ပလမ္ာ့မမ္္။
$ more ad_lesbiam2.txt
1: V. ad Lesbiam
2:
3: VIVAMUS mea Lesbia, atque amemus,
4: rumoresque senum seueriorum
5: omnes unius aestimemus assis!
6: soles occidere et redire possunt:
7: nobis cum semel occidit breuis lux,
8: nox est perpetua una dormienda.
9: da mi basia mille, deinde centum,
10: dein mille altera, dein secunda centum,
11: deinde usque altera mille, deinde centum.
12: dein, cum milia multa fecerimus,
13: conturbabimus illa, ne sciamus,
14: aut ne quis malus inuidere possit,
15: cum tantum sciat esse basiorum.
16: (GAIUS VALERIUS CATULLUS)
ျ စ္ပနိုင္တာ့ဲ ျ ပနာတစ္ ေ
ို ျ ာ ပမမ္္။ အရေပနျ ါးသား file တစ္ ိုကို write လို ္ ိုန္႔ open
လို ္မအရင္ေအရာ္။ ဒပဆိုအရင္ေတာာ့ ပနဂိုအရေပနတဲာ့ file ကို က္လိုက္ ပတမ္္။

အရျ ါးသား file ကိုမ ္ေ ပင္း င္အရင္ “a” ကိုသံိုးအရ ပမမ္္။

Reading in one

မႀကာ ဏဆိုသလို file ေတြကို for loop သံိုးျ ါး တစ္ေႀကာင္း င္းအလို လ


္ ို ္ႀက ပတမ္္။ file
ကသ ္မႀကါးဘးဆိုအရင္ file အရဲာ့ data structre တစ္ ိုလာ့ိုးကို read လို ္တာ ိုအဆင္ေျ ပတမ္.
>>> poem = open("ad_lesbiam.txt").readlines()
>>> print poem
['V. ad Lesbiam \n', '\n', 'VIVAMUS mea Lesbia, atque amemus,\n',
'rumoresque senum seueriorum\n', 'omnes unius aestimemus assis!\n', 'soles

Python2(ဘာသာျ ပန္) Han Phyo Oo 102


occidere et redire possunt:\n', 'nobis cum semel occidit breuis lux,\n',
'nox est perpetua una dormienda.\n', 'da mi basia mille, deinde centum,\n',
'dein mille altera, dein secunda centum,\n', 'deinde usque altera mille,
deinde centum.\n', 'dein, cum milia multa fecerimus,\n', 'conturbabimus
illa, ne sciamus,\n', 'aut ne quis malus inuidere possit,\n', 'cum tantum
sciat esse basiorum.\n', '(GAIUS VALERIUS CATULLUS)']
>>> print poem[2]
VIVAMUS mea Lesbia, atque amemus,
ေ ာ္ျ ပ စ မာမာ poem တစ္ ိုလံိုးကို list poem အေပနပနဲာ့ read လို ္ေ း ပတမ္္။ line 3
ကိုလို င္အရင္င poem[2] လိုန္႔အသံိုးျ ဳေပနိုင္ ပတမ္္။

ေပနာက္တစ္ပနည္းကေတာာ့ read() ျ စ္ ပတမ္္။ သကေတာာ့ file တစ္ ိုလံိုးကို string


ေျ ာင္းေ း ပတမ္္။
>>> poem = open("ad_lesbiam.txt").read()
>>> print poem[16:34]
VIVAMUS mea Lesbia
>>> type(poem)
<type 'str'>
>>>
String မာ carriage return ၊ line feed ေတြ ပ ပ ပတမ္္။

"How to get into a Pickle"

Data ေတြကိုေပနာက္တစ္ ပလြမ္လြမ္ ျ ပန္သိုးံ ပနိုင္ေအာင္ ဘမ္လိုလို ္မလဲ? Data ေတြကို


“pickling” လို ္ ပမမ္္။

Python မာ “pickle”လိုန္႔ေ ခတဲာ့ Module တစ္ ို ပ ပတမ္္။ pickle module သံိုးျ ါးေတာာ့ python
object ေတြကို serialize / de-serialize လို ္ပနင္ ပတမ္္။ “pickilng” ဆတ
ို ာကေတာာ့ python
object ေတြကို byte stream အျ စ္ေျ ာင္းလဲတာျ စ္ျ ါး ္။ “unpickling”ကေတာာ့
ေျ ာင္းျ ပန္ျ စ္ ပတမ္္။ byte stream ကေပန python object ေျ ာင္းေ းတာ ပ္။ pickling and
unpickling ကို data structre ကို “serialization” သိုန္႔ “flattening”လိုန္႔လည္းသႀက ပတမ္္။

Pickle module အရဲာ့ dump method ပနဲန္႔ dump(ေျ ာင္းလဲ) ပနိုင္ ပတမ္္။
pickle.dump(obj, file[,protocol])
object “obj”အရဲာ့ serialized version က file က
ဲ ိုေအရာက္သြား ပမမ္္။ protocol ကေတာာ့ object
ကိုဘမ္လို write လို ္မလဲေျ ာတာ ပ္။

 0=ascii
 1=compact (not human readable)
 2=optimised classes

Pickle.dump method ပနဲာ့ file က


ဲ ို dump လို ္ ာ့တ
ဲ ာ့ဲ object ေတြကို program ကေပနျ ါးတာာ့
pickle.load(file) ပနဲာ့ ျ ပန္ တ္ ပတမ္္။ pickle.load ကဘမ္္format ပနဲန္႔ data write လို ္ ာ့လ
ဲ ဲ
အလိုအေလ ာက္သ ပတမ္.
import pickle

Python2(ဘာသာျ ပန္) Han Phyo Oo 103


data = (1.4,42)
output = open('data.pkl', 'w')
pickle.dump(data, output)
output.close()

code execute လို ္ျ ါးအရင္ေတာာ့ data.pkl မ


ဲ ာ ဒါလိုအရ ပတမ္္။
(F1.3999999999999999
I42
tp0
.
File ကိုလြမ္ကစြာ ဲ read ျ ပန္လို ္ပနိုင္ ပတမ္္။
>>> import pickle
>>> f = open("data.pkl")
>>> data = pickle.load(f)
>>> print data
(1.3999999999999999, 42)
>>>
Object ေတြသာ မတ္ေ းတာျ စ္ျ ါး object name ေတြတာာ့မ ပ ပဘး္။ ဒပေႀကာင္ာ့ data ကို
assign လို ္ ာ့တ
ဲ ာျ စ္ ပတမ္္။data = pickle.load(f).

Python2(ဘာသာျ ပန္) Han Phyo Oo 104


Chapter 27
Modular Programming and Modules

Modular Programming

မမအရဲာ့ program ေတြကိုလမ


ြ ္လြမ္ကက ပန္းသမ္းပနိုင္ေအာင္ Modular software design
ေတြသံိုးသင္ာ့ ပတမ္္။ modular programming ကေတာာ့ code ေတြကို သါးျ ား
အစတ္အ ိုင္းေလး ေတြအျ စ္ ျဲြ ားတဲာ့ software desing technique တစ္ ို ဲျ စ္ ပတမ္္။
၎အစတ္အ ိုင္း ေလးေတြကို module လိုန္႔ေ ခ ပတမ္္။ ဒါလို ို္င္းျ ားအရတဲာ့အ ပမာ
တစ္ ိုင္းပနဲာ့တစ္ ိုင္း မါ ိုမ(dependency )ပနည္းေအာင္းအေလး ားအရ ပတမ္္။ Modular system
တစ္ ိုတည္ေဆာက္ အရာမာ module ေတြကိုသါးျ ားစါတည္ေဆာက္ျ ါးေတာာ့ ၎တိုန္႔ေ ပင္းစ ္အရမ
executable application တစ္ ိုျ စ္ ပတမ္္။

Python မာ module ဆိုတာကေတာာ့ python statement ေတြ definition ေတြ ပတဲာ့ file
တစ္ ို ပ ဲ္။ module ပနာမည္ကေတာာ့ file name ဲျ စ္ ပတမ္္။ ေပနာက္က file extension ျ စ္တာ့ဲ
.py ည္ာ့စာမလို ပဘး္။ fibonacci.py ဆိုအရင္ Module name က Fibonacci ျ စ္ ပတမ္္။
eg.fibonacci.py
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def ifib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
ဒါmodule ကို interactive shell မာ Import လို ္ျ ါးအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> import fibonacci
>>> fibonacci.fib(30)
832040
>>> fibonacci.ifib(100)
354224848179261915075L
>>> fibonacci.ifib(1000)
434665576869374564356885276750406258025646605173717804024817290895365554179
490518904038798400792551692959225930803226347752096896232398733224711616429
96440906533187938298969649928516003704476137795166849228875L
>>>
module function name ေတြကိုတိုသာြ းေအာင္ local name ေတြပနဲံအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> fib = fibonacci.ifib
>>> fib(10)
55
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 105


More on Modules

Module ေတြ မ
ဲ ာ function ေတြ ပပနို္င္သလို statement ေတြလည္း ပပနင္ ပတမ္္။ ၎
statement ေတြကို module initialize လို ္ ိုန္႔သံိုးပနိုင္ ပတမ္္။ ျ ါးေတာာ့ ၎ statement ေတြကို
module import လို ္တဲာ့အ ပမာ ဲ execute လို ္ ပတမ္္။

Module မာ private symbol table အရ ပတမ္္။ module မ


ဲ ာ အရတဲာ့ function ေတြကေတာာ့
၎ကို global symbol table အျ စ္အသံိုးျ ဳေႀက ပတမ္္။ user အရဲာ့ global variable ပနဲန္႔ module အရဲ႕
global variable ေတြ ပနာမည္တတဲာ့အ ပ clash (error)မျ စ္ေအာင္ကာကြမ္ေ း ပတမ္္။
module အရဲာ့ global variable ကို function ေတြလို ဲ အသံိုးျ ဳေပနိုင္ ပတမ္္။ i.e.
modname.name

Module မာ အျ ား module ေတြကို import လို ္ပနိုင္ ပတမ္္။ script သိုန္႔ module ေတြမာ
Import ကိုအအရင္ ္ဆံိုးမာ ေအရးႀက ပတမ္္။

Importing Names from a Module Directly

Module ဲက name ေတြကို import လို ္ေပနတဲာ့ module အရဲာ့ symbol table ဲ တိုက္အရိုက္
import လို ္ပနင္ ပတမ္္။
>>> from fibonacci import fib, ifib
>>> ifib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Local symbol table မ
ဲ ာေတာာ့ ဘမ္Module ကေပနimport
လို ္တမ္ဆိုတာအရမာမဟိုတ္ ပဘး္။ module မ
ဲ ာ အရတဲာ့ name အားလံိုးကို import
လို ္ပနိုင္ေ မမ္ာ့ recommend မေ း ပဘး္။
>>> from fibonacci import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
မလို ္သင္ာ့ေ မဲiန္႔ nteractive session ေတြမာ ေတာာ့ typing အရိုက္အရသက္သာေစ ပတမ္္။

အေအရးႀကါးတာတစ္ ိုက interpreter session တစ္ ိုမာ တစ္ ပ ဲ Import လို ္ပနိုင္ ပတမ္္။
တကမ္ လိုာ့module မာ ေျ ာင္းလဲမတစ္ ိုအရအရင္ interpreter ကို restart လို ္အရင္လို ္ မလို ္အရင္
reload(modulename) လို ္ေ းအရ ပမမ္္။

Executing Modules as Scripts

Python module ေတြဟာ script ေတြ ဲျ စ္တာေႀကာင္ာ့ script ေတြလို ဲ run ပနင္ ပတမ္္။
python fibo.py

Python2(ဘာသာျ ပန္) Han Phyo Oo 106


module ကို script အျ စ္သံိုးတဲာ့အ ပ execute လို ္ေ မမ္ာ့ ၽြင္း က္တစ္ ိုအရ ပတမ္္။ system
variable __name__ ကို “__main__” အျ စ္သတ္မတ္လိုက္တာ ပ္။ ဒပေႀကာင္ာ့ module ကို
အေျ အေပန ႏွာစ္မ ဳေးပနဲာ့ အသံိုးျ ဳေပနိုင္ေအာင္ ေအရးသားပနိုင္ ပတမ္္။ ေအာက္ ပ ံိုစံအတိုင္းဆိုလ င္ file
ကို module သိုန္႔ script အျ စ္သံိုးပနိုင္ ပတမ္္။ ဒပေ မမ္ာ့ script အျ စ္ သံိုးမသာလ င္ fib method
က command line arguament တစ္ ိုပနဲာ့ စတင္ ပလမ္ာ့မမ္္။
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
script အျ စ္ သံိုးႀကည္ာ့အရင္ ေအာက္ ပအတိုင္းျမင္အရ ပလမ္ာ့မမ္္။
$ python fibo.py 50
1 1 2 3 5 8 13 21 34
Import လို ္ျ ါးသံိုးအရင္ေတာာ့ if block က
ဲ အလို ္လို ္မာမဟိုတ္ ပဘး
>>> import fibo
>>>

Renaming a Namespace

Module Import လို ္တဲာ့အ ပ namespace အရဲာ့ name ကိုေျ ာင္းလဲပနိုင္ ပတမ္္။
>>> import math as mathematics
>>> print mathematics.cos(mathematics.pi)
-1.0
Namespace အရေပနေ မဲာ့ ပနာမည္ေတာာ့တေတာာ့မာမဟိုတ္ ပဘး္။ method အ ဳေန္႔ကို ဲ Import
လို ္ င္အရင္လည္းအရ ပတမ္္။
>>> from math import pi,pow as power, sin as sinus
>>> power(2,3)
8.0
>>> sinus(pi)
1.2246467991473532e-16

Kinds of Modules

Module အမ ဳေးအစားမ ားစြာအရ ပတမ္

 Python မာ ေအရးသား ားတာေတြ


They have the suffix: .py
 Dynamically linked C modules
Suffixes are: .dll, .pyd, .so, .sl, ...
 C-Modules linked with the Interpreter:
It's possible to get a complete list of these modules:
o import sys
o print sys.builtin_module_names

Python2(ဘာသာျ ပန္) Han Phyo Oo 107


An error message is returned for Built-in-Modules.

Module Search Path

Module import လို ္အရာမာ interpreter က ေအာက္ေ ာ္ျ ပအစစ္အတိုင္း module


ကိုအရာ ပတမ္္။

1.top-level file အရတဲာ့ေပနအရာ ္။လက္အရ run ေပနတဲာ့ file အရအရာေပနအရာျ စ္ ပတမ္္။

2. PYTHONPATH global variable မ


ဲ ာ သတ္မတ္ ားတဲာ့ directory ေတြ

3.standard installation path eg./usr/lib/python2.5

Module import လို ္ျ ါးသြားအရင္ သဘမ္မာအရလဲႀကည္ာ့ပနင္ ပတမ္္။


>>> import math
>>> math.__file__
'/usr/lib/python2.5/lib-dynload/math.so'
>>> import random
>>> random.__file__
'/usr/lib/python2.5/random.pyc'

Content of a Module

Built-in function dir() ပနဲာ့ module ပနဲာ့သက္ဆိုင္တာ့ဲ attribute ေတြmethod ေတြကို


သအရပနို္င္ ပတမ္္။
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin',
'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees',
'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians',
'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>
Dir() မာ argument မ ပအရင္ေတာာ့ လက္အရ local scoper ဲက name ေတြ ပ ပမမ္္။
>>> import math
>>> col = ["red","green","blue"]
>>> dir()
['__builtins__', '__doc__', '__name__', 'col', 'math']

Built-in function ေတြကိုလည္းႀကည္ာ့ပနင္ ပတမ္္။


>>> import __builtin__
>>> dir(__builtin__)

Python2(ဘာသာျ ပန္) Han Phyo Oo 108


['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FloatingPointError', 'FutureWarning',
'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning',
...

Module Packages

Module ေတြကို package မ


ဲ ာလည္း ည္ာ့ပနိုင္ ပတမ္္။ pyton code ေတြစို ားတဲာ့ directory
ကို package လိုန္႔ေ ခ ပတမ္္။ package က Moudle import လို ္သလို သ
ဲ ံိုး ပတမ္္။

Package မ
ဲ ာ ပ၀င္တာ့ဲ directory တိုင္းမာ __init__.py ဆိုတဲာ့ file ပ၀င္အရ ပမမ္္။
မဟိုတ္အရင္ေတာာ့ import လို ္လိုန္႔မအရ ပဘး္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 109


Chapter 28
Regular Expressions

“regular expression”ကို တစ္ ပတစ္အရံ regex သိုန္႔ rexexp လိုန္႔လည္းေ ခႀက ပတမ္္။

Text ေတြ textstring ေတြကို filtering လို ္ ိုန္႔ regular expression ေတြကသ
ို ံိုးႀက ပတမ္္။

Regular expression အတြန္႔က္ syntax ေတြဟာ programming language ေတြအားလံိုးမာ


အတတ ဲျ စ္ ပတမ္္။

Introduction

Sequential data type ေတြတပန


ို ္းက “in” operator ကိုေျ ာ ဲာ့ ပတမ္္။ string တစ္ ို ဲမာ အျ ား
string တစ္ ို ပလား စစ္ႀကည္ာ့အရေအာင္
>>> s = "Regular expressions easily explained!"
>>> "easily" in s
True
>>>
တဆင္ာ့ျ င္းႀကည္ာ့အရေအာင္

String sub=”abc”

က string s= "xaababcbcd" မာ ပလားစစ္တမ္္။

အအရင္ဆံိုး မေပနအရာတလားစစ္မမ္ i.e. s[0] == sub[0].

မတဘးဆိုေတာာ့ ေပနာက္တစ္ ိုကိုေအရြန္႔မမ္္။

မတအရင္ ဒိုတမတလားဆက္စစ္အရမမ္ မတဆက္ေအရြန္႔ ဒို တအရင္ တတမစစ္ မတေအရြန္႔ တအရင္


ok ေ ပာ့္။

အကိုပန္ကိုပန္လိုန္႔မမတအရင္ေတာာ့ s မ
ဲ ာ sub မ ပဘးေ ပာ့္။

A Simple Regular Expression

ဒပကို regular expression သံိုးျ ါး လြမ္ကစြာေျ အရင္းပနိုင္ ပတမ္္။ pyrhon မာ regular


expression သံိုးမမ္ဆိုအရင္ “re” module ကို import လို ္ေ းအရ ပမမ္္။

Representing Regular Expressions in Python

အျ ား Language ေတြမာ regular expression ကို “/”ႀကားမာ ေအရး ပလမ္ာ့မမ္္။ python


မာေတာာ့ regular expression ကို ံိုမပန္ string ေတြလို ေ
ဲ အရး ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 110


ျ ပနာတစ္ ိုကေတာာ့ backslash က regular expression မာ special character အေပနပနဲာ့
အသံိုးျ ဳေ ျ ါးေတာာ့ string မာ ကေတာာ့ escape character အျ စ္အသံိုးျ ဳေ ပတမ္္။ ဒါ အ ပမာ
python က string အရဲာ့ backslash ေတြအျ စ္ evaluate အအရင္လို ္မာျ စ္ျ ါး က ပန္တာေတြကိုမ
regular expression အျ စ္သတ္မတ္ ပလမ္မမ္ာ့္။ ဒပကိုကာကြမ္ ိုန္႔အတြက္ double backslash
“\\” အသံိုးျ ဳေပနိုင္ ပတမ္္။ အေကာင္းဆံိုးကေတာာ့ regular expression ေတြကို raw string
အျ စ္အသံိုးျ ဳေတာျ စ္ ပတမ္္။
r"^a.*\.html$"

ဒါစ မာမာ a ပနဲာ့ စတင္ျ ါး .html ပနဲာ့ အဆံိုးသတ္တဲာ့ file အားလံိုးျ စ္ ပတမ္္။

Syntax of Regular Expressions

r”cat” ဆိုတာ regular expression တစ္ ို ပ္။ သက "A cat and a rat can't be friends." ပနဲာ့
ဆိုအရင္ match ျ စ္ ပတမ္္။

ဒပေ မမ္ာ့ဒါမာ အမားတစ္ ိုအရ ပတမ္္။ cat လိုန္႔ဆိုလိုေ မမ္ာ့ အျ ားစကားလံိုးေတြပနဲာ့လည္း ကိုက္ညါ
ေပန ပေသးတမ္္။ စ မာ “education” "communicate", "falsification", "ramifications",
"cattle” စသျ င္ာ့စကားလံိုးေတြ ပ ဲာ့အရင္လည္း match ျ စ္ေပန ပလမ္ာ့မမ္္။ ဒပကို “over
matching”လိုန္႔ဆို ပတမ္္။

ဒပကိုေအရာင္အရား င္တာ့အ
ဲ ပ r” cat ”ဆိုျ ါး ေဘးမာ black ေတြ ား င္ ားပနိုင္ ပတမ္္။
ိုပနစကားလံိုးေတြမ ပေတာာ့ေ မမ္ာ့ ေပနာက္ျ ပနာတစ္ ို ္ျ စ္ ပတမ္္။ "The cat, called
Oscar, climbed on the roof." မာဆိုအရင္ cat ေပနာက္မာ “,” ပလာတဲာ့အတြက္ match
မျ စ္ေတာာ့ ပ ဘး္။

Python မာ regular expression ကိုဘမ္လိုသံိုးလဲအအရင္ႀကည္ာ့အရေအာင္္။


>>> import re
>>> x = re.search("cat","A cat and a rat can't be friends.")
>>> print x
<_sre.SRE_Match object at 0x7fd4bf238238>
>>> x = re.search("cow","A cat and a rat can't be friends.")
>>> print x
None
အ က္ေ ာ္ျ ပစ မာမ ာ regular expression ကိုအသံိုးျ ဳေ ိုန္႔ re module ကို import
လို ္ ားတာေတြန္႔အရ ပမမ္္။ အေအရးအႀကါးဆံိုး ပနဲာ့ အသံိုးအမ ားဆံိုးျ စ္ ပတမ္္။ re.search(expr,s)
ကေတာာ့ s ဆိုတဲာ့ string မ
ဲ ာ expr ေ ခ regular expression ပနဲန္႔ကိုက္တဲာ့ substring
ေတြအရာေ း ပတမ္္။ မဆံိုး ကိုက္ညါတာ့ဲ substring ကို ို ္ေ း ပတမ္္။ match ျ စ္အရင္ match
object ကို result အျ စ္ ိုတ္ေ းျ ါး မျ စ္အရင္ေတာာ့ none ပ္။
>>> if re.search("cat","A cat and a rat can't be friends."):
... print "Some kind of cat has been found :-)"
... else:
... print "No cat has been found :-("
...

Python2(ဘာသာျ ပန္) Han Phyo Oo 111


Some kind of cat has been found :-)
>>> if re.search("cow","A cat and a rat can't be friends."):
... print "Cats and Rats and a cow."
... else:
... print "No cow around."
...
No cow around.

Any Character

အေ ခမာျ ဲာ့တဲာ့ example လို cat ကိုမအရာ ဲ at ပနဲန္႔ အဆံိုးသတ္တဲန္႔ character သံိုးလံိုး ပ ကိုအရာမမ္္။

“any character” အတြက္ က “.”ျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ ို example အတြက္ဆိုအရင္

r“ .at ”

ျ စ္ ပတမ္္။ဒပဆိုအရင္ "rat", "cat", "bat", "eat", "sat" ေတြအျ ားတိုက္ဆိုင္တာေတြအရလာ ပလမ္ာ့


မမ္္။

ဒပေ မမ္ာ့ "@at" or "3at" လိုစကားလံိုးေတြ ပအရင္လည္းေ ာ္ျ ပလမ္န္႔မမ္္။ overmatching ပ ဲ

Character Classes

Square bracket “[” “]” ေတြကို ပေစ င္တာ့စ


ဲ ကားလံိုးေတြေအရးအရင္သံိုး ပတမ္္။ [xyz]ဆိုအရင္ x သိုန္႔
y သိုန္႔ z လိုာ့ဆိုလို ပတမ္္။
r"M[ae][iy]er"
German surname တစ္ ိုပနဲာ့တိုက္တာအရာတာ ပ္။ Maier, Mayer, Meier, Meyer စတဲာ့
သံတေႀကာင္း ကြဲ စကားလံိုးေတြအတြက္ျ စ္ ပတမ္္။

အ ိုလို စကားလံိုးတစ္လံိုးႏွာစ္လံိုးအတြက္ မဟိုတ္ ဲ အစိုလိုက္စစ္တာေတြလည္းျ စ္ပနိုင္ ပတမ္္။

ဒပဆိုအရင္ေတာာ့ “-” ကိုသံိုးအရ ပမမ္္။ [a-e] ဆိုအရင္ [abcde] [0-5]ဆိုအရင္ [012345]ျ စ္ ပတမ္္။

“-” ကိုစကားလံိုးႀကားေတြ မ
ဲ ာမသံိုး ဲ ေအရာ့မာသိုန္႔ ေပနာက္မာသံိုးအရင္ေတာာ့ “-
”တစ္ ိုကိုဆိုလို ပတမ္္။ [-az] ဆိုအရင္ - or a or z လိုန္႔ဆိုလို ပတမ္္။

Predefined Character Classesing list:

\d =[0-9]

\D=[^0-9]

\s=[\t\n\r\f\v]

Python2(ဘာသာျ ပန္) Han Phyo Oo 112


\S=[^\t\n\r\f\v]

\w=[a-zA-Z0-9]

\W=\w မဟိုတ္တာ

\b=empty string ျ စ္ျ ါးေတာာ့ စကားလံိုးတစ္ ိုအရဲာ့ေအရာ့ သိုန္႔ ေပနာက္မာအရမမ္္။

\B= empty string ျ စ္ျ ါးေတာာ့ စကားလံိုးတစ္ ိုအရဲာ့ေအရာ့ သိုန္႔ ေပနာက္မာ မအရအရဘး

\\=\

Matching Beginning and End

the expression r"M[ae][iy]er" က string မ


ဲ ာ အရတဲာ့ဘမ္ေပနအရာမာမဆိုအရာေ ြပနို္င္ ပတမ္္။
>>> import re
>>> line = "He is a German called Mayer."
>>> if re.search(r"M[ae][iy]er",line): print "I found one!"
...
I found one!
>>>

မမက string အစမာ ဲအရာ င္တမ္ဆိုအရင္ဘမ္လိုလို ္မလဲ၊ re module မာ matching အတြက္


function ႏွာစ္ ို ပ ပတမ္္။ search() and match()
>>> import re
>>> s1 = "Mayer is a very common Name"
>>> s2 = "He is called Meyer but he isn't German."
>>> print re.search(r"M[ae][iy]er", s1)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.search(r"M[ae][iy]er", s2)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.match(r"M[ae][iy]er", s1)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.match(r"M[ae][iy]er", s2)
None
>>>
ဒပဆိုအရင္ေတာာ့အရ ပျ ါ ဒပေ မမ္ာ့ ဒပက python မာ ဲသံိုးလိုန္႔အရမာ ပ္။

“^” က string အစကိုေျ ာတာျ စ္ ပတမ္္။ MULTILINE mode မာေတာာ့ newline စတိုင္း
match ျ စ္ ပတမ္္။
>>> import re
>>> s1 = "Mayer is a very common Name"
>>> s2 = "He is called Meyer but he isn't German."
>>> print re.search(r"^M[ae][iy]er", s1)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.search(r"^M[ae][iy]er", s2)
None

Python2(ဘာသာျ ပန္) Han Phyo Oo 113


ဒပေ မမ္ာ့ s1 ပနဲာ့ s2 ကို ဒါလိုေ ပင္းလိုက္အရင္ဘာျ စ္ပနိုင္ ပသလဲ္။
s = s2 + "\n" + s1

maier လိုစကားလံိုးအစေတြမအရေ မဲာ့ newline character တစ္ ို ပလာ ပတမ္္။


>>> s = s2 + "\n" + s1
>>> print re.search(r"^M[ae][iy]er", s)
None
>>>
String အစကို ဲစစ္တာျ စ္တာ့အ
ဲ တြက္ name ကိုမေတြန္႔ေတာာ့ ပဘး္။ multine mode သံိုးအရင္ေတာာ့
တစ္မ ဳေးျ စ္သာြ း ပလမာ့္မမ္္။
>>> print re.search(r"^M[ae][iy]er", s, re.MULTILINE)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.search(r"^M[ae][iy]er", s, re.M)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.match(r"^M[ae][iy]er", s, re.M)
None
>>>

စာေႀကာင္းအစမာ အရာျ ါးေတာာ့ အဆံိုးမာအရာအရေအာင္ ဒပဆိုအရင္ေတာာ့ “$” ကိုသံိုး ပမမ္္။


>>> print re.search(r"Python\.$","I like Python.")
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.search(r"Python\.$","I like Python and Perl.")
None
>>> print re.search(r"Python\.$","I like Python.\nSome prefer Java or
Perl.")
None
>>> print re.search(r"Python\.$","I like Python.\nSome prefer Java or
Perl.", re.M)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>>

Optional Items

Mayer ဆိုတဲာ့ ပနာမည္မာအအရင္ ပနာမည္ေတြအျ င္ e ကိုျ ဳေတ္ ားတဲာ့ ံိုစံေတြ ["Mayr", "Meyr",
"Meir", "Mair"] plus our old set ["Mayr", "Meyr", "Meir", "Mair"].အရ ပေသးတမ္္။

e က င္ ပပနိုင္တမ္လိုန္႔ေျ ာ င္အရင္ “?” ေလးသံိုး ပတမ္္။


r"M[ae][iy]e?r"
“feb 2011” သိုန္႔ “February 2011” အတြက္ဆိုလ င္
r"Feb(ruary)? 2011"

Quantifiers

Python2(ဘာသာျ ပန္) Han Phyo Oo 114


zero to infinity အႀကမ္ေအရအတြက္ဆိုအရင္ “*”
r"[0-9]*"

အႀကမ္အေအရအတြက္အတအက သိုန္႔ range တစ္ ိုပနဲန္႔ေအရး င္တမ္ဆိုအရင္ {} မ


ဲ ာေအရးေ းအရမမ္
r"^[0-9]{4} [A-Za-z]*"
min max အတြက္ဆိုအရင္ {from, to} ိုစ
ံ ံေအရးအရမမ္
r"^[0-9]{4,5} [A-Z][a-z]{2,}"

Grouping

Regurlar expression ေတြကို group ြန္႔ဲ င္အရင္ () ပနဲန္႔ အသံိုးျ ဳေပနိုင္ ပတမ္္။

Capturing Groups and Backreferences

A Closer Look at the Match Objects

Re.search() method သံိုးတာမာ match ျ စ္အရင္ Match object return ျ ပန္ျ ါး မျ စ္အရင္ None
ပ္။ match object မ
ဲ ာ data ေတြအျမားအျ ား ပ၀င္ ပတမ္္။

Match object မာ group(),span(),start(),end() စတဲာ့ method ေတြ ပ၀င္ ပတမ္္။


>>> import re
>>> mo = re.search("[0-9]+", "Customer number: 232454, Date: February 12,
2011")
>>> mo.group()
'232454'
>>> mo.span()
(17, 23)
>>> mo.start()
17
>>> mo.end()
23
>>> mo.span()[0]
17
>>> mo.span()[1]
23
>>>
Span() က အစပနဲာ့အဆံိုး position ေတြ return ျ ပန္ေ း ပတမ္္။ start() ပနဲာ့ end() ကလည္း
ဒါသေဘာ ပ ဲ္။ group() ကေတာာ့argument မ ပအရင္ regular expression ပနဲံတိုက္တဲာ့ substring
ကို ိုတ္ေ း ပတမ္္။
>>> import re
>>> mo = re.search("([0-9]+).*: (.*)", "Customer number: 232454, Date:
February 12, 2011")

Python2(ဘာသာျ ပန္) Han Phyo Oo 115


>>> mo.group()
'232454, Date: February 12, 2011'
>>> mo.group(1)
'232454'
>>> mo.group(2)
'February 12, 2011'
>>> mo.group(1,2)
('232454', 'February 12, 2011')
>>>

Xml/html tag ေတြပနဲန္႔စ မာႀကည္ာ့ႀကည္ာ့အရေအာင္


<composer>Wolfgang Amadeus Mozart</composer>
<author>Samuel Beckett</author>
<city>London</city>
ဒါtextကိုေအာက္ ပအတိုင္းေျ ာင္း င္တမ္္။
composer: Wolfgang Amadeus Mozart
author: Samuel Beckett
city: London
ေအာက္ ပ python script ေလးကအလို ္လို ္ေ း ပလမ္ာ့မမ္္။ အဓကကေတာာ့ regular
expresson ပ္။ “<” အအရင္အရာတမ္္။ “>” မေတြန္႔မ င္း lower case letter ေတြကို တ္တမ္္။ “<”
“>” ႀကား ေ
ဲ တြန္႔သမ ကို backreference အေပနပနဲာ့သမ္း ားျ ါး \1 ဆိုတဲာ့ expression ပနဲန္႔
ျ ပန္သံိုးပနိုင္တမ္္။expression က “>”ကိုေအရာက္တဲာ့အ ပမာ \1 မာ composer ပတမ္ဆို ပဆိုန္႔္။
import re
fh = open("tags.txt")
for i in fh:
res = re.search(r"<([a-z]+)>(.*)</\1>",i)
print res.group(1) + ": " + res.group(2)
() တစ္စံို က္ ိုအရင္ backreference ေတြကို \1,\2,\3 စသျ င္ာ့သတ္မတ္ ပတမ္္။

Named Backreferences

အေ ခမာ ျ ဲာ့တာကို "Numbered Capturing Groups" and "Numbered Backreferences"


လိုန္႔ေ ခပနိုင္ ပတမ္္။ numbered capturing group အစား capturing group ေတြသံိုးအရင္ ေတာာ့
automatic number ေတြအစား ပနာမည္ေလးေတြေ းျ ါးအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> import re
>>> s = "Sun Oct 14 13:47:03 CEST 2012"
>>> expr = r"\b(?P<hours>\d\d):(?P<minutes>\d\d):(?P<seconds>\d\d)\b"
>>> x = re.search(expr,s)
>>> x.group('hours')
'13'
>>> x.group('minutes')
'47'
>>> x.start('minutes')
14
>>> x.end('minutes')
16
>>> x.span('seconds')

Python2(ဘာသာျ ပန္) Han Phyo Oo 116


(17, 19)
>>>

Comprehensive Python Exercise

In this comprehensive exercise, we have to bring together the information of two files. In the first
file, we have a list of nearly 15000 lines of post codes with the corresponding city names plus
additional information. Here are some arbitrary lines of this file:
68309,"Mannheim",8222,"Mannheim",8,"Baden-Wrttemberg"
68519,"Viernheim",6431,"Bergstraße",6,"Hessen"
68526,"Ladenburg",8226,"Rhein-Neckar-Kreis",8,"Baden-Württemberg"
68535,"Edingen-Neckarhausen",8226,"Rhein-Neckar-Kreis",8,"Baden-
Württemberg"
The other file contains a list of the 19 largest German cities. Each line consists of the rank, the name
of the city, the population, and the state (Bundesland):
1. Berlin 3.382.169 Berlin
2. Hamburg 1.715.392 Hamburg
3. München 1.210.223 Bayern
4. Köln 962.884 Nordrhein-Westfalen
5. Frankfurt am Main 646.550 Hessen
6. Essen 595.243 Nordrhein-Westfalen
7. Dortmund 588.994 Nordrhein-Westfalen
8. Stuttgart 583.874 Baden-Württemberg
9. Düsseldorf 569.364 Nordrhein-Westfalen
10. Bremen 539.403 Bremen
11. Hannover 515.001 Niedersachsen
12. Duisburg 514.915 Nordrhein-Westfalen
13. Leipzig 493.208 Sachsen
14. Nürnberg 488.400 Bayern
15. Dresden 477.807 Sachsen
16. Bochum 391.147 Nordrhein-Westfalen
17. Wuppertal 366.434 Nordrhein-Westfalen
18. Bielefeld 321.758 Nordrhein-Westfalen
19. Mannheim 306.729 Baden-Württemberg
Our task is to create a list with the top 19 cities, with the city names accompanied by the postal
code. If you want to test the following program, you have to save the list above in a file called
largest_cities_germany.txt and you have to download and save the list of German post codes
# -*- coding: iso-8859-15 -*-

import re

fh_post_codes = open("post_codes_germany.txt")
PLZ = {}
for line in fh_post_codes:
(post_code, city, rest) = line.split(",",2)
PLZ[city.strip("\"")] = post_code

fh_largest_cities = open("largest_cities_germany.txt")

for line in fh_largest_cities:

Python2(ဘာသာျ ပန္) Han Phyo Oo 117


re_obj = re.search(r"^[0-9]{1,2}\.\s+([\wÄÖÜäöüß\s]+\w)\s+[0-9]",line)
city = re_obj.group(1)
print city, PLZ[city]

Another Comprehensive Example


We want to present another real life example in our Python course. A regular expression for UK
postcodes.
We write an expression, which is capable of recognizing the postal codes or postcodes of the UK.

Postcode units consist of between five and seven characters, which are separated into two parts by
a space. The two to four characters before the space represent the so-called outward code or out
code intended to direct mail from the sorting office to the delivery office. The part following the
space, which consists of a digit followed by two uppercase characters, comprises the so-called
inward code, which is needed to sort mail at the final delivery office. The last two uppercase
characters can be only one of these ABDEFGHJLNPQRSTUWXYZ

The outward code can have the form: One or two uppercase characters, followed by either a digit or
the letter R, optionally followed by an uppercase character or a digit. (We do not consider all the
detailed led rules for postcodes, i.e only certain character sets are valid depending on the position
and the context.)
A regular expression for matching this superset of UK postcodes looks like this:
r"\b[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}\b"
The following Python program uses the regexp above:
import re

example_codes = ["SW1A 0AA", # House of Commons


"SW1A 1AA", # Buckingham Palace
"SW1A 2AA", # Downing Street
"BX3 2BB", # Barclays Bank
"DH98 1BT", # British Telecom
"N1 9GU", # Guardian Newspaper
"E98 1TT", # The Times
"TIM E22", # a fake postcode
"A B1 A22", # not a valid postcode
"EC2N 2DB", # Deutsche Bank
"SE9 2UG", # University of Greenwhich
"N1 0UY", # Islington, London
"EC1V 8DS", # Clerkenwell, London
"WC1X 9DT", # WC1X 9DT
"B42 1LG", # Birmingham
"B28 9AD", # Birmingham
"W12 7RJ", # London, BBC News Centre
"BBC 007" # a fake postcode
]

pc_re = r"[A-z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}"

for postcode in example_codes:


r = re.search(pc_re, postcode)
if r:
print postcode + " matched!"

Python2(ဘာသာျ ပန္) Han Phyo Oo 118


else:
print postcode + " is not a valid postcode!"

Python2(ဘာသာျ ပန္) Han Phyo Oo 119


Chapter 29
Regular Expressions(Advanced)

Regular expression introduction မာ regular expression အတြက္ basic concept ေတြ ေလ


ေလန္႔လာ ဲာ့ႀက ပတမ္္။ အရိုးအရင္းတဲန္႔ regular expression ေတြ္။ re module က search() match()
method ေတြ္။ formatting ပနဲန္႔ built-in character clsss ေတြ \d, \D, \s, \S, ေတြလိုမ ဳေး
predefined character class ေတြ္။ string အစပနဲန္႔အဆံိုးေတြဘမ္လို တိုက္မလဲ္။optional item
ေတြအတြက္ ? အသံိုးျ ဳေ ံိုေတြ္။ quantifier ေတြသံိုးျ ါး အႀကမ္အေအရအတြက္ အတြက္သံိုးတာေတြ
စသျ င္ာ့သ ဲာ့ ပတမ္္။

Grouping ပနဲန္႔ backreference လည္းသအရ ပမမ္္။ ေပနာက္ျ ါးေတာာ့ re module အရဲာ့ match object
ေတြ သန္႔မာ ဘာ information ေတြ ပလ ဲ information ေတြကsို pan(), start(), end(), and
group() ေတြသံိုးျ ါးဘမ္လိုအရပနိုင္မလဲစသျ င္ာ့သအရ ပမမ္္။

Finding all Matched Substrings

Re module မာ အျ ား Language ေတြမာမ ပတဲာ့ method တစ္ ို ပ ပေသးတမ္္။


re.findall(pattern, string[, flags])
ဆိုအရင္ တိုက္ဆိုင္တဲာ့ string pattern ေတြကို string list အေပနပနဲန္႔ return ျ ပန္ေ း ပတမ္္။ ဘမ္မာ
ညာ စစ္တာျ စ္ျ ါးေတာာ့ ေတြန္႔အရတဲာ့ အစစ္အတိုင္း return ျ ပန္ ပတမ္္။
>>> t="A fat cat doesn't eat oat but a rat eats bats."
>>> mo = re.findall("[force]at", t)
>>> print mo
['fat', 'cat', 'eat', 'oat', 'rat', 'eat']
Pattern မ
ဲ ာ group ေတြ ပအရင္ group ေတြကို List အေပနပနဲာ့ return ျ ပန္ေ း ပတမ္္။ group
တစ္ ို က္ ိုအရင္ေတာာ့ tuples ေတြကို list အေပနပနဲန္႔ return ျ ပန္ေ း ပတမ္္။
>>> import re
>>> items = re.findall("[0-9]+.*: .*", "Customer number: 232454, Date:
February 12, 2011")
>>> print items
['232454, Date: February 12, 2011']
>>> items = re.findall("([0-9]+).*: (.*)", "Customer number: 232454, Date:
February 12, 2011")
>>> print items
[('232454', 'February 12, 2011')]
>>>

Alternations

Regular expression introduction မာ character classes ေတြအေႀကာင္းေျ ာ ဲာ့တမ္္။


character class ေတြမာဆိုအရင္ ကိုမ္လို င္တဲာ့ character set

Python2(ဘာသာျ ပန္) Han Phyo Oo 120


ကိုအသံိုးျ ဳေပနိုင္တမ္္။ ေပနာက္တစ္မ ိုးကေတာာ့ regular expression ေတြ က
ဲ မာ ျ
ျ ပန္ေအရြးတာျ စ္ ပတမ္္။ logical or ျ စ္ ပတမ္္။ “|”

ေအာက္ေ ာ္ျ ပ စ မာမာ ျမဳေ႕ေတြ ဲကေပနေအရြးတာျ စ္ ပတမ္္။ေ း ားတဲန္႔ျမဳေန္႔ေတြ က


ဲ တစ္ ိုေ ပန္႔
>>> import re
>>> str = "The destination is London!"
>>> mo = re.search(r"destination.*(London|Paris|Zurich|Strasbourg)",str)
>>> if mo: print mo.group()
...
destination is London
>>>

Compiling Regular Expressions

Regexp တစ္ ို ဲကို ္ ပ ္ ပျ ပန္သံိုး င္အရင္ regular expression object


ကိုသံိုးသင္ာ့ ပတမ္္။
re.compile(pattern[, flags])
compile က regex object ကို return ျ ပန္ေ း ပတမ္္။ သန္႔ကိုသံိုးျ ါးအရာေ ြတာေတြ
အစား ိုးတာေတြ လို ္ပနိုင္ ပတမ္္။ expression အရဲန္႔ behavior ကိုေတာာ့ flag value
ပနဲန္႔သတ္မတ္ေ း ပတမ္္။

Abbreviation Full name Description


re.I re.IGNORECASE Makes the regular expression case-insensitive
The behaviour of some special sequences like \w, \W,
re.L re.LOCALE \b,\s, \S will be made dependant on the current locale, i.e.
the user's language, country aso.
^ and $ will match at the beginning and at the end of each
re.M re.MULTILINE
line and not just at the beginning and the end of the string
re.S re.DOTALL The dot "." will match every character plus the newline
Makes \w, \W, \b, \B, \d, \D, \s, \S dependent on Unicode
re.U re.UNICODE
character properties
Allowing "verbose regular expressions", i.e. whitespace
are ignored. This means that spaces, tabs, and carriage
returns are not matched as such. If you want to match a
space in a verbose regular expression, you'll need to
escape it by escaping it with a backslash in front of it or
re.X re.VERBOSE
include it in a character class.
# are also ignored, except when in a character class or
preceded by an non-escaped backslash. Everything
following a "#" will be ignored until the end of the line, so
this character can be used to start a comment.

Python2(ဘာသာျ ပန္) Han Phyo Oo 121


Example

UK postcodes အတြက္ regular expression


r"[A-z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}"
ဒပကို regex object ပနဲာ့ သံိုးမမ္္။
>>> import re
>>> regex = r"[A-z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}"
>>> address = "BBC News Centre, London, W12 7RJ"
>>> compiled_re = re.compile(regex)
>>> res = compiled_re.search(address)
>>> print res
<_sre.SRE_Match object at 0x7fc9f688f6b0>
>>>

Splitting a String With or Without with Regular Expressions

String ေတြကို substring ေတြအျ စ္ ိုင္းတဲံ split ဆိုတဲန္႔ string method တစ္ ိုအရ ပတမ္္။
str.split([sep[, maxsplit]])

Split မာ optional parameter ႏွာစ္ ိုအရတမ္္။ ဘာမမ ည္ာ့ေ းအရင္ white space ေတြသံိုးျ ါး
ိုင္းေ းမမ္္။

Exampls
>>> law_courses = "Let reverence for the laws be breathed by every American
mother to the lisping babe that prattles on her lap. Let it be taught in
schools, in seminaries, and in colleges. Let it be written in primers,
spelling books, and in almanacs. Let it be preached from the pulpit,
proclaimed in legislative halls, and enforced in the courts of justice.
And, in short, let it become the political religion of the nation."
>>> law_courses.split()
['Let', 'reverence', 'for', 'the', 'laws', 'be', 'breathed', 'by', 'every',
'American', 'mother', 'to', 'the', 'lisping', 'babe', 'that', 'prattles',
'on', 'her', 'lap.', 'Let', 'it', 'be', 'taught', 'in', 'schools,', 'in',
'seminaries,', 'and', 'in', 'colleges.', 'Let', 'it', 'be', 'written',
'in', 'primers,', 'spelling', 'books,', 'and', 'in', 'almanacs.', 'Let',
'it', 'be', 'preached', 'from', 'the', 'pulpit,', 'proclaimed', 'in',
'legislative', 'halls,', 'and', 'enforced', 'in', 'the', 'courts', 'of',
'justice.', 'And,', 'in', 'short,', 'let', 'it', 'become', 'the',
'political', 'religion', 'of', 'the', 'nation.']
>>>
White space အရတဲာ့ေပနအရာေတြကို ိုင္းေ းသြား ပတမ္္။ semicolon “;” ပနဲန္႔ဲ ိုင္းႀကည္ာ့အရေအာင္္။
>>> line = "James;Miller;teacher;Perl"
>>> line.split(";")
['James', 'Miller', 'teacher', 'Perl']

Python2(ဘာသာျ ပန္) Han Phyo Oo 122


ေပနာက္ optional parameter က maxsplit ပ္။

Maxsplit ည္ာ့ေ းအရင္ result မာ “maxsplit+1” element ပ ပမမ္္။


>>> mammon = "The god of the world's leading religion. The chief temple is
in the holy city of New York."
>>> mammon.split(" ",3)
['The', 'god', 'of', "the world's leading religion. The chief temple is in
the holy city of New York."]
Blank ကို delimiter string အေပနပနဲာ့သံိုး ဲာ့တာေတြန္႔မာ ပ္။ အတြဲလိုက္အရတဲာ့ whitespace ေတြဆိုအရင္
split() က blank တစ္ ိုျ ါးတိုင္း တစ္ ပ ိုင္းမာ ပ္။
>>> mammon = "The god \t of the world's leading religion. The chief temple
is in the holy city of New York."
>>> mammon.split(" ",5)
['The', 'god', '', '\t', 'of', "the world's leading religion. The chief
temple is in the holy city of New York."]
>>>
Empty string ေတြမ ပ င္အရင္ first argument ကို None ည္ာ့ေ းအရ ပမမ္္။
>>> mammon.split(None,5)
['The', 'god', 'of', 'the', "world's", 'leading religion. The chief temple
is in the holy city of New York.']

Regular Expression Split

String split() Method ကေတာ္ေတာ္မ ားမ ားမာ အဆင္ေျ ပတမ္္။ ိုမိုအရဳေ ္ေ းြ တဲာ့ အလို ္ေတြ
အတြက္ေတာာ့ re module ဲက split ကိုသံိုးအရ ပမမ္္။
>>> import re
>>> metamorphoses = "OF bodies chang'd to various forms, I sing: Ye Gods,
from whom these miracles did spring, Inspire my numbers with coelestial
heat;"
>>> re.split("\W+",metamorphoses)
['OF', 'bodies', 'chang', 'd', 'to', 'various', 'forms', 'I', 'sing', 'Ye',
'Gods', 'from', 'whom', 'these', 'miracles', 'did', 'spring', 'Inspire',
'my', 'numbers', 'with', 'coelestial', 'heat', '']

Example
>>> import re
>>> lines = ["surname: Obama, prename: Barack, profession: president",
"surname: Merkel, prename: Angela, profession: chancellor"]
>>> for line in lines:
... re.split(",* *\w*: ", line)
...
['', 'Obama', 'Barack', 'president']
['', 'Merkel', 'Angela', 'chancellor']
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 123


First element မာ empty string မ ပ င္အရင္ slice operator သံိုးပနိုင္ ပတမ္္။
>>> import re
>>> lines = ["surname: Obama, prename: Barack, profession: president",
"surname: Merkel, prename: Angela, profession: chancellor"]
>>> for line in lines:
... re.split(",* *\w*: ", line)[1:]
...
['Obama', 'Barack', 'president']
['Merkel', 'Angela', 'chancellor']
>>>

Search and Replace with sub


re.sub(regex, replacement, subject)
ဒပဆိုအရင္ regular expression ပနဲန္႔တိုက္တာေတြကို အစား ိုးေ း ပလမာ့္မမ္္။
Example:
>>> import re
>>> str = "yes I said yes I will Yes."
>>> res = re.sub("[yY]es","no", str)
>>> print res
no I said no I will no.

Python2(ဘာသာျ ပန္) Han Phyo Oo 124


Chapter 30
Lambda, filter, reduce and map

Lambda Operator

Lambada operator or lambda function ဆိုတာကေတာာ့ anonymous functions ေလးေတြ


လို ္တာျ စ္ ပတမ္္။ ပနာမည္မအရတဲန္႔ function ေ ပာ့္။ သံိုးမမ္ေပနအရာ မာ တစ္ ပ ည္း ပန္းတါးတာ ာ့ျ
ာ့ျ စ္တာ့အ
ဲ တြက္ throw-away function လိုန္႔လည္းေ ခ ပတမ္္။ lambda function ေတြကို filter(),
map(), reduce() ေတြပနဲန္႔တသ
ြဲ ံိုးေလန္႔အရ ပတမ္္။ lisp programmer ေတြေတာင္းဆိုတာ ေႀကာင္ာ့
lambda feature ကို ည္ာ့ေ း ဲာ့တာျ စ္ ပတမ္္။

Lambda function ေအရးတဲာ့ ံိုစံကေတာာ့အရိုးအရင္း ပတမ္္။


lambda argument_list: expression

arugment list မ
ဲ ာ comma ျ ား ားတဲာ့ list of argument ေတြ ပ ပတမ္္။ expression
ကေတာာ့ ၎ argument ေတြကိုသံိုးမမ္ာ့ arithematic expression ျ စ္ ပတမ္္။ function
ကိုပနာမည္ေ း င္အရင္လည္း variable တစ္ ို ဲကို assign လို ္ပနင္ ပတမ္္။

ေအာက္ ပ စ မာ မာ argument ႏွာစ္ ိုေ ပင္းအရလဒ္ကို ိုတ္ေ း ပတမ္္။


>>> f = lambda x, y : x + y
>>> f(1,1)
2

The map() Function

Lambda operator အရဲာ့အသံိုး၀င္မိုကို map() function ပနဲန္႔တသ


ြဲ ံိုးတဲန္႔အ ပျမင္ပနိုင္ ပတမ္္။

Map() ဆိုတာကေတာာ့ argument ႏွာစ္ ို ပတဲာ့ function ျ စ္ ပတမ္္။


r = map(func, seq)
func ဆိုတဲာ့ မ argument ကေတာာ့ function name တစ္ ို ို ျ စ္ျ ါးေတာာ့ ဒိုတမ argument
ကေတာာ့ sequence တစ္ (ို eg.list)ျ စ္ ပတမ္္။ map() က sequence seq ဲက element
ေတြအားလံိုးသံိုးျ ါးေတာာ့ fynction func အတိုင္းတြက္ က္ေ းတာျ စ္ ပတမ္္။ အရလဒ္အေပန ပနဲာ့
list အသစ္တစ္ ို ိုတ္ေ း ပတမ္္။
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)

F = map(fahrenheit, temp)
C = map(celsius, F)

Python2(ဘာသာျ ပန္) Han Phyo Oo 125


အ က္ေ ာ္ျ ပ စ မာမာ lambda မသံိုး ား ပဘး္။ lambda သံိုးအရင္ fahrenheit() celsius()
စတဲာ့ function ေတြကို သတ္မတ္ ပနာမည္ေ းစအရာမလို ပဘး္။

ေအာ ္ ပ interactive session မာေတြန္႔ျမင္ပနိုင္ ပတမ္္။


>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>> C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit)
>>> print C
[39.200000000000003, 36.5, 37.300000000000004, 37.799999999999997]
>>>
Map() က List တစ္ ို က္လည္း ိုအလို ္လို ္ပနိုင္ ပတ္္။ list ေတြအရဲာ့ length ေတာာ့ တအရ ပမမ္္။
map() က မ list အရဲာ့ 0th element ၊ ဒိုတမ list အရဲာ့ 0th element စတဲန္႔ ံိုစံပနဲာ့ အရတဲာ့ length
အတိုင္း အလို ္လို ္ေ း ပမမ္္။
>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> map(lambda x,y:x+y, a,b)
[18, 14, 14, 14]
>>> map(lambda x,y,z:x+y+z, a,b,c)
[17, 10, 19, 23]
>>> map(lambda x,y,z:x+y-z, a,b,c)
[19, 18, 9, 5]
အ က္ေ ာ္ျ ပ စ မာမာ parameter x က သန္႔အတြက္ တပန္ ိုးေတြကို list a ကေပနအရအရ ပတမ္္။
y ကေတာာ့ list b ကေပနျ စ္ျ ါး ၊ z ကေတာာ့ lit c ကေပနျ စ္ ပတမ္္။

Filtering

Filter(function,list) function ႕ေတာာ့ list ဲက element ေတြ filter(စစ္ ိုတ္)လို ္အရာမာ


သံိုး ပတမ္္။ first argument ကေတာာ့ function တစ္ လ
ို ို ပတမ္.၎ function က Boolean
value ိုတ္ေ းအရမာျ စ္ ပတမ္္။ ၎ function ကို list မ
ဲ ာ အရတဲာ့ element တိုင္းအတြက္
တြက္ က္ေ းမျ စ္ျ ါးေတာာ့ true ျ စ္တာ့ဲ element ေတြကို List အေပနပနဲန္႔ ိုတ္ေ း ပတမ္္။
>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]
>>>

Reducing a List

Python2(ဘာသာျ ပန္) Han Phyo Oo 126


Reduce(func,seq) ကေတာာ့ seq ဲက element ေတြကိုေတာက္ေလ ာက္ တြက္ က္ေ းျ ါး
value တစ္ ို ဲ ိုတ္ေ း ပတမ္္။ စ မာ list ဲက element ေတြအားလံိုးေ ပင္းလဒ္လိုမ ဳေး

Seq=[s1,s2,s3,s4,s5,…..,sn] ကိုသံိုးျ ါး reduce(func,seq)ကိုေ ခမမ္ဆိုအရင္

 မဆံိုး element ႏွာစ္ က


ို ိုအအရင္တက
ြ ္မမ္ func(s1,s2)
 ေပနာက္တစ္ဆင္ာ့မာ ိုပနအရလာတဲာ့ result ပနဲန္႔ တတမ element ပနဲန္႔ ္ျ ါးတြက္မမ္
func(func(s1,s2),s3) ဒါလို ံိုစံျ စ္သာြ း ပတမ္္။
 ေပနာက္ဆံိုးအကိုပန္ကိုပန္သာြ းတဲာ့အ လို ္ျ ါး value တစ္ ိုျ ပန္ ိုတ္ေ း ပတမ္္။

Example
>>> reduce(lambda x,y: x+y, [47,11,42,13])
113

Examples of reduce()

Determining the maximum of a list of numerical values by using reduce:


>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>
Calculating the sum of the numbers from 1 to 100:
>>> reduce(lambda x, y: x+y, range(1,101))
5050

Python2(ဘာသာျ ပန္) Han Phyo Oo 127


Chapter 31
List Comprehension

Introduction

List compression ဆိုတာကေတာာ့ python မာ List ေတြ ပန္တါး ိုန္႔အတြက္ သ ္အရ ္လ တဲန္႔
ပနည္းလမ္းတစ္ ိုျ စ္ ပတမ္္။

List compression ဟာ map() filter() redue() ေတြအစားသံိုးပနိုင္ ပတမ္္။

Examples

Lambda အ ပန္းမာ Celsius <=>fahrenheit ေလးေအရး ဲာ့တမ္္။ list compression ပနဲာ့ဆိုအရင္


ေအာက္ ပ ံိုစံအတိုင္းအရမမ္္။
>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
>>> print Fahrenheit
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999]
>>>

Pythagorean triples အတြက္ဆိုအရင္


>>> [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30)
if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15),
(10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]
>>>

Cross product of two sets:


>>> colours = [ "red", "green", "yellow", "blue" ]
>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'),
('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow',
'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue',
'tree')]
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 128


Generator Comprehension

Python2.6 မာ generator compression စတင္ ပ၀င္လာတမ္္။ သကေတာာ့ () ပနဲန္႔သံိုးတဲာ့


generator expression ျ စ္ ပတမ္.္။ သအရဲာ့အလို ္လို ္ ံိုက list compression ပနဲာ့တတမ္
ဒပေ မမ္ာ့ သက list အစာ းgenerator ကို ိုတ္ေ းတမ္္။

>>> x = (x **2 for x in range(20))


>>> print(x)
at 0xb7307aa4>
>>> x = list(x)
>>> print(x)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256,
289, 324, 361]

A more Demanding Example

sieve of Eratosthenes ကိုသံိုးျ ါး 1 ပနဲန္႔ 100 ႀကား prime number ေတြအရာမမ္္။


>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>> primes = [x for x in range(2, 100) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97]
>>>
ဒပကိုမ ိုျ ါး general က မမ္ာ့ ံိုစံေျ ာင္းမမ္္။ n ေလာက္အရတဲန္႔ prime number ေတြအရာမမ္ေ ပာ့္။
>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = [j for i in range(2,sqrt_n) for j in range(i*2, n, i)]

no_primes ကိုႀကည္ာ့အရင္ ျ ပနာတစ္ ိုအရတာေတြန္႔ ပမမ္္။ list မ


ဲ ာ ႏွာစ္ ို ္ေပနတာေတြေတြန္႔
ပလမာ့္မမ္္။
>>> no_primes
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78,
80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 6, 9, 12, 15, 18, 21, 24, 27, 30,
33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87,
90, 93, 96, 99, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64,
68, 72, 76, 80, 84, 88, 92, 96, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60,
65, 70, 75, 80, 85, 90, 95, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78,
84, 90, 96, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 16, 24, 32,
40, 48, 56, 64, 72, 80, 88, 96, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99]
>>>
ဒပကိုေျ အရင္း န္႔အ
ို တြက္ ေပနာက္အ ပန္းမာ ပမမ္ာ့ set compression ပနားလည္အရ ပမမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 129


Set Comprehension

Set comprehension က list comprehension ပနဲန္႔တ ပတမ္္။ သကေတာာ့ set တစ္ ို return
ျ ပန္ေ း ပတမ္္။ set လို ္ ိုန္႔ {} ေတြသံိုး ပတမ္္။ ိုပန ျ ပနာကို ္တာေတြမ ပ င္အရင္ set
comprehension သံိုးအရ ပမမ္္။
>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}
>>> no_primes
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30,
32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55,
56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80,
81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99}
>>> primes = {i for i in range(n) if i not in no_primes}
>>> print(primes)
{0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97}
>>>

Recursive Function to Calculate the Primes

ေအာက္ ပ python scriptကေတာာ့ prime numbers ေတြကို recursive function


သံိုးျ ါးတြက္ ေ းတာျ စ္ ပတမ္္။
from math import sqrt
def primes(n):
if n == 0:
return []
elif n == 1:
return []
else:
p = primes(int(sqrt(n)))
no_p = {j for i in p for j in xrange(i*2, n+1, i)}
p = {x for x in xrange(2, n + 1) if x not in no_p}
return p

for i in range(1,50):
print i, primes(i)

Python2(ဘာသာျ ပန္) Han Phyo Oo 130


Chapter 32
Generators

Introduction

Generator ေတြဆိုအရာကေတာာ့ iterator ေတြကို ိုတ္ေ းတဲန္႔အလြမ္ကဆံိုး


ပနည္းလမ္းေတြျ စ္ ပတမ္္။ function ေတြပနဲန္႔ ံိုစံတေ မဲာ့ syntactic အေပနပနဲန္႔ေအရာ semantic
အေပနပနဲာ့ေအရာ ကြဲျ ား ပတမ္္။ generator ေတြမာ return အစား yield ဆိုတာေတြအရ ပလမ္ာ့မမ္္။
ေပနာက္အေအရးႀကါးတာတစ္ ိုကေတာာ့ local variable ေတြ execution ေတြကို call ေတြႀကားမာ
အလိုအေလ ာက္လို ္ ေဆာင္ေ း ပတမ္္။ ဒါလိုလို ္အရတဲာ့အေႀကာင္းကေတာာ့ ံိုမပန္ function call
ေတြလို generator function ေတြက function အစမာ execution မလို ္လိုန္႔ျ စ္ ပတမ္္။
အဲံလိုန္႔အစကေပန execute လို ္မမ္ာ့အစား generator မာ ေပနာက္ဆံိုး call က ြက္သာြ းတဲန္႔ yield
statement မာဆက္လို ္ ပတမ္္။ ေပနာက္တစ္ပနည္းေျ ာအရအရင္ python interpreter က yield
statement တစ္ ိုကို generator ကေပန ိုတ္ေ းတဲiန္႔ terator တစ္ ို ဲမာေတြအရင္ ၎ ေပနအရာပနဲန္႔
local variable ေတြကိုမတ္ျ ါးေတာာ့ iteratorကေပန return (ျ ပန္ က
ြ ္) ပတမ္္။ ေပနာက္တစ္ႀကမ္
iterator ကိုေ ခတဲာ့အ ပမာ ိုပနမတ္ ားတဲာ့ yield statement ကေပနျ ပန္စ ပတမ္္။ generator

ဲ ာ yield statement ေတြတစ္ ို က္ ိုပနိုင္သလို loop မ
ဲ ာလည္း အရေပနပနိုင္ ပတမ္္။
generator မာ return statement ပအရင္ python interpreter က၎ codeကို execute
လို ္တဲန္႔အ ပ မာ StopIteration exception error ျ ျ ါး အရ ္သာြ း ပလ္မာ့္မမ္္။
ိုေျ ာသမ ေတြကို class based iterator ပနဲန္႔လည္းအသံိုးျ ဳေပနိုင္ ပတမ္္။ ဒပေ မမ္ာ့ generator
အရဲာ့အဓက အားသာ က္က __iter__() ပနဲန္႔ next() method ေတကို
အလိုအေလ ာက္ျ ဳေလို ္ေ းျ င္း ေတြ ပ ပတမ္္။ အအရမ္းႀကါးတဲန္႔အဆံိုးသတ္မအရတဲာ့
dataေတြ ိုတ္ေ း ိုန္႔အရာ ေကာင္းမြပန္တဲန္႔ ပနည္းလမ္း ေတြ generator
မာ ပ ပတမ္္။ျမဳေန္႔ပနာမည္ေလး ို ိုတ္ေ းတဲာ့ generator တစ္ ို example ျ ား ပတမ္္။
def city_generator():
yield("Konstanz")
yield("Zurich")
yield("Schaffhausen")
yield("Stuttgart")
၎generator ကိုသံိုးျ ါး iterator လို ္ပနိုင္ ပတမ္္။
>>> from city_generator import city_generator
>>> x = city_generator()
>>> print x.next()
Konstanz
>>> print x.next()
Zurich
>>> print x.next()
Schaffhausen
>>> print x.next()
Stuttgart
>>> print x.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>

Python2(ဘာသာျ ပန္) Han Phyo Oo 131


StopIteration
>>>

အ က္မျ ာသလို ဲ iterator x ကို interactive shell မာလို ္ ဲာ့တမ္္။ next()


ကိုေ ခတိုင္း ေပနာက္ျမန္႔တစ္ ို ိုတ္ေ းတမ္္။ေပနာက္ဆံိုးျမဳေန္႔ကို ေ းျ ါး x.next() ကိုေ ခအရင္
"StopIteration". error ျ မမ္္။

အစကေပနျ ပန္စေအာင္္လိုန္႔ reset လည္းလို ္လိုန္႔မအရ ပဘး္။ ဒပေ မမ္ာ့ generator


ေပနာက္တစ္ ို ပန္တါး ပနိုင္ ပတမ္္။ x=city_generator() ကို ္လို ္တာျ စ္ ပတမ္္။ yield က
return ပနဲန္႔တတမ္ င္အရေ မဲာ့ ဒါ စ မာ ပနဲာ့ဆိုအရင္ မတတာေတြန္႔ ပလမ္ာ့မမ္္။ yield အစား return
ကို ည္ာ့မမ္ဆိုအရင္ function ဲျ စ္ ပလမ္ာ့မမ္.္။ ဒပေ မမ္ာ့ function ဆိုအရင္ အျမဲတမ္း
“Konstanz” ဲ return ျ ပန္ေ း ေပန ပလမ္ာ့မမ္္။

Method of Operation

Generator ေတြက interator ေတြ ိုတ္ေ းတဲန္႔(generate) အတြက္ေႀကာင္ာ့ generator


လိုန္႔ ခတာျ စ္ ပတမ္္။

အလို ္လို ္ ံိုကေတာာ့

 Generator ကို function ေတြလို ဲ call လို ္ ပတမ္္။ သက return ျ ပန္ေ းတာကေတာာ့
iterator object ျ စ္ ပတမ္္။ ဒါအ ေတာာ့ generator code ေတြအလို ္မလို ္ေသး ပ
 Iterator ေတြကိုေတာာ့ next method ပနဲာ့ေ ခ ပတမ္္။ မဆံိုး မာေတာာ့ function
လိုအလို ္လို ္ ပတမ္္။yield statement ကိုမေတြန္႔မ င္းျ စ္ ပတမ္္။
 Yield ကေတာာ့ expression တစ္ ိုအရဲာ့ value ကို keyword yield ပနဲrန္႔ eturn
ျ ပန္ေ း ပတမ္္။ ဒပကေတာာ့ function ပနဲာ့တ ပတမ္.ဒပေ မမ္ာ့ pythonက yield အရဲာ့ position
ေတြ local variable ေတြကို next call အတြက္ မတ္ ားေ း ပတမ္္။ ေပနာက္တစ္ ပ call
လို ္တဲာ့ အ ပ yield statement ေပနာက္ကေပနျ ါးဆက္ျ ါး execution ဆက္လို ္ ပတမ္္။
 ေပနာက္ဆံိုး အကိုပန္ျ ါးသြားတမ္ သိုန္႔ value မ ပတဲန္႔ return တစ္ ိုေတြန္႔အရင္ iterator
ျ ါးဆံိုး ျ ါျ စ္ ပတမ္္။

Fibonacci ိုတ္ေ းတဲာ့ example ေလးႀကည္ာ့အရေအာင္္။

Example seauence 0,1,1,2,3,5,8,13

Mathematical term ပနဲာ့ဆိုအရင္


Fn = Fn - 1 + Fn - 2
F0 = 0 and F1 = 1

Python implementation

Python2(ဘာသာျ ပန္) Han Phyo Oo 132


def fibonacci(n):
"""Fibonacci numbers generator, first n"""
a, b, counter = 0, 1, 0
while True:
if (counter > n): return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5)
for x in f:
print x,
print

အ က္ေ ာ္ျ ပ generator ကို Fibonacci အတြက္သံိုးပနိုင္ ပတမ္္။


Endless iterator example တစ္ ို ္ေျ ာ ပမမ္္။
def fibonacci():
"""Fibonacci numbers generator"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b

f = fibonacci()

counter = 0
for x in f:
print x,
counter += 1
if (counter > 10): break
print

Recursive Generators

Function ေတြလို ဲ generator ေတြကို recusice ေအရးပနိုင္ ပတမ္္။ေအာက္မာ list ေတြကို


permutation လို ္ ား ပတမ္္။

Permutation ဆိုတာကေတာာ့ ေ း ားတဲာ့ အစါအစစ္ အမ ဳေးမ ိုဳေးစစ္တာျ စ္ ပတမ္္။

a,b,c ကို permutation လို ္ႀကည္ာ့ ပမမ္္။

abc
acb
bac
bca
cab
cba

n elemetnt အတြက္ number of permutation ကေတာာ့ n


ာ့ ! ျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 133


n! = n*(n-1)*(n-2) ... 2 * 1

def permutations(items):
n = len(items)
if n==0: yield []
else:
for i in range(len(items)):
for cc in permutations(items[:i]+items[i+1:]):
yield [items[i]]+cc

for p in permutations(['r','e','d']): print ''.join(p)


for p in permutations(list("game")): print ''.join(p)

A Generator of Generators

Fibonacci sequence exampleအရဲာ့ ဒိုတမgenerator မာ iterator တစ္ ို ိုတ္ေ း ပတမ္္။


theory အအရဆိုအရင္ေတာာ့ ဒပကိုသံိုးျ း finbonacci number အားလံိုးကို ိုတ္ေ းပနိုင္ ပတမ္္။
list(fibonacci())
ဒပဆိုအရင္ ကိုမ္ာ့ computer ျမပန္သေလာက္အရတဲာ့ sequence ေတြျ ပလမ္ာ့မမ္္။

လက္ေတြန္႔မာ ေတာာ့ အဆံိုမအရတဲာ့ iterator က


ဲ မ n element ဲလို ပတမ္္။ ဒပဆိုအရင္ ေပနာက္
generator တစ္မ ဳေးသံိုပနို္င္ ပတမ္္။ generator g အတြက္ n element ေတြဆိုအရင္
def firstn(g, n):
for i in range(n):
yield g.next()
ေအာ ္ ပ script ကေပန Fibonacci sequence အရဲန္႔ မ 10 လံိုး ိုတ္ေ း ပတမ္္။
#!/usr/bin/env python
def fibonacci():
"""Ein Fibonacci-Zahlen-Generator"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b

def firstn(g, n):


for i in range(n):
yield g.next()

print list(firstn(fibonacci(), 10))

Python2(ဘာသာျ ပန္) Han Phyo Oo 134


Chapter 33
Exception Handling

Exeception ဆိုတာကေတာာ့ program တစ္ ိုကို execute လို ္တဲာ့အ ပမာ ျ စ္ေ ခလာတဲာ့ error
ေတြျ စ္ ပတမ္္။ exeception handling ဆိုတာကေတာာ့ error ေတြျ စ္ေ ခလာလ င္
အလိုအေလ ာက္ ကိုင္တြမ္ေျ အရင္းတာကိုဆိုလို ပတမ္္။

Error handling ကို error ျ စ္ေ ခတဲာ့အ ပမာအရတန္႔ဲ execution state ေတြကို မတ္သားျ ါးေတာာ့
သန္႔အတြက္ ေအရးသား ားတဲာ့ code ေတြ(exeception handler) ပနဲန္႔ေျ အရင္း ပတမ္္။ ျ စ္ေ ခလာ တဲာ့
error ေ ခမတည္ျ ါးေတာာ့ error handler ကျ င္ဆင္ေ းပနိုင္သလို သမ္း ားတဲာ့ data ေတြပနဲန္႔
ဆက္လက္လို ္ေဆာင္ပနိုင္ ပတမ္္။

Exception Handling in Python

Execption handling မာ python က java ပနဲန္႔တ ပတမ္္။ execption ျ စ္ပနိုင္တာ့ဲ code ကို try
block မ
ဲ ာ ား ပတမ္္။ java မာေတာာ့ exeception ေတြကို catch ပနဲာ့သံိုးေ မမ္ာ့ python
မာေတာာ့ except ပနဲန္႔သံိုး ပတမ္္။raise statement ပနဲန္႔လည္း ကိုမ္ ိုင္ execption
ေတြလို ္ပနိုင္ ပေသးတမ္္။

Example- user ကို integer number ည္ာ့ ိုင္းမမ္္။ raw_input() ကိုသံိုးအရင္input က string
ျ စ္မမ္ ဒပေႀကာင္း Integer ျ စ္ေအာင္ cast လို ္ေ းအရမမ္္။ input က integer မဟိုတ္အရင္
ValueError တက္မမ္.္။
>>> n = int(raw_input("Please enter a number: "))
Please enter a number: 23.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.5'
ဒပကို execption handling ည္ာ့ေအရးရင္
while True:
try:
n = raw_input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print "Great, you successfully entered an integer!"
ဒပဆိုအရင္ integer ေ းမ ဲ loop ကို break လို ္မမ္္။

Sample output
$ python integer_read.py
Please enter an integer: abc
No valid integer! Please try again ...
Please enter an integer: 42.0

Python2(ဘာသာျ ပန္) Han Phyo Oo 135


No valid integer! Please try again ...
Please enter an integer: 42
Great, you successfully entered an integer!
$
Multiple Except Clauses

အမ ဳေးအမ ဳေးေသာ execption ေတြအတြ႕္ try statement မာ except clause


တစ္ ို က္ ိုပနိုင္ ပတမ္္။ အမ ားဆံိုးေတာာ့ တစ္ ို ဲ execution ျ စ္ပနိုင္ ပတမ္္။

ေပနာက္ စ မာတစ္ ိုအေပနပနဲာ့ file read လို ္ ိုန္႔ open မမ္္။file ဲက Line တစ္ေႀကာင္း read
ျ ါးေတာာ့ အဲန္႔ဒါ line ကို Integer ေျ ာင္းမမ္္။အပနည္းဆံိုး execption ႏွာစ္ ိုျ စ္ပနိုင္တမ္္။

 an IOError
 ValueError

တစ္ျ ား မသတ္မတ္ပနိုင္တာ့ဲ execption ေတြလည္းအရမမ္္။


import sys

try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "No valid integer in line."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
IOError ကို handling လို ္တာႀကည္ာ့အရမာျ စ္ ပတမ္္။ IOError က tuple အေပနပနဲန္႔ error
number ေတြ error message string ေတြကို ိုတ္ေ း ပတမ္္။ ဒပေတြကို variable errno ပနဲာ့
strerror မ
ဲ ာ "except IOError as (errno, strerror)" လိုန္႔ assign လို ္ ာ့ဲ ပတမ္္။ မအရတဲာ့ file
တစ္ ိုကို အ က္ ပ script သံိုးျ ါး ြင္ာ့ ိုန္႔ႀကဳေးစားအရင္ ေအာက္ ပ message အရ ပမမ္္။
I/O error(2): No such file or directory
Integers.txt က readable မျ စ္အရင္ read လို ္ ိုန္႔ permission မအရအရင္ေတာာ့
I/O error(13): Permission denied
Except clause တစ္ို ကို execption တစ္ ို က္ ိုျ ါးေ း င္အရင္ tuple ေတြပနဲာ့
ပနာမည္ေ းပနိုင္ ပတမ္္။
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except (IOError, ValueError):
print "An I/O error or a ValueError occurred"
except:
print "An unexpected error occurred"
raise

Python2(ဘာသာျ ပန္) Han Phyo Oo 136


Clean-up Actions (try ... finally)

Try ပနဲန္႔ except ကို အတြဲလိုက္ ေ


ဲ တြ ဲန္႔မာျ စ္ ပတမ္္။ေပနာက္တစ္မ ဳေးသံိုးပနိုင္ ပေသးတမ္္။ try
ေပနာက္မာ finally clause ပပနိုင္ ပတမ္္။ clean-up or termination clauses လိုန္႔လည္း ေ
ေ ခ ပတမ္္။ ဘမ္အေျ အေပနမာ ဲျ စ္ျ စ္ execution လို ္တာေႀကာင္ာ့ျ စ္ ပတမ္္။ example
try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
finally:
print("There may or may not have been an exception.")
print "The inverse: ", inverse
sample output
bernd@venus:~/tmp$ python finally.py
Your number: 34
There may or may not have been an exception.
The inverse: 0.0294117647059
bernd@venus:~/tmp$ python finally.py
Your number: Python
There may or may not have been an exception.
Traceback (most recent call last):
File "finally.py", line 3, in <module>
x = float(raw_input("Your number: "))
ValueError: invalid literal for float(): Python
bernd@venus:~/tmp$
Combining try, except and finally

“finally” ပနဲန္႔ “except”ကို အတသံိုးပနိုင္ ပတမ္္။


try:
x = float(raw_input("Your number: "))
inverse = 1.0 / x
except ValueError:
print "You should have given either an int or a float"
except ZeroDivisionError:
print "Infinity"
finally:
print("There may or may not have been an exception.")

sample output
bernd@venus:~/tmp$ python finally2.py
Your number: 37
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: seven
You should have given either an int or a float
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: 0
Infinity
There may or may not have been an exception.
bernd@venus:~/tmp$

Python2(ဘာသာျ ပန္) Han Phyo Oo 137


else Clause

tr…except clause မာ else clause လည္း ပပနင္ ပတမ္္။ else ကို except ေတြအားလံိုးေပနာက္မာ
ားအရ ပမမ္္။ try မာ error မတက္အရင္ else အလို ္လို ္ေ း ပမမ္္။

example
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
text = fh.readlines()
fh.close()
except IOError:
print 'cannot open', file_name

if text:
print text[100]
ဒါစ မာ မာ commamd line argument ကေပန file name ကိုလက္ ံေ း ပတမ္္။
“exception_test.py” လိုန္႔သမ္း ားတမ္ဆို ပဆိုန္႔.္။ဒပဆိုအရင္
python exception_test.py integers.txt
ဒါလိုမလို ္ င္အရင္ "file_name = sys.argv[1]" to "file_name = 'integers.txt'"
လိုန္႔ေျ ာင္းလိုက္ ပ္။
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
except IOError:
print 'cannot open', file_name
else:
text = fh.readlines()
fh.close()

if text:
print text[100]
မတတာကေတာာ့ first case မာျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 138


The assert Statement

Assert Statement ကေတာာ့ debugging statement ေတြအတြက္ျ စ္ ပတမ္္။


သတ္မတ္ ားတဲာ့ အေျ အေပနတစ္ ိုမမပန္မသာလ င္ assert အတြက္ exception ျ စ္ ပတမ္္။

Assert statement မသံိုး ဲ python မာေအာက္ ပအတိုင္းအသံိုးျ ဳေပနိုင္ ပတမ္္။


if not <some_test>:
raise AssertionError(<message>)
ေအာက္မာေတာာ့ assert statement ကိုသိုးံ ား ပတမ္္။
assert <some_test>, <message>
အ က္ေ ာ္ျ ပစာေႀကာင္းကို <some_test> တြက္ က္တာေတြ မားမမ္ဆိုအရင္ exeception
ျ စ္ျ ါးေတာာ့ <message>ကို output ိုတ္ေ း ပမမ္္။

Example:
>>> x = 5
>>> y = 3
>>> assert x < y, "x has to be smaller than y"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: x has to be smaller than y
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 139


Chapter 34
Classes

Object Oriented Programming

ေအရန္႔အ ိုင္းေတြမာ Object oriented programming(OOP) အႀကာင္းေတြကိုတမင္ ပန္လ ္ ား


ဲာ့ ပတမ္္။ OOP အေႀကာင္းမေျ ာ ဲာ့တာ ိုလမ
ြ ္မာျ စ္ ပတမ္္။ ဒပေ မမာ့္ classes ေတြအရန္႔ဲ object
ေတြ method ေတြကိုသံိုး ဲာ့ႀက ပတမ္္။

တစ္ ိုန္႔က oop ကို modern programming paradigm တစ္ ိုလိုန္႔ င္ေ မဲာ့ ၁၉၆၀
ေလာက္ကစတမ္ ေျ ာအရ ပမမ္္။ မဆံိုး object သံိုးတဲာ့ language ကေတာာ့ simula 67 ပ္။
OOP ကိုေကာင္းတမ္ေျ ာတဲာ့သအရ ာ့ဲ သလို မေကာင္းဘးေျ ာတဲာ့သမ ားလည္း အရ ဲာ့ ပတမ္္။ OOP
C++ အရဲာ့ designer/implementer ျ စ္တာ့ဲ Alexander StepanovကOOP provides a
mathematically-limited viewpoint and called it "almost as much of a hoax as Artificial
Intelligence".လိုန္႔ေျ ာ ဲာ့ ပတမ္္။

Edsger W. Dijkstra, one of the most renown professors of Computer Science, wrote:
"... what society overwhelmingly asks for is snake oil. Of course, the snake oil has
the most impressive names - otherwise you would be selling nothing - like
"Structured Analysis and Design", "Software Engineering", "Maturity Models",
"Management Information Systems", "Integrated Project Support Environments"
"Object Orientation" and "Business Process Re-engineering" (the latter three being
known as IPSE, OO and BPR, respectively).

Object Oritented Projection အရဲာ့ အဓက principle 4 ို

 Encapsulation
 Data Abstraction
 Polymorphism
 Inheritance

Object oritented program တစ္ ိုကို class ေတြေ ခမာအေျ ံ ားျ ါးေတာာ့ သပနဲန္႔တဲဆ
ြ က္
အလို ္လို ္ေပနတဲာ့ object မ ား ပအရ ပတမ္္။ ံိုမပန္ program ေတြမာေတာာ့ function ေတြ routine
ေတြပနဲန္႔ အ
ဲ လို ္လို ္ ပတမ္္။ OOP မာ object ေတြဟာ တစ္ ိုပနဲန္႔တစ္ ို message မ ားလက္ ံျ င္း္။
data မ ားတြက္ က္ေ းျ ငး္္။ တစ္ျ ား object မ ားဆါသိုန္႔ message ေ း ိုန္႔ျ င္းမ ားလို ္ေဆာင္ေ း
ႀက ပတမ္္။

Analogy: The Cake Class

Class ကိုေျ ာအရအရင္ cake တစ္ ိုလို ္ ိုန္႔လိုအ ္တာ့ဲ receipe ပနဲန္႔မစ္ႀကည္ာ့ပနင္ ပတမ္္။ cake တစ္ ို
ိုတ္ ိုန္႔အတြက္ receipe လို ပတမ္္။ receipe(class) ပနဲန္႔ cake(an instance or an object of this

Python2(ဘာသာျ ပန္) Han Phyo Oo 140


class) ႀကားျ ားပနား က္ကေတာာ့ င္အရား ပတမ္္။ cake ကိုလို ္ျ ါးအရင္စားပနိုင္ေ မမ္ာ့ receipe
ကိုေတာာ့ စားလိုန္႔မအရ ပဘး္။cake မိုပန္ာ့ ိုတ္သလို ပ ဲ oop program တစ္ ိုဟာ object ေတြကို class
definition မာ သတ္မတ္ ာတဲာ့အတိုင္းတည္ေဆာက္ေ း ပတမ္္။ class ဲမာ variable ေတြ
method ေတြ ပ၀င္ ပတမ္္။ cake မိုပန္ာ့ တ
ို ္မမ္ဆိုအရင္ ပ၀င္ စၥည္း(ingredient) ပနဲန္႔
လို ္ငပန္းစစ္(instruction) ေတြလို ပမမ္္။ အဲာ့ဒါလို ဲ class မာလည္း variable ေတြ method
ေတြလို ပတမ္္။ ၎ တို႕ကို class variable လိုန္႔ေ ချ ါးေတာာ့ method ေတြအားလံိုးအတြက္
တညါတဲန္႔တပန္ ိုးေတြအရ ပတမ္.္။instance variable ကေတာာ့သါျ ား object တစ္ ို င္းစါအတြက္
မတညါတာ့တ
ဲ ပန္ ိုးေတြအရ ပတမ္္။ data ေတြသံိုးစြဲပနိုင္ေအာင္လည္း class မ
ဲ ာ လိုအ ္တဲာ့ method
ေတြသတ္မတ္ ိုန္႔လည္းလို ပတမ္္။

Classes, Objects, Instances

Class က data type တစ္ ိုကိုသတ္မတ္ေ းျ ါးေတာာ့ ၎ မ


ဲ ာ variable ,properties,methods
ေတြ ပ၀င္ ပတမ္္။

Class ေတြအရဲာ့ instance ေတြ Object ေတြအရပနိုင္ ပတမ္္။ instance ဆိုတာကေတာာ့ run-time မာ
ပန္တါးလို္က္တဲာ့ class အရဲာ့ object ျ စ္ ပတမ္္။ object ေတြအရဲာ့ attribute value ေတြကိုေတာာ့ state
လိုန္႔ေ ခ ပတမ္္။ object မာ class မ
ဲ ာသတ္မတ္ ားတဲာ့ state ပနဲန္႔ behavior ပ၀င္ ပတမ္္။

အ က္မာေျ ာ ဲာ့သလို ဲ class ေတြမာလည္း attribute ေတြ properties ေတြ ပနဲန္႔ instance
ေတြအတြက္ method ေတြ ပ၀င္ ပတမ္္။ method ဆိုတာကေတာာ့ function ပ ဲ ဒပေ မမ္ာ့သက
class က ိုင္တာျ စ္ ပတမ္္။ class မ
ဲ ာသတ္မတ္ ားတာျ စ္ျ ါး instance ေတြ ပနဲာ့ class data
ေတြအတြက္အလို ္လို ္ ပတမ္္။ method ေတြကို class အရဲာ့ instance ေတြ subclass ေတြကသာ
အသံိုးျ ဳေပနိုင္ ပတမ္္။

“Account” ပနဲန္႔ “Account Holder”ဆိုျ ါး class ႏွာစ္ ိုအရမမ္္။ “Account Holder” အရဲန္႔ data မာ
Holder Surname and Prename, Adress, Profession, and Birthday စတာေတြ ပ ပမမ္္။
method ေတြကေတာာ့ "Change of Residence" and "Change of Profession"
ေတြျ စ္ ပတမ္္။ ျ ါးျ ည္ာ့စံို တဲာ့ model ေတာာ့မဟိုတ္ ပဘး္။ data ေတြ method
ေတြအမ ားႀကါးလို ပစါးမမ္္။

Encapsulation of Data

OOP အရဲာ့ ေကာင္းမြပန္တဲာ့တစ္ က္က data encapsulation ျ စ္ ပတမ္္။


encapsulation/abstractopm/ data hiding အတတ ဲျ စ္ ပတမ္္။ encapsulation
အရဲာ့သေဘာကေတာာ့ object component ေတြကို အရမအသံိုးျ ဳေျ င္းကို
ကပန္ာ့သတ္ေ းတာ ဲျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ object definition အရဲာ့အျ င္ကေပနႀကည္ာ့အရင္ object
ကိုဘမ္လိုလို ္ ားတမ္ဆိုတာမသပနိုင္ ပဘး္။ ဒပေတြကို access အရ င္အရင္ေတာာ့ special

Python2(ဘာသာျ ပန္) Han Phyo Oo 141


method ေတြျ စ္တာ့ဲ getter/setter ေတြသံိုးအရ ပမမ္္။ get() set() method ေတြသံိုးျ ါး တာာ့
internal data ေတြကို မေတာ္တဆေျ ာင္းလဲမတာေတြကို ေအရာင္အရားပနိုင္ ပတမ္္။

ဒါလိုကာကြမ္ ားတာေတြကို ေအရာင္အရား ိုန္႔လည္းျ စ္ပနိုင္ ပတမ္္။ c++ မာ “friends” , java ပနဲာ့
ruby မာ reflection api ,python မာ ေတာာ့ mangling ကိုသံိုးပနိုင္ ပတမ္္။

Private data ေတြသတ္မတ္ ိုန္႔သံိုးတဲာ့ method ေတြကို စစ္ေဆးတာေတြအတြက္လည္း


သံိုးပနင္ ပတမ္္။ eg မာဆို birthday ဟိုတ္မဟိုတ္ကိုစစ္ပနင္ ပတမ္္။ အသက္ ၁၀၀
ေက ာ္တမ္ဆိုတာ မ ဳေး ဲမစ္း ပတမ္္။ General Interbank Recurring Order (GIRO) ပနဲန္႔
customer တစ္ေမာက္ဟာ အသက္ ၁၄ ႏွာစ္ဆိုတာလည္းမျ စ္ပနိုင္ ပဘး္။

Inheritance

Class တစ္ ိုက အျ ား class ေတြကို inherit လို ္ပနိုင္ ပတမ္္။ super-class တစ္ ိုဆါကေပန class
တစ္ ို attribute ေတြ behavior ေတြ inherit လို ္ပနိုင္ ပတမ္္။ super-class ကေပန inherit
လို ္တဲာ့ class ကိုက ေတာာ့ sub-class လိုန္႔ေ ခ ပတမ္္။ super-class ကို anscestor
လိုန္႔လည္းေ ခ ပေသးတမ္္။

Class account အရဲာ့ model ကိုန္႔ႀကည္ာ့မမ္ဆိုအရင္ တကမ္ာ့ bank


ေတြအတြက္ ေတာ္ေတာ္ေလးကိုက္ညါ တာေတြန္႔ ပလမ္ာ့မမ္္။ Bank ေတြမာ account
အမ ဳေးမ ိုးအရ ပတမ္္။ eg. e.g. Savings Accounts, Giro Accounts and others္။
အမ ဳေးအစားေတြမတေ မဲလ
ာ့ ည္း ဘံိုတတဲာ့ properties ေတြ method ေတြအရႀက ပတမ္္။စ မာ
account number,holder,balance္။ ဒပအျ င္ အားလံိုးက deposit /withdraw
ေတြလို ္ပနင္ ပတမ္္။

ဒပႀကာင္ာ့အားလံိုးအတြက္အေျ ံ “fundamental” account အရျ ါးေတာာ့ အာလံိုးကသန္႔ဆါကေပန


inherit လို ္ ပတမ္္။ inheritance ကေတာာ့ အရျ ါးသား class ကိုအသံိုးျ ဳေျ ါးေတာာ့ class
အသစ္ေတြ တည္ေဆာက္တာျ စ္ ပတမ္္။ အသစ္လို ္လိုက္တာ့ဲ class ဟာ အရျ ါးသားကို
္ ည္ာ့တာေတြ ျ စ္ပနိုင္သလို အရတာေတြကိုမ ကပန္ာ့သတ္တာေတြလည္းျ စ္ပနိုင္ ပတမ္္။

Python မာ ဘမ္လို implement လို ္မလဲႀကည္ာ့အရေအာင္္။အအရင္း


ဆံိုး ံိုစံေလးတစ္ ိုတည္ေဆာက္ ႀကည္ာ့ ပမမ္္။
class Account(object):
pass
ိုေအရး ားတဲာ့ accout class မာ ဘာ attribute ဘာ method မမ ပ ပဘး္။ ိုဒါ empty class အရဲာ့
instance ေတြလို ္ႀကည္ာ့အရေအာင္
>>> from Account import Account
>>> x = Account()
>>> print x
<Account.Account object at 0x7f364120ab90>

Python2(ဘာသာျ ပန္) Han Phyo Oo 142


>>>

Definition of Methods

Method ပနဲန္႔ function ေအာက္ ပအတိုင္းကြဲ ပတမ္္။

 Class က ိုင္ျ ါးေတာာ့ class မ


ဲ ာ ဲ သတ္မတ္ ား ပတမ္္။
 Method definition အရဲာ့ မ parameter က class instance အရဲာ့ reference ျ စ္တာ့ဲ
“self”ျ စ္အရ ပမမ္္။
 Method ကိုေ ခအရာမာေတာာ့ “self” parameter မ ပ ပဘး

လက္အရါ class ကို method ေတြ ္ ည္ာ့ႀကည္ာ့အရေအာင္္။ method body


ေတာာ့မ ည္ာ့ေသး ပဘး္။
class Account(object):

def transfer(self, target, amount):


pass

def deposit(self, amount):


pass

def withdraw(self, amount):


pass

def balance(self):
pass

Constructor

Python မာ c++,java တိုန္႔လို explicit constructor ေတြမအရ ပဘး္။ဒပေ မမ္ာ့ __init__() method
ကေတာာ့ပနည္းပနည္းတ ပတမ္္။ သက constructor လို ္တဲာ့အလို ္ ေတာ္ေတာ္မ ားမ ား
လို ္ေ း ပတမ္္။ စ မာ. Class instance တစ္ ိုလို ္တာ့အ
ဲ ပ ၎ကို အအရင္ execute လို ္ ပတမ္္။
ပနာမည္ကလည္း construntor ပနဲာ့ဆင္ ပတမ္္။ ဒပေ မမ္ာ့ constructor လိုန္႔ေတာာ့ေ ခလိုန္႔မအရ ပဘး္။
ဘာေႀကာင္န္႔လဆ
ဲ ိုေတာာ့ __init__ ကိုေ ခတဲာ့အ ပန္ မာ instance ကလို ္ျ ါးေပနျ ါျ စ္ ပတမ္္။

ဒပေ မမ္ာ့ object initialize လို ္ ိုန္႔အတြက္ေတာာ့ __init__ method ကိုသံိုး ပတမ္္။ init ေအရးတဲာ့
ံိုစံကေတာာ့ တစ္ျ ား method ေတြေအရးသလို ပ ဲ္။
def __init__(self, holder, number, balance,credit_line=1500):
self.Holder = holder
self.Number = number
self.Balance = balance
self.CreditLine = credit_line

Python2(ဘာသာျ ပန္) Han Phyo Oo 143


Destructor

Constructor ေတြမာေျ ာသလို ဲ destructor လည္းအတတ ပ ဲ္။ destructor မအရေ မမ္ာ့


ဆင္တာအရ ပတမ္္။ eg. __del__ method ၊ instance တစ္ ိုကို က္ဆါးတဲာ့ အ ပ မာ ၎ ကိုေ ခ
ပတမ္္။ base class မာ __del__() method အရအရင္ ,derived class အရဲာ့ __del__() method
ကေပန ေ ခေ းအရ ပမမ္္။ example/
class Greeting:
def __init__(self, name):
self.name = name
def __del__(self):
print "Destructor started"
def SayHello(self):
print "Hello", self.name
ဒါ class ကိုသံိုးအရင္ del က __del__() method ကို direct ေ ခတာမဟိုတ္ေႀကာင္ာ့ ေတြန္႔ ပလမ္ာ့
မည္္။ x1 ကို က္တာ့အ
ဲ ပမာ destructor ကိုမေ ခအရေသး ပဘး္။ ဘာလိုလဆ
ဲ ိုေတာာ့ del က x1
object အတြက္ reference count ကို ေလ ာာ့လိုက္တာျ စ္ ပတမ္္။ reference count က zero
ျ စ္မသာ destructor ကို ေ ခ ပတမ္္။
>>> from hello_class import Greeting
>>> x1 = Greeting("Guido")
>>> x2 = x1
>>> del x1
>>> del x2
Destructor started

Complete Listing of the Account Class


class Account(object):
def __init__(self, holder, number, balance,credit_line=1500):
self.Holder = holder
self.Number = number
self.Balance = balance
self.CreditLine = credit_line

def deposit(self, amount):


self.Balance = amount

def withdraw(self, amount):


if(self.Balance - amount < -self.CreditLine):
# coverage insufficient
return False
else:
self.Balance -= amount
return True

def balance(self):
return self.Balance

def transfer(self, target, amount):


if(self.Balance - amount < -self.CreditLine):
# coverage insufficient
return False
else:

Python2(ဘာသာျ ပန္) Han Phyo Oo 144


self.Balance -= amount
target.Balance += amount
return True

Account.pyလိုန္႔သမ္း ားမမ္ဆိုအရင္ ဒါ class ကို interactive python shell မာသံိုးပနိုင္ ပတမ္္။


>>> import Account
>>> k = Account.Account("Guido",345267,10009.78)
>>> k.balance()
10009.780000000001
>>> k2 = Account.Account("Sven",345289,3800.03)
>>> k2.balance()
3800.0300000000002
>>> k.transfer(k2,1000)
True
>>> k2.balance()
4800.0300000000007
>>> k.balance()
9009.7800000000007
>>>
စ မာမာ မားေပနတာေလးေတြအရါ ပတမ္္။attribute ေတြကို အျ င္အရေပန direct access
အရေပန ပတမ္္။
>>> k.balance()
9009.7800000000007
>>> k2.Balance
4800.0300000000007
>>> k2.Balance += 25000
>>> k2.Balance
29800.029999999999
>>>

Data Encapsulation

Identifiter ကို “_” underscore character ပနဲန္႔ မစအရင္ အျ င္ကေပန အရမအသံိုးျ ဳေပနိုင္ ပတမ္္။
ဆိုလိုတာကေတာာ့ တပန္ ိုးေတြကို တ္လိုန္႔အရ ေျ ာင္းလဲလိုန္႔အရ ပတမ္္။ data ေတြကိုကာကြမ္ င္
အရင္ေတာာ့ member ေတြကို private or protected ားအရ ပမမ္္။ underscore character ႏွာစ္ ိုပနဲာ့
အစျ ဳေ ားတဲာ့ instance variable name ေတြကို class အျ င္ကေပန မသံိုးစြဲပနိုင္ ပဘး္။ direct
မအရေ မမ္ာ့လည္း private name mangling သံိုးျ ါး access သံိုးပနိုင္ ပေသးတမ္္။
ဆိုလိုတာကေတာာ့ private data __A ကို ေအာက္ ပအတိုင္းသံးပနိုင္ ပတမ္္။
instance_name._classname__A ေအာက္မာအရင္းျ ား ပတမ္္။
>>> from mangling import Mangling
>>> x = Mangling(42)
>>> x.__A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Mangling' object has no attribute '__A'
>>> x._Mangling__A
42
>>>

Python2(ဘာသာျ ပန္) Han Phyo Oo 145


Identifier ကို underscore တစ္ ပန
ို ဲန္႔ ဲ စ ားတာဆိုအရင္ ေတာန္႔ protected member ျ စ္ ပတမ္္။
protected member ေတြကို class အျ င္ကေပန public လို ဲ အရမအသံိုးျ ဳေပနိုင္ ပတမ္္။

Example.္။ encapsulation.py လိုန္႔သမ္း ားမမ္္။


class Encapsulation(object):
def __init__(self, a, b, c):
self.public = a
self._protected = b
self.__private = c
ေအာက္ ပ interactive seeeion မာ public,protected,private member
ေတြဘမ္လိုအလို ္လို ္လေ
ဲ တြန္႔ပနို္င္ ပတမ္္။
>>> from encapsulation import Encapsulation
>>> x = Encapsulation(11,13,17)
>>> x.public
11
>>> x._protected
13
>>> x._protected = 23
>>> x._protected
23
>>> x.__private
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Encapsulation' object has no attribute '__private'
>>>

ေအာက္မာဘမ္လိုအလို ္လို ္လဲေျ ာ ား ပတမ္္။

Name Notation Behaviour

name Public Can be accessed from inside and outside

_name Protected Like a public member, but they shouldn't be directly accessed
from outside.

__name Private Can't be seen and accessed from outside

Account classအရဲာ့ private member ေတြ ပတဲာ့ constructor ပ္။


def __init__(self, holder, number, balance,credit_line=1500):
self.__Holder = holder
self.__Number = number
self.__Balance = balance
self.__CreditLine = credit_line

Python2(ဘာသာျ ပန္) Han Phyo Oo 146


Class and Object Variables

Object variable (instance variable )ေတြေတာာ့သံိုး ာ့ျဲ ါ္။ ၎ variable ေတြဟာ မတညါတာ့ဲ
object ေတြအတြက္မတညါတာ့ဲ value ေတြအရႀက ပတမ္္။eg္။ account ႏွာစ္ ိုမာဆိုအရင္ acoount
number မတပနိုင္သလို balance ေတြလည္း တ င္မတ ပလမ္ာ့မမ္္။ Object variable ေတြကို
object ေတြ class instacce ေတြစတဲန္႔ ဆိုင္အရာဆိုင္အရာက ိုင္ဆိုင္ႀက ပတမ္္။ object
ေတြအရဲာ့ကိုမ္ ိုင္ variable ေတြျ စ္ ပတမ္္။ object တစ္ ိုျ င္းစါ အတြက္ ပန္တါးေ း ားတာ ျ
ျ စ္တာေႀကာင္ာ့ non-static or dynamic variable or members လိုန္႔ေ ခႀက ပတမ္္။
Class variable ကေတာာ့ object အားလံိုးကမ ေ၀သံိုးစြဲႀက ပတမ္္။ သတိုန္႔ကိုေတာာ့ မည္သည္ာ့
object ကေပနမဆို ေျ ာင္းလဲမေတြလို ္ပနိုင္ ပတမ္္။ object အားလံိုးအတြက္ တစ္ ို ဲအရတာေႀကာင္ာ့
အျ ား object ေတြအတြက္လည္းေျ ာင္းလဲ ပတမ္္။

Static variable အတြက္ example အေပနပနဲန္႔္။ account စိုစိုေ ပင္း တြက္မမ္ာ့ counter variable
တစ္ ိုလို ္ ပမမ္္။ ဒပကို class အရဲာ့ေအာက္မာ တစ္ ပ ဲျ ဳေလို ္သြား ပမမ္္။ constructor
ကိုေ ခတိုင္း variable ကို တိုးသြား ပမမ္္။ account အရဲာ့ object ကို က္မမ္ဆိုအရင္
ေလ ာာ့သြား ပမမ္္။
class Account(object):
counter = 0
def __init__(self, holder, number, balance,credit_line=1500):
Account.counter += 1
self.__Holder = holder
self.__Number = number
self.__Balance = balance
self.__CreditLine = credit_line
def __del__(self):
Account.counter -= 1
Interaction session မာ ျ သြား ပမမ္္။
>>> from Account import Account
>>> Account.counter
0
>>> a1 = Account("Homer Simpson", 2893002, 2325.21)
>>> Account.counter
1
>>> a2 = Account("Fred Flintstone", 2894117, 755.32)
>>> Account.counter
2
>>> a3 = a2
>>> Account.counter
2
>>> a4 = Account("Bill Gates", 2895007, 5234.32)
>>> Account.counter
3

Python2(ဘာသာျ ပန္) Han Phyo Oo 147


>>> del a4
>>> Account.counter
2
>>> del a3
>>> Account.counter
2
>>> del a2
>>> Account.counter
1
Inheritance

Account class ကေပန inherit လို ္ပနိုင္တာ့ဲ Counter class တစ္ ိုလို ္ျ ါး inheritance
ကိုစမ္းႀကည္ာ့ ပမမ္္။ ဒပဆိုအရင္ account သိုန္႔ အျ ား class ေတြ မ
ဲ ာ count
လို ္စအရာမလိုေတာာ့ ပဘး္။ eg member or employee

Class တစ္ ိုဘမ္ CLASS ကေပန inherit လို ္ ားတမ္ဆိုတာ(super-class )


ကိုေ ာ္ျ တာလြမ္ ပတမ္္။ class name ေပနာက္က () မ
ဲ ာ super-class ကို ည္ာ့ေ းအရံို ပ ဲ္။

ေအာက္မာ account class ကို super-class အေပနပနဲာ့ ားတဲာ့ counter class


ကိုေ ာ္ျ ား ပတမ္္။
class Counter(object):
number = 0

def __init__(self):
type(self).number += 1

def __del__(self):
type(self).number -= 1

class Account(Counter):
def __init__(self,
account_holder,
account_number,
balance,
account_current=1500):
Counter.__init__(self)

Multiple Inheritance

Class တစ္ ိုသည္ inherit လို ္ျ င္းကို class တစ္ ို က္ ို လို ္ေဆာင္ပနိုင္ ပတမ္္။ ဒပကို
multiple inheritance လိုန္႔ေ ခ ပတမ္္။ ေအရးသားတာကေတာာ့လြမ္ ပတမ္္။ super-class
အားလံိုးကို class ေပနာက္က () မ
ဲ ာ comma ံျ ါးေအရးသားပနိုင္ ပတမ္္။
class NN (class1, class2, class3 ...):
This class inherits from class1, class2, and so on.

Python2(ဘာသာျ ပန္) Han Phyo Oo 148


Chapter 35
Inheritance Example

Introduction

Web ေ ခမာ inheritance တ္သတ္တဲာ့ example မ ားစြာေတြန္႔ပနင္ ပတမ္္။ လြမ္ကအရိုးအရင္း


တာေတြ အရသလို အအရမ္း က္ တ
ဲ ာေတြည္း ေတြန္႔ ပနိုင္ ပတမ္္။ ဒပေႀကာင္ာ့ အအရမ္းလည္း မ က္ ဲ
လက္ေတြန္႔လည္း အသံိုး၀င္ျ ါးေတာာ့ inheritance အရဲာ့အေျ ံ သေဘာတအရားေတြကို
အရင္းလင္းျ င္ ပတမ္္။

ဒါအတြက္ base class ႏွာစ္ ိုလို ္ ပမမ္္။ clock အတြက္အရမ္ calendar အတြက္အရမ္ျ စ္ ပတမ္္။ ဒါ
ႏွာစ္ ိုအေ ခမာ အေျ ံျ ါးေတာာ့(inherit) CalendarClock ဆိုတဲာ့ class ျ ဳေလို ္ ား ပတမ္္။

The Clock Class


class Clock(object):

def __init__(self,hours=0, minutes=0, seconds=0):


self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds

def set(self,hours, minutes, seconds=0):


self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds

def tick(self):
""" Time will be advanced by one second """
if self.__seconds == 59:
self.__seconds = 0
if (self.__minutes == 59):
self.__minutes = 0
self.__hours = 0 if self.__hours==23 else self.__hours+1
else:
self.__minutes += 1;
else:
self.__seconds += 1;

def display(self):
print("%d:%d:%d" % (self.__hours, self.__minutes, self.__seconds))

def __str__(self):
return "%2d:%2d:%2d" % (self.__hours, self.__minutes,
self.__seconds)

x = Clock()
print(x)
for i in xrange(10000):
x.tick()
print(x)

Python2(ဘာသာျ ပန္) Han Phyo Oo 149


The Calendar Class
class Calendar(object):
months = (31,28,31,30,31,30,31,31,30,31,30,31)

def __init__(self, day=1, month=1, year=1900):


self.__day = day
self.__month = month
self.__year = year

def leapyear(self,y):
if y % 4:
# not a leap year
return 0;
else:
if y % 100:
return 1;
else:
if y % 400:
return 0
else:
return 1;

def set(self, day, month, year):


self.__day = day
self.__month = month
self.__year = year

def get():
return (self, self.__day, self.__month, self.__year)
def advance(self):
months = Calendar.months
max_days = months[self.__month-1]
if self.__month == 2:
max_days += self.leapyear(self.__year)
if self.__day == max_days:
self.__day = 1
if (self.__month == 12):
self.__month = 1
self.__year += 1
else:
self.__month += 1
else:
self.__day += 1

def __str__(self):
return str(self.__day)+"/"+ str(self.__month)+ "/"+ str(self.__year)

if __name__ == "__main__":
x = Calendar()
print(x)
x.advance()
print(x)

Python2(ဘာသာျ ပန္) Han Phyo Oo 150


The Calendar-Clock Class
from clock import Clock
from calendar import Calendar

class CalendarClock(Clock, Calendar):

def __init__(self, day,month,year,hours=0, minutes=0,seconds=0):


Calendar.__init__(self, day, month, year)
Clock.__init__(self, hours, minutes, seconds)

def __str__(self):
return Calendar.__str__(self) + ", " + Clock.__str__(self)

if __name__ == "__main__":
x = CalendarClock(24,12,57)
print(x)
for i in range(1000):
x.tick()
for i in range(1000):
x.advance()
print(x)

Python2(ဘာသာျ ပန္) Han Phyo Oo 151


Chapter 36
Slots

Avoiding Dynamically Created Attributes

Object ေတြအရဲာ့ attribute ေတြကို “__dict__”ဆိုတဲာ့ dictionary မ


ဲ ာသမ္း ား ပတမ္္။ အျ ား
dictionary ေတြလို ဲ attribute အတြက္ သံိုးတဲာ့ dictionary ေတြမာ element
ဘမ္ေလာက္ ပမမ္ ဆိုတဲာ့ တက တဲာ့ သတ္မတ္ က္မအရ ပဘး္။
ကိုမ္လို င္လို ္ ည္ာ့ပနင္ ပတမ္္။ ဒပေႀကာင္ာ့ ဲ class object ေတြ အရဲာ့ attribute ေတြကို
dynamically ္ ည္ာ့ပနိုင္တာျ စ္ ပတမ္္။
>>> class A(object):
... pass
...
>>> a = A()
>>> a.x = 66
>>> a.y = "dynamically created attribute"
“a”အရဲာ့ attribute ေတြ ပတဲာ့ dictionary ကိုေအာက္ ပအတိုင္း အရမအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> a.__dict__
{'y': 'dynamically created attribute', 'x': 66}
ဒါလို attribute ေတြကို dynamic ည္ာ့ပနိုင္တာကိုေတြန္႔ပနိုင္ ပတမ္္။ ဒပေ မမ္ာ့ built-in class
ေတြျ စ္တာ့ဲ “int” သိုန္႔ “list”ေတြမာေတာာ့လို ္လိုန္႔မအရ ပဘး္။
>>> x = 42
>>> x.a = "not possible to do it"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'a'
>>>
>>> lst = [34, 999, 1001]
>>> lst.a = "forget it"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'a'

Dictionary ေတြကိုattribute ေတြသမ္း ိုန္႔သံိုးတာအဆင္ေျ ပတမ္္။ ဒပေ မမ္ာ့ variable


ပနည္းပနည္းေလးအရတဲာ့ object ေတြအတြက္ ေတာာ့ space ျ ဳေပန္းတါးအရာေအရာက္ ပတမ္္။ instance
ေတြအမ ားႀကါးလို ္မမ္ဆိုအရင္ေတာာ့ ဒါလို space consumption ဟာ အႏွာၱအရာမ္အရ ပတမ္္။
ဒါျ ပနာ အတြက္ဆိုအရင္ slots ကိုသံိုးအရ ပမမ္္။ object attribute ေတြကို dynamic
ည္ာ့ ြင္ာ့ေ းမည္ာ့ အစား slots ကေတာာ့ object ပန္တါးျ ါးအရင္ မေျ ာငး္လပန
ဲ ိုင္တာ့ဲ static-structure
ပနဲာ့အလို ္လို ္ ပတမ္္။

Class တစ္ ိုကို design လို ္အရာမာ slot ကိုသံိုးျ ါး attribute dynamic creation ကိုကာကြမ္
ပနိုင္ ပတမ္္။ slot လို ္ ိုန္႔အတြက္ “__slots__” ဆိုတဲာ့ list တစ္ ိုလို ္ေ းအရ ပမမ္္။ list မ
ဲ ာ

Python2(ဘာသာျ ပန္) Han Phyo Oo 152


ကိုမ္သံိုး င္တဲာ့ attribute ေတြ ပအရ ပမမ္္။ ေအာက္ ပ example မာ val ဆိုတဲာ့ attribute
တစ္ ို ဲ ပတဲာ့ slot list တစ္ ိုလို ္ ား ပတမ္္။
class S(object):

__slots__ = ['val']

def __init__(self, v):


self.val = v

x = S(42)
print(x.val)

x.new = "not possible"

program ကို run လိုက္မမ္ဆိုအရင္ dynamic attribute ေတြလို ္မအရတာ ေတြန္႔ ပလမ္ာ့မမ္္။ 42
Traceback (most recent call last):
File "slots_ex.py", line 12, in <module>
x.new = "not possible"
AttributeError: 'S' object has no attribute 'new'
Slot ေတြဟာ object ေတြကspace comsuption လို ္တာကို ကာကြမ္ေ းတမ္လိုန္႔ေျ ာ ဲာ့
ပတမ္္။ python 3.3 ေပနာက္မာေတာာ့ သ ္ျ ါးအသံိုးမ၀င္ေတာာ့ ပဘး္။ python 3.3 မာ object
ေတြကို သမ္း ိုန္႔အတြက္ Key-Sharing dictionary ေတြကိုသံိုး ပတမ္္။ instance ေတြအရဲာ့ attribute
ေတြဟာ တစ္ ိုပနဲာ့ တစ္ ို မ ေ၀သံိုးစြဲလာပနိုင္ ပတမ္္။ ဆိုလိုတာက key သမ္း ားတဲာ့ အ ိုင္းပနဲာ့
သက္ဆိုင္အရာ hash ေတြကိုျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ non-builtin type instance ေတြအမ ား ႀကါး
တည္ေဆာက္တန္႔ဲ program ေတြမာ memory consumption ကိုေလ ာာ့ ေ း ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 153


Chapter 37
Classes and Class Creation

New-style vs. old-style Classes

Python2 မာအေအရာ့ ပန္းေတြမာေျ ာ ဲသလို ဲ အရို ္ေ ြးပနိုင္တာတစ္ ိုအရ ပတမ္္။ The coexistence
of old-style and new-style classes.

Official python reference မာေအာက္ ပအတိုင္းေျ ာ ား ပတမ္္။

"New-style classes were introduced in Python 2.2 to unify classes and types. A new-
style class neither more nor less than a user-defined type. If x is an instance of a
new-style class, then type(x) is the same as x.class."

ေပနာက္တစ္ ိုဒ္ကေတာာ့ new-style class ကိုဘာေႀကာင္ာ့လို ္အရလဲေျ ာ ား ပတမ္္။ “to provide


a unified object model with a full meta-model"လိုန္႔ေျ ာ ား ပတမ္္။ အျ ား ျ စ္တာ့ဲ
"immediate benefits" the "ability to subclass most built-in types, or the introduction
of 'descriptors', which enable computed properties."ေတြလည္းေျ ာ ား ပတမ္္။

Syntactic အပနည္းငမ္သာကြာ ပတမ္္။ new-style class ျ စ္ ိုန္႔အတြက္ new-stycle class


object တစ္ ိုသိုန္႔ အျ ား new-style class တစ္ ိုကေပန inherit လို ္အရ ပမမ္္။ python 3 မာေတာာ့
new-style class ဲအရ ပတမ္္။
# old-style class
class A:
pass
class B(A):
pass
a = A()
b = B()
print(type(A), type(B))
print(type(a), type(b))
အ က္ေ ာ္ျ ပ program ကို execute လို ္အရင္ေအာက္ ပအတိုင္းအရ ပမမ္္။
(<type 'classobj'>, <type 'classobj'>)
(<type 'instance'>, <type 'instance'>)

# new-style class
class A(object):
pass
class B(A):
pass
a = A()
b = B()

Python2(ဘာသာျ ပန္) Han Phyo Oo 154


print(type(A), type(B))
print(type(a), type(b))
အ က္ေ ာ္ျ ပ code ကို execute လို ္အရင္ေအာက္ ပအတိုင္းအရ ပမမ္္။
(<type 'type'>, <type 'type'>)
(<class '__main__.A'>, <class '__main__.B'>)

ေအာက္ ပေ ပင္းစစ္ကေတာာ့ new-style class ပနဲာ့သတ္မတ္ ားမအရ ပမမ္္။

Behind the scenes: Relationship between Class and type

Class ေတြသတ္မတ္အရင္ object ေတြလို ္အရင္ ေပနာက္ကမ


ြ ္မာဘာေတြျ စ္ေပနလဲ ႀကည္ာ့အရေအာင္ ္။

Type ပနဲန္႔ class ေတြႀကားဆက္ႏွာြမ္မေတြအအရင္ႀကည္ာ့မမ္္။ class


တစ္ ိုတည္ေဆာက္တဲာ့အ ပ ေပနာ္ကမာဘာေတြျ စ္ေပနလဲေ ပာ့္။ object ကို type ပနဲံန္႔ႀကည္ာ့အရင္objet
ဟာ ဘမ္ class ကလဲ ဆိုတာေတြန္႔မာျ စ္ ပတမ္္။
x = [4, 5, 9]
y = "Hello"
print(type(x), type(y))
ေအာက္ ပအတိုင္း ေတြန္႔မာ ပ္။
(<type 'list'>, <type 'str'>)
Class အရဲာ့ name ကိုမ type ပနဲန္႔ႀကည္ာ့အရင္ type ဆိုတဲာ့ class ကိုအရမာ ပ
print(type(list), type(str))
ေ အာက္ ပအတိုင္းေတြန္႔မာ ပ္။
(<type 'type'>, <type 'type'>)
ဒပက type(x) type(y) ေတြကို type ပနဲာ့ႀကည္ာ့တာပနဲာ့တ ပတမ္္။
x = [4, 5, 9]
y = "Hello"
print(type(x), type(y))
print(type(type(x)), type(type(y)))
ေ အာက္ ပအတိုင္းေတြန္႔မာ ပ္။
(<type 'list'>, <type 'str'>)
(<type 'type'>, <type 'type'>)
User-defined class ဆိုတာအမပန္ေတာာ့ type ဆိုတာ့ဲ class အရဲာ့ object သာျ စ္ ပတမ္္။

ဒပႀကာင္ာ့ class ေတြဟာ type ဆိုတဲာ့ class ကေပန ပန္တါးတာျ စ္ ပတမ္္။ puthon 3 မာ ေတာာ့
class ပနဲန္႔ type အတတ ပ ဲ္။

One argument အစာ းtype ကို parameter 3 ိုပနဲန္႔ အသံိုးျ ဳေပနိုင္ ပတမ္္။
type(classname, superclasses, attributes_dict)

Python2(ဘာသာျ ပန္) Han Phyo Oo 155


type က argument သံိုး ိုပနာ့ေ
ဲ ခ ား ပတမ္္။ type object အသစ္တစ္ ို return ျ ပန္ေ း ပတမ္.
Class အရဲာ့ dynamic form ကိုေတြန္႔ပနို္င္ ပတမ္္။

 “”classname”ကေတာာ့ class name အတြက္ string ျ စ္ျ ါးေတာာ့ name attribute


ျ စ္လာ ပတမ္္။
 “superclass”ကေတာာ့ list သန္႔ို tuple ျ စ္ျ ါးေတာာ့ က ပန
ြ ္ေတာ္တိုန္႔ class အရဲာ့ super-class
ေတြ ပ၀င္ ပတမ္္။ list or type က base attribure ေတြျ စ္လာ ပတမ္္။
 “attributes_dict”ကေတာာ့ dictionary ျ စ္ ပတမ္္။ ကၽြပန္ေတာ္တိုန္႔ class အရဲာ့ namespace
အေပနပနဲာ့အလို ္လို ္ ပတမ္္။ class body အရဲာ့ definition ေတြ ပျ ါးေတာာ့ dict attribute
ျ စ္လာ ပတမ္္။

Class definition တစ္ ိုကိုႀကည္ာ့ႀကည္န္႔အရေအာင္


class A(object):
pass
x = A()
print(type(x))
result အေပနပနဲာ့ ေအာက္ ပအတိုင္းေတြန္႔မာျ စ္ ပတမ္္။
<class '__main__.A'>

၎အတြက္ လည္း type ကိုသံိုးပနိုင္ ပတမ္္။


A = type("A", (), {})
x = A()
print(type(x))
result အေပနပနဲာ့ ေအာက္ ပအတိုင္းေတြန္႔မာျ စ္ ပတမ္္။
<class '__main__.A'>
{'__doc__': None, '__module__': '__main__', '__dict__': <attribute
'__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A'
objects>}
ေျ ာအရအရင္ class A ကိုေအာက္ ပအတိုင္းသတ္မတ္ပနိုင္ ပတမ္္။
type(classname, superclasses, attributedict)
“type”ကိုေ ခတဲာ့အ ပမာ type အရဲာ့ call method ကိုေ ခ ပတမ္္။ call method ကေပနမ အျ ား
method ေတြျ စ္တာ့ဲ new ပနဲန္႔ init ကိုေ ခ ပတမ္္။
type.__new__(typeclass, classname, superclasses, attributedict)
type.__init__(cls, classname, superclasses, attributedict)
new method ကေပန မ class objet အသစ္တစ္ ိုလို ္ျ ါးေတာာ့ return ျ ပန္ေ း ပတမ္္။
၎ေပနာက္မာေတာာ့ init method ကေပနျ ါးေတာာ့ အသစ္ ပန္တါးလိုက္တဲာ့ object ကို initialize
လို ္ ပတမ္္။
class Robot(object):
counter = 0
def __init__(self, name):
self.name = name
def sayHello(self):
return "Hi, I am " + self.name

Python2(ဘာသာျ ပန္) Han Phyo Oo 156


def Rob_init(self, name):
self.name = name
Robot2 = type("Robot2",
(),
{"counter":0,
"__init__": Rob_init,
"sayHello": lambda self: "Hi, I am " + self.name})
x = Robot2("Marvin")
print(x.name)
print(x.sayHello())
y = Robot("Marvin")
print(y.name)
print(y.sayHello())
print(x.__dict__)
print(y.__dict__)
ေအာက္ ပ output ကိုအရ ပမမ္္။
Marvin
Hi, I am Marvin
Marvin
Hi, I am Marvin
{'name': 'Marvin'}
{'name': 'Marvin'}
Robot ပနဲR
ာ့ obot2 class ႏွာစ္ ိုဟာ syntactically အေပနပနဲာ့ မတ ပဘး logically အေပနပနဲာ့ ေတာာ့
အတတ ဲျ စ္ ပတမ္္။

မစ မာမာ python ႕လို ္တာက ံိုမပန္အတိုင္း class လို ္အရင္ဘာေတြလို ္သလဲဆိုေတာာ့္။


python ကေပနျ ါးေတာာ့ class Robot အရဲာ့ statement ေတြကို process လို ္ျ ါးေတာာ့ robot class
အရဲာ့ method ေတြ attribute ေတြကိုအရမကာ call type အရဲာ့ attributes_dict က
ဲ ို ည္ာ့ ပတမ္္။
ဒပေႀကာင္ာ့ python က Robot2 မာလို ္သလို ဲ type ကို call လို ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 157


Chapter 38
On the Road to Metaclasses

Motivation for Metaclasses

ဒါအ ိုင္းမာေတာာ့ metaclass ဘာေႀကာင္ာ့သံိုးအရတာလဲ ဆိုတအ


ဲာ့ ေႀကာင္းေျ ာ င္ ပတမ္ ္။
metaclass ကေပနေျ အရင္းေ း ပနင္းတဲာ့ design problem ေတြကို demo ျ ိုန္႔ philosopher class
ေတြတည္ေဆာက္သာြ း ပမမ္္။ philosopher class
တိုင္းအတြက(္ Philosopher1,philosoper2,etc) method ေတြ ပ၀င္ ပမမ္္။ လံိုး၀မေကာင္းတဲာ့
ပနည္းလမ္းကေတာာ့ class တိုင္းမာ တညါတဲာ့ code ေတြ ပေပနတာ ပ ဲ္။
class Philosopher1:

def the_answer(self, *args):


return 42

class Philosopher2:
def the_answer(self, *args):
return 42

class Philosopher3:
def the_answer(self, *args):
return 42

plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)
print(kant.the_answer())
42
42
“the_answer” method ကို ြား ားတာေတြေတြန္႔မာျ စ္ ပတမ္္။ error ျ စ္ပနိုင္လို maintain
လို ္ ိုန္႔လည္း က္ ပတမ္္။

သ ာ့သ
ဲ ေလာက္ပနာ့ဲ redundant code ေတြကိုေျ အရင္းမမ္ဆိုအရင္ေတာာ့ “the_answer” method
ပ၀င္တာ့ဲ Base class တစ္ ိုတည္ေဆာက္မာ ပ ္။ျ ါးေတာာ့ Philosoper class ေတြက inherit
လို ္မာျ စ္ ပတမ္္။
class Answers:
def the_answer(self, *args):
return 42

class Philosopher1(Answers):
pass
class Philosopher2(Answers):
pass
class Philosopher3(Answers):
pass
plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)

Python2(ဘာသာျ ပန္) Han Phyo Oo 158


print(kant.the_answer())
42
42

ဒါလိုလို ္လိုက္အရင္ philosopher class တိုင္းမာ “the_answer”method ပေပနမာ ပ္။ ၎ method


လိုမလိုဆိုတာ ႀကိုမသပနိုင္ဘးဆို ပစိုန္႔္။ ဒပကို run-time မ ဲဆံိုးျ တ္မမ္ လိုန္႔ ားလိုက္ ပမမ္္။
ဒပကိုဆံိုးျ စ္တာက configuration file,user input ,တြက္ က္မတစ္ ိုေ ခမတည္လမ္ာ့မမ္္။
# the following variable would be set as the result of a runtime
calculation:
x = input("Do you need the answer? (y/n): ")
if x=="y":
required = True
else:
required = False

def the_answer(self, *args):


return 42

class Philosopher1:
pass
if required:
Philosopher1.the_answer = the_answer

class Philosopher2:
pass
if required:
Philosopher2.the_answer = the_answer

class Philosopher3:
pass
if required:
Philosopher3.the_answer = the_answer

plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
Do you need the answer? (y/n): y
42
42
ဒပက ဒါျ ပနာအတြက္ ေျ အရင္း က္တစ္ ိုဆိုေ မဲာ့ မေကာင္းတာေတြအရ ပေသးတမ္္။
ဘာလိုလဆ
ဲ ိုေတာာ့ class တိုင္းကို code အတတေတြ ည္ာ့အရမာျ စ္ျ ါး ဒပကေ
ို မန္႔ပနိုင္ ပေသးတမ္္။
ဒပာ့အျ င္ method ေတြအမ ားႀကးဆိုအရင္ အရို ္ေ းြပနိုင္ ပေသးတမ္္။

ဒပကို ိုေကာင္းေအာင္း manager function တစ္ ိုလို ္ျ ါး redundant code ေတြ မ္ပနိုင္ ပတမ္္။
manager function ကိုသံိုးျ းေတာာ့ calss ကို conditionally augument လို ္မာ ပ္။
# the following variable would be set as the result of a runtime
calculation:

Python2(ဘာသာျ ပန္) Han Phyo Oo 159


x = input("Do you need the answer? (y/n): ")
if x=="y":
required = True
else:
required = False

def the_answer(self, *args):


return 42

# manager function
def augment_answer(cls):
if required:
cls.the_answer = the_answer

class Philosopher1:
pass
augment_answer(Philosopher1)
class Philosopher2:
pass
augment_answer(Philosopher2)
class Philosopher3:
pass
augment_answer(Philosopher3)

plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
Do you need the answer? (y/n): y
42
42
ျ ပနာကိုေျ အရင္း န္႔အ
ို သံိုး၀င္ေ မမ္ာ့ကၽြပန္ေတာ္ တိုန္႔က manage fuction ျ စ္တာ့ဲ
“augument_answer” ကို ေ ခ ိုန္႔ေမန္႔ပနိုင္ ပေသးတမ္္။ code ေတြကို အလိုအေလ ာက္ execute
လို ္သင္ာ့ ပတမ္္။ class definition ျ ါးလ င္ အလိုအေလ ာက္ အလို ္လို ္မမ္ာ့ code အ ဳေလို
ေပန ပတမ္္။
# the following variable would be set as the result of a runtime
calculation:
x = input("Do you need the answer? (y/n): ")
if x=="y":
required = True
else:
required = False

def the_answer(self, *args):


return 42

def augment_answer(cls):
if required:
cls.the_answer = the_answer
# we have to return the class now:

Python2(ဘာသာျ ပန္) Han Phyo Oo 160


return cls

@augment_answer
class Philosopher1:
pass
@augment_answer
class Philosopher2:
pass
@augment_answer
class Philosopher3:
pass

plato = Philosopher1()
kant = Philosopher2()

# let's see what Plato and Kant have to say :-)


if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
Do you need the answer? (y/n): y
42
42
Metaclass ေတြကိုေ ာျ ပျ ပနာေတြအတြက္သံိုးပနိုင္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 161


Chapter 39

Metaclasses

Metaclass ေတြဆိုတာကေတာာ့ class တစ္ ို ဲျ စ္ျ ါးေတာာ့ ၎ အရဲာ့ object ေတြကလည္း class
ေတြ ဲျ စ္ ပတမ္္။ ံိုမပန္ classs တစ္ို ိုက class object behavior ေတြကိုသတ္မတ္သလို ဲ
,metaclass ကလည္း class ေတြပနဲန္႔ ၎ အရဲာ့ object ေတြအတြက္ကို behavior
ေတြသတ္မတ္ေ း ပတမ္္။

Metaclass ေတြကို OOP language တင


ို ္းက ေ ာက္ ံန္႔ေ းတာေတာာ့မဟိုတ္ ပဘး္။
အေ ာက္အ ံာ့ မေ းတဲာ့ language ေတြမာ အျ ားပနည္းသံိုးႀက ပတမ္္။ python ကေတာာ့
ေ ာက္ ံာ့ ေ း ပတမ္္။

Metaclass အသံိုးျ ဳေ ံိုမ ားစြာအရ ပတမ္္။

 logging and profiling


 interface checking
 registering classes at creation time
 automatically adding new methods
 automatic property creation
 proxies
 automatic resource locking/synchronization.

Defining Metaclasses

Metaclass ကအျ ား class ပနဲာ့တေ မမ္ာ့ အျ ား class ေတြက “type” ကေပန inherit
လို ္ ားတာျ စ္ ပတမ္္။ ေပနာက္မတတာက metaclass ကိုသံိုး ားတဲာ့ class statement
ေတြဆံိုးအရင္ metaclass ေတြကို အလိုအေလ ာက္ ေ ခေ း ပတမ္္။ metaclas မသံိုး ားအရင္
type() class ကိုေ ခတာျ စ္ျ ါး သံိုး ားအရင္ေတာာ့ type အစား metaclass ကိုေ ခတာျ စ္ ပတမ္္။

Metaclass ေလးတစ္ ိုတည္ေဆာက္ႀကည္ာ့ ပမမ္္။ __new__ method ဲက argument


content ေတြကို print ိုတ္တာအရမ္ __new__ type ကိုေ ခတဲာ့အ ပအရလာတဲာ့ result ကို return
ျ ပန္တာအရမ္ ပ ပမမ္္။
class LittleMeta(type):
def __new__(cls, clsname, superclasses, attributedict):
print("clsname: ", clsname)
print("superclasses: ", superclasses)
print("attributedict: ", attributedict)
return type.__new__(cls, clsname, superclasses, attributedict)

“LittleMeta” ဆိုတဲာ့ metaclass ကိုေအာက္ ပ example မာသံိုး ပမမ္္။


class S:

Python2(ဘာသာျ ပန္) Han Phyo Oo 162


pass
class A(S, metaclass=LittleMeta):
pass
a = A()
clsname: A
superclasses: (<class '__main__.S'>,)
attributedict: {'__module__': '__main__', '__qualname__': 'A'}
LittleMeta.__new__ ကိုေ ခတာျ စ္ျ ါးေတာာ့ type.__new__ ကိုမသံိုးတာေတြန္႔ ပမမ္္။

အအရင္ chapter က အ ိုင္းကိုျ ပန္သာြ းအရေအာင္ “EssentialAnswers”ဆိုတဲာ့ metaclass


တည္ေဆာက္ ပမမ္္။ ၎ က လိုအ ္တဲာ့ augument_answer method
ကိုအလိုအေလ ာက္ ည္ာ့သင
ြ ္း ေ းပနိုင္ ပတမ္္။
x = input("Do you need the answer? (y/n): ")
if x.lower() == "y":
required = True
else:
required = False

def the_answer(self, *args):


return 42

class EssentialAnswers(type):

def __init__(cls, clsname, superclasses, attributedict):


if required:
cls.the_answer = the_answer

class Philosopher1(metaclass=EssentialAnswers):
pass
class Philosopher2(metaclass=EssentialAnswers):
pass
class Philosopher3(metaclass=EssentialAnswers):
pass

plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)
print(kant.the_answer())
Do you need the answer? (y/n): y
42
42
Class definition ျ ါးအရင္ pyton ကေအာက္ ပ function ကိုေ ခ ပတမ္္။
type(classname, superclasses, attributes_dict)
metaclass ကို header အေပနပနဲာ့ေျ ာ ားအရင္ ဒပကျ ပနာမဟိုတ္ ပဘး္။ ိုပန example မာ
ဒါလိုလို ္ ားတာျ စ္ ပတမ္္။ Philosopher1, Philosopher2 and Philosopher3ေတြကို
metaclass ျ စ္တာ့ဲ EssentialAnswers ပနဲန္႔ တ္ ား ပတမ္္။ဒပေႀကာင္ာ့ type အစား
EssentialAnswer ကိုေ ခတာျ စ္ ပတမ္္။
EssentialAnswer(classname, superclasses, attributes_dict)
အတအက ေျ ာအရအရင္ call လို ္တဲာ့ argument ေတြကိုေအာက္ ပတပန္ ိုးေတြျ စ္ ပတမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 163


EssentialAnswer('Philopsopher1',
(),
{'__module__': '__main__', '__qualname__': 'Philosopher1'})
အျ ား philosopher class ေတြအတြက္လည္းအတတ ျဲ စ္ ပတမ္္။

Creating Singletons using Metaclasses

Singleton pattern ဆိုတာကေတာာ့ design pattern တစ္ ိုျ စ္ျ ါးေတာာ့ class တစ္ ိုအတြက္ ကို
object တစ္ ိုလိုကပန္သတ္ ား ပတမ္္။ object တစ္ ို ဲလိုအ ္တာ့အ
ဲ ပသံိုး ပတမ္္။
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton,
cls).__call__(*args, **kwargs)
return cls._instances[cls]

class SingletonClass(metaclass=Singleton):
pass
class RegularClass():
pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y)
True
False
Creating Singletons using Metaclasses

ေပနာက္တစ္ပနည္းအေပနပနဲာ့ေတာာ့ singleton class တစ္ ို ကို အျ ား singleton class တစ္ ိုကေပန


inherit လို ္ျ ါး ပန္တါးတာျ စ္ ပတမ္္။
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance

class SingletonClass(Singleton):
pass
class RegularClass():
pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y)

True
False

Python2(ဘာသာျ ပန္) Han Phyo Oo 164


Chapter 40
Metaclass Use Case: Count Function Calls

Introduction

ဒါအ ပန္းမာေတာာ့ meatclass use case ကို စ မာပနဲာ့ေျ ာသြားမာျ စ္ ပတမ္္။ metaclass တစ္ ိုကို
တည္ေဆာက္မမ္ ၎ ျ ါးေတာာ့ subclass အရဲာ့ method ေတြကို decorate လို ္မာျ စ္ ပတမ္္။
decorator ကေပန return ျ ပန္လာတဲာ့ decorated function ေတြက subclass အရဲာ့ method ေတြကို
ဘမ္ႏွာစ္ႀကမ္ call လို ္လဲဆိုတာကို ေအရတြက္ပနိုင္ ပတမ္္။

Preliminary Remarks

ျ ပနာကို မေျ အရင္း င္ class attribute ေတြကို ဘမ္လို access လို ္လဲျ ပန္ႀကည္ာ့အရေအာင္္။
list class ပနဲာ့ျ ပမမ္္။ class တစ္ ိုအရဲာ့ non-private attribute list
ကိုေအာက္ ပအတိုင္းအရပနိုင္ ပတမ္္။
import random
cls = "random" # name of the class as a string
all_attributes = [x for x in dir(eval(cls)) if not x.startswith("__") ]
print(all_attributes)
ဒပဆိုေအာက္ ပအတိုင္းအရ ပမမ္္။
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',
'_Set', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi',
'_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'expovariate',
'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate',
'normalvariate', 'paretovariate', 'randint', 'random', 'randrange',
'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform',
'vonmisesvariate', 'weibullvariate']

Public method ေတြကို ဲ filter လို ္ႀကည္ာ့ ပမမ္္။


methods = [x for x in dir(eval(cls)) if not x.startswith("__")
and callable(eval(cls + "." + x))]
print(methods)
ေအာက္ ပအတိုင္းေတြန္႔အရမာျ စ္ ပတမ္္။
['Random', 'SystemRandom', '_BuiltinMethodType', '_MethodType',
'_Sequence', '_Set', '_acos', '_ceil', '_cos', '_exp', '_log', '_sha512',
'_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn',
'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',
'getrandbits', 'getstate', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate',
'weibullvariate']

Python2(ဘာသာျ ပန္) Han Phyo Oo 165


Non-public attribute ေတြအတြက္ဆိုအရင္ေတာာ့ not ည္ာ့ေ းအရံို ပ ဲ
non_callable_attributes = [x for x in dir(eval(cls)) if not
x.startswith("__")
and not callable(eval(cls + "." + x))]
print(non_callable_attributes)
ဒပဆိုအရင္ေအာက္ ပ result အရ ပမမ္္။
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'SG_MAGICCONST', 'TWOPI',
'_e', '_inst', '_pi', '_random']

ံိုမ python program ေတြအတြက္ေတာာ့ ေအာက္မာေ ာ္ျ ားတဲာ့ ံိုစံေတြ


မလိုေ မဲာ့ျ စ္ပနိုင္ ပေသးတမ္္။
lst = [3,4]
list.__dict__["append"](lst, 42)
lst
ဆိုအရင္ေအာက္ ပအတိုင္းအရအရ ပလမ္ာ့မမ္္။
[3, 4, 42]

A Decorator for Counting Function Calls

Metaclass design ကိုစအရေအာင္ ္။ ၎ subclass ဲက method ေတြကို call


ေတြေအရတြက္ေ းမမ္ာ့ decorator ပနဲန္႔ decorate လို ္ ပမမ္္။
def call_counter(func):
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
helper.__name__= func.__name__
return helper
ံိုမပန္သံိုးသလို ဲသံိုးပနိုင္ ပတမ္္။
@call_counter
def f():
pass
print(f.calls)
for _ in range(10):
f()

print(f.calls)
ေအာက္ ပအတိုင္း ိုတ္ေ း ပလမ္န္႔မမ္္။
0
10

Python2(ဘာသာျ ပန္) Han Phyo Oo 166


Decorator ကိုေပနာက္တစ္မ ဳေးေ ခ ံိုလည္းမတ္ ားသင္ာ့ ပတ.္္။
def f():
pass
f = call_counter(f)
print(f.calls)
for _ in range(10):
f()

print(f.calls)
def f():
pass
f = call_counter(f)
print(f.calls)
for _ in range(10):
f()

print(f.calls)

The "Count Calls" Metaclass

Metaclass ေအရး ိုန္႔လိုအ ္တာေတြစံိုသြားျ ါျ စ္ ပတမ္္။ call_decorator ကို static method


အေပနပနဲာ့ ည္ာ့ ား ပတမ္္။
class FuncCallCounter(type):
""" A Metaclass which decorates all the methods of the
subclass using call_counter as the decorator
"""

@staticmethod
def call_counter(func):
""" Decorator for counting the number of function
or method calls to the function or method func
"""
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
helper.__name__= func.__name__

return helper

def __new__(cls, clsname, superclasses, attributedict):


""" Every method gets decorated with the decorator call_counter,
which will do the actual call counting
"""
for attr in attributedict:
if not callable(attr) and not attr.startswith("__"):
attributedict[attr] = cls.call_counter(attributedict[attr])

return type.__new__(cls, clsname, superclasses, attributedict)

class A(metaclass=FuncCallCounter):

def foo(self):
pass

Python2(ဘာသာျ ပန္) Han Phyo Oo 167


def bar(self):
pass
if __name__ == "__main__":
x = A()
print(x.foo.calls, x.bar.calls)
x.foo()
print(x.foo.calls, x.bar.calls)

This gets us the following:


0 0
1 0

Python2(ဘာသာျ ပန္) Han Phyo Oo 168


Chapter 41
Abstract Classes

Abstract class ေတြကေတာာ့ abstract method မ ား ပ၀င္တာ့ဲ class ေတြျ စ္ ပတမ္္။ abstract
method ေတြကေတာာ့(declare) ေႀကျငာ ားေ မမ္ာ့ implement
မလို ္အရေသးတာေတြျ စ္ ပတမ္္။ abastract class ေတြကို instantiate မလို ္တာျ စ္ပနိုင္သလို
subclass ေတြအေပနပနဲန္႔ abastrct method ေတြကို implement လို ္ေ း န္႔လ
ို ိုအ ္ ပတမ္္။ python
အရဲာ့ abstract class တစ္ ိုအရဲာ့ subclass ကေတာာ့ paret class အရဲာ့ abstract method ေတြကို
implement လို ္စအရာမလို ပဘး္။

Example ႀကည္ာ့အရေအာင္
class AbstractClass:

def do_something(self):
pass

class B(AbstractClass):
pass
a = AbstractClass()
b = B()
ဒပကိုႀကည္ာ့အရင္ abastract class မဟိုတ္တာကိုေတြန္႔ ပမမ္္။ ဘာလိုာ့လဆ
ဲ ိုေတာာ့

 instantiate လည္းလို ္ ားတမ္


 B အရဲာ့ class definition မာ do_something ကို implement လို ္စအရာမလို ပဘး္။

ဒါ example မာ inheritance လို ္တာေလး ဲ ပျ ါး ေတာာ့ abstract class ပနဲာ့ဘာမမဆိုင္ ပဘး္။


python မာကိုမ္ ိုင္အေပနပနဲန္႔ abstract class မ ပ ပဘး္။ဒပေ မမ္ာ့ abstract base classes
ေတြအတြက္ abc လိုန္႔ေ ခတဲာ့ Module ေတာာ့ ပ ပတမ္္။

ေအာက္မာ abc module ကိုသံိုးျ ါးေတာာ့ abtract base class တစ္ ိုတည္ေဆာက္ ား ပတမ္္။
from abc import ABC, abstractmethod

class AbstractClassExample(ABC):

def __init__(self, value):


self.value = value
super().__init__()

@abstractmethod
def do_something(self):
pass
အ ို abstract class ကိုသံိုး ိုန္႔ subclass လို ္မမ္္။ do_something method ကို implement
လို ္ ိုန္႔လေ မမ္ာ့ မလို ္အရေသးတာေတြန္႔မျ စ္ ပတမ္္။ဘာေႀကာင္ာ့လဲဆိုေတာာ့ ၎ method ကို
“abstractmethod” ဆိုတဲာ့ decorator ပနဲန္႔ docorate လို ္ ားလိုန္႔ျ စ္ ပတမ္္။DoAdd42 ကို
instantiate လို ္မအရ ပဘးဆိုတာ့ဲ exception တက္ ပလမ္ာ့မမ္္။

Python2(ဘာသာျ ပန္) Han Phyo Oo 169


class DoAdd42(AbstractClassExample):
pass
x = DoAdd42(4)
အရလာတဲာ့ result က
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-83fb8cead43d> in <module>()
2 pass
3
----> 4 x = DoAdd42(4)
TypeError: Can't instantiate abstract class DoAdd42 with abstract methods
do_something
ေပနာက္တစ္ ိုမာမပန္ေအာင္ျ ပန္ေအရး ပမမ္္။ class ႏွာစ္ ိုေဆာက္ျ ါးေတာာ့ abstract class ကေပန
inherit လို ္ ပမမ္္။
class DoAdd42(AbstractClassExample):
def do_something(self):
return self.value + 42

class DoMul42(AbstractClassExample):

def do_something(self):
return self.value * 42

x = DoAdd42(10)
y = DoMul42(10)
print(x.do_something())
print(y.do_something())
52
420
Abstract class ကေပန derived လို ္ ားတဲာ့ class ကို instantiate လို ္မမ္ဆိုအရင္ abstract
method အားလံိုးကို overridden လို ္ ားမအရ ပမမ္္။

Abstract metchod ေတြကို abstract base class မ


ဲ ာ implement မလို ္ပနိုင္ဘး
င္ ပလမ္ာ့မမ္္။ ဒပေ မမ္ာ့ လို ္လိုန္႔အရ ပတမ္္။ implement လို ္ ားအရင္ေတာင္မ subclass
ေတြ မ
ဲ ာ implementation ေတြကို overridden လို ္ေ းအရ ပမမ္္။ အျ ား ံိုမပန္ inheritance
ေတြမာလို abstract class ေတြကေပန super() ကိုေ ခပနိုင္ ပတမ္္။ ဒပေႀကာင္ာ့ abastract classs

ဲ ာ basic functionality ေတြ ည္ာ့ပနိုင္ျ ါးေတာာ့ ၎ တိုန္႔က ို subclass ေတြ မ
ဲ ာ implement
လို ္ပနိုင္ ပတမ္္။
from abc import ABC, abstractmethod

class AbstractClassExample(ABC):

@abstractmethod
def do_something(self):
print("Some implementation!")

class AnotherSubclass(AbstractClassExample):
def do_something(self):
super().do_something()

Python2(ဘာသာျ ပန္) Han Phyo Oo 170


print("The enrichment from AnotherSubclass")

x = AnotherSubclass()
x.do_something()

Some implementation!
The enrichment from AnotherSubclass

Original website http://python-course.eu/

ဘာသာျ ပန္ဆိုသ ဟပန္ျ ဳေးစါး


အရက္စဲြ 10/4/2017

Python2(ဘာသာျ ပန္) Han Phyo Oo 171

You might also like