Tuesday, October 20, 2015

Python in a Minute

Today I will share about how to learn python in a minute, in this post I will use python version 3 only and discuss about python keyword, using python module, python mode, basic syntax, operator, function, python data type and class.

This post is not deep concept, but about basic concept before we start deep learning into python.

Python is easy programming language to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Learning python is not hard because it's "human language" :-) it's mean that python language is more readable, portable, clean, easy to develop and easy to extends.

Ok lets start don't wasting time :D.

Python Mode
Python have two mode which is interpreter mode and scripting mode, we don't need to compile the code because compilation process to byte code will be handled by python interpreter.

You need to install python interpreter before you can start using python, can be downloaded from here python.org. Choose the right one for you distribution OS.

Interpreter mode can be access from terminal emulator in linux and mac or cmd in windows. Most linux distro include python interpreter on each their distribution.

From terminal emulator or cmd you simply type python you will get in to python interpreter depend on your system.
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
With interpreter method you can use it as calculator like sum, div, mod etc
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
>>> 3*3
9
>>> 3**4
81
>>> 6%2
0
>>>

The second one is script method, you can save python code in .py extension and run it with python interpreter. Let start with hello world example :D, open your text editor (notepad, notepad++, sublime text, emacs or nano up to you which one do you choose or you prefer using other text editor) create helloWorld.py then save it. Put this line into helloWorld.py and save it.
a = 'Hello World, this is my first python script'
print(a)
Open terminal in the same folder where helloWorld.py file saved. Then type python helloWorld.py
amrus-MacBook-Pro:Desktop amru$ python helloWorld.py
Hello World, this is my first python script
Ok, now we know about interpreter mode and scripting mode. :-) super easy isn't it?

Python Keyword
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise
Basic Syntax
Python use indentation for block code, I recommended using space rather than tab so it can be portable if change to other text editor. Change from your text editor setting and change tab to 4 spaces or depend on your preference.

Python syntax compare with other language:
C language:
// this is line comment in C
/*
* this is block comment in C
*/
int add(int a, int b){
    return a*b;
PHP language:
// this is line comment in PHP
/*
* this is block comment in PHP
*/
function add($a, $b){
    return $a*$b;
Java language:
// this is line comment in Java
/*
* this is block comment in Java
*/
public int add(int a, int b){
    return a*b;
Python language:
# this is line comment in C
"""
 this is block comment in C
"""
def add(a, b):
    return a*b
Which one is simpler? :D. Yes python is simpler and clean. I don't mean that other language is bad but I just want to show to you python is more simpler than other.

Keep in mind python using indentation for block code, let try other sample create fibonacci.py, put this code and save it.
a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b
then run python fibonacci.py, the execution output should be
1
1
2
3
5
8
Python Operator
Like in other programming language python have some operator, this table will explain operator in python

OperationSyntaxFunction
Additiona + badd(a, b)
Concatenationseq1 + seq2concat(seq1, seq2)
Containment Testobj in seqcontains(seq, obj)
Divisiona / btruediv(a, b)
Divisiona // bfloordiv(a, b)
Bitwise Anda & band_(a, b)
Bitwise Exclusive Ora ^ bxor(a, b)
Bitwise Inversion~ ainvert(a)
Bitwise Ora | bor_(a, b)
Exponentiationa ** bpow(a, b)
Identitya is bis_(a, b)
Identitya is not bis_not(a, b)
Indexed Assignmentobj[k] = vsetitem(obj, k, v)
Indexed Deletiondel obj[k]delitem(obj, k)
Indexingobj[k]getitem(obj, k)
Left Shifta << blshift(a, b)
Moduloa % bmod(a, b)
Multiplicationa * bmul(a, b)
Negation (Arithmetic)- aneg(a)
Negation (Logical)not anot_(a)
Positive+ apos(a)
Right Shifta >> brshift(a, b)
Slice Assignmentseq[i:j] = valuessetitem(seq, slice(i, j), values)
Slice Deletiondel seq[i:j]delitem(seq, slice(i, j))
Slicingseq[i:j]getitem(seq, slice(i, j))
String Formattings % objmod(s, obj)
Subtractiona - bsub(a, b)
Truth Testobjtruth(obj)
Orderinga < blt(a, b)
Orderinga <= ble(a, b)
Equalitya == beq(a, b)
Differencea != bne(a, b)
Orderinga >= bge(a, b)
Orderinga > bgt(a, b)

Checking syntax is easy, we can use python interpreter mode, ex:
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # for a + b
... 1 + 2
3
>>> # for a - b
... 1 - 2
-1
>>> # concat two string
... 'hello' + ' world'
'hello world'
>>> # shift right operation
... 1 >> 2
0
>>> # shift left operation
... 1 << 2
4
>>> # test if object in list
... 'a' in ['a', 'b', 'c']
True
>>>
Python Data Type
Python have powerful built in data type dict, list, set, frozenset and tuple

Python Data Type : Dict
Dict is dictionary data type  must contain pair key and value, initialization of dict using {}
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = {'hello':'world', 1:'oke', 'yes':10, 'dict_in_dict':{}, 'list_in_dict':[1, 2, 3, 4], 'tuple_in_dict':(1, 2, 3, 4)}
>>> a.get('hello')
'world'
>>> a.get('tuple_in_dict')
(1, 2, 3, 4)
>>> a.get('list_in_dict')
[1, 2, 3, 4]
>>> a['hello'] = 'guys'
>>> a.get('hello')
'guys'
>>> a['add new item'] = 'new item added'
>>> a.get('add new item')
'new item added'
>>>
As we can see python dictionary can be mixed value with string, object, int and other python objects.

Python Data Type : List
List in python is like array in C or C++ but more powerful, you can mixed value inside list not only one data type. List python support append, insert, sort and other operation.
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 'oke', 4, 0.3, 'yeah']
>>> a[0]
1
>>> a[2:]
[4, 0.3, 'yeah']
>>> a[2:-1]
[4, 0.3]
>>> a.append('append to last')
>>> a
[1, 'oke', 4, 0.3, 'yeah', 'append to last']
>>> del a[0]
>>> a
['oke', 4, 0.3, 'yeah', 'append to last']
>>> a.pop(2)
0.3
>>> a
['oke', 4, 'yeah', 'append to last']
>>>
list initialization using [], list item can be retrieve using list[index]. Negative index will search from last list item. List[-1] mean get last item, List[0:3] mead get slice of list from index 0 until index 3.

Python Data Type : Tuple
Tuple is like List the difference between both data type is Tuple immutable, the value cannot be change. To initialize tuple use ().
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = (1, 2, 3, 4.3, 'iya')
>>> a[1]
2
>>> a[0:3]
(1, 2, 3)
>>> a[0] = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
See last command a[0] = 2 will raise error, because tuple is immutable

Python Data Type : Set, Frozenset
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = set([1, 2, 3, 4, 5])
>>> b = set((3, 4))
>>> a.union(b)
{1, 2, 3, 4, 5}
>>> a.difference(b)
{1, 2, 5}
>>> b.issubset(a)
True
>>>
As we can see when create set parameter should be iterable object like tuple or list.

Python Loop
Python only have two type of loop which is for and while.

Python Loop : For
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> for i in [1, 2, 3]:
...     print(i)
...
1
2
3
>>> for i in range(3, 10):
...     print(i)
...
3
4
5
6
7
8
9
>>> for i in (1, 2, 3):
...     print(i)
...
1
2
3
>>> d = {'mami':'halo', 'papi':'halo'}
>>> for i in d:
...     print(d.get(i))
...
halo
halo
>>>
Python Loop : While
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> a = 3
>>> while a > 0:
...     a -= 1
...     print(a)
...
2
1
0
Python Import Module
We can import external module or internal python module using import keyword.
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> from datetime import date
>>> date.today()
datetime.date(2015, 4, 15)
>>> datetime.datetime.today()
datetime.datetime(2015, 4, 15, 12, 36, 27, 307647)
>>>
Let create external simple module, create testModule.py then put this code.
def sum_it(a, b):
    print(a+b)
def pow_it(a, b):
    print(a**b)
Open python interpreter in folder contain testModule.py file then do this stuff.
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from testModule import *
>>> sum_it(1, 3)
4
>>> pow_it(2, 5)
32
>>>
 Finally we can call function from other file.

Python Function
To define python function we use def keyword, python function can have default parameter to prevent ordering fault. Better if your function have default parameter :D
Let we do little stuff with python function.
amrus-MacBook-Pro:Desktop amru$ python
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # let we define functin here
... def devide_it(a, b):
...     return a/b # return result a devide by b
...
>>> # let we call the function
... devide_it(10, 3)
3.3333333333333335
>>> # let try create function and use default parameter
... def set_name(first_name='amru', last_name='rosyada'):
...     print(first_name + ' ' + last_name)
...
>>> # let call function without parameter
... set_name()
amru rosyada
>>> # let call function with parameter
... set_name('David', 'Beckham')
David Beckham
>>>
Python Class
As high level language python also support OOP Concept(Object Oriented Programming). If you don't know about OOP you must learn it from other source.
Ok let we take a look to python class,
Python 3.4.3 (default, Mar 10 2015, 14:53:35)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # let we define a class
... class ParenClass():
...     def __init__(self): # this is constructor of the class
...         self.public_paren_var = 'a'
...         self.__private_paren_var = 'private a'
...     def public_method(self):
...         print('public method')
...     def __private_method(self):
...         print('private method')
...
>>> p = ParenClass()
>>> # let retrieve public variable
... p.public_paren_var
'a'
>>> # we cannot retrieve private variable of class
... # private variable or method use prefix '__'
>>> p.__private_paren_var
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'ParenClass' object has no attribute '__private_paren_var'
>>> # let we call public method
... p.public_method()
public method
>>> # we can't call private method
... # private method/function use prefix '__'
... p.private_method()
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AttributeError: 'ParenClass' object has no attribute 'private_method'
>>>
Ok, that is the basic of python and now we can learn more deep about python concept. Let me know if you need some assist contact me for free.

No comments:

Post a Comment