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)With interpreter method you can use it as calculator like sum, div, mod etc
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
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'Open terminal in the same folder where helloWorld.py file saved. Then type python helloWorld.py
print(a)
amrus-MacBook-Pro:Desktop amru$ python helloWorld.pyOk, now we know about interpreter mode and scripting mode. :-) super easy isn't it?
Hello World, this is my first python script
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, raiseBasic 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: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.
# this is line comment in C
"""
this is block comment in C
"""
def add(a, b):
return a*b
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, 1then run python fibonacci.py, the execution output should be
while b < 10:
print(b)
a, b = b, a+b
1Python Operator
1
2
3
5
8
Like in other programming language python have some operator, this table will explain operator in python
Operation | Syntax | Function |
---|---|---|
Addition | a + b | add(a, b) |
Concatenation | seq1 + seq2 | concat(seq1, seq2) |
Containment Test | obj in seq | contains(seq, obj) |
Division | a / b | truediv(a, b) |
Division | a // b | floordiv(a, b) |
Bitwise And | a & b | and_(a, b) |
Bitwise Exclusive Or | a ^ b | xor(a, b) |
Bitwise Inversion | ~ a | invert(a) |
Bitwise Or | a | b | or_(a, b) |
Exponentiation | a ** b | pow(a, b) |
Identity | a is b | is_(a, b) |
Identity | a is not b | is_not(a, b) |
Indexed Assignment | obj[k] = v | setitem(obj, k, v) |
Indexed Deletion | del obj[k] | delitem(obj, k) |
Indexing | obj[k] | getitem(obj, k) |
Left Shift | a << b | lshift(a, b) |
Modulo | a % b | mod(a, b) |
Multiplication | a * b | mul(a, b) |
Negation (Arithmetic) | - a | neg(a) |
Negation (Logical) | not a | not_(a) |
Positive | + a | pos(a) |
Right Shift | a >> b | rshift(a, b) |
Slice Assignment | seq[i:j] = values | setitem(seq, slice(i, j), values) |
Slice Deletion | del seq[i:j] | delitem(seq, slice(i, j)) |
Slicing | seq[i:j] | getitem(seq, slice(i, j)) |
String Formatting | s % obj | mod(s, obj) |
Subtraction | a - b | sub(a, b) |
Truth Test | obj | truth(obj) |
Ordering | a < b | lt(a, b) |
Ordering | a <= b | le(a, b) |
Equality | a == b | eq(a, b) |
Difference | a != b | ne(a, b) |
Ordering | a >= b | ge(a, b) |
Ordering | a > b | gt(a, b) |
Checking syntax is easy, we can use python interpreter mode, ex:
amrus-MacBook-Pro:Desktop amru$ pythonPython Data Type
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 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$ pythonAs we can see python dictionary can be mixed value with string, object, int and other python objects.
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'
>>>
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$ pythonlist 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 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']
>>>
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$ pythonSee last command a[0] = 2 will raise error, because tuple is immutable
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
>>>
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$ pythonAs we can see when create set parameter should be iterable object like tuple or list.
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
>>>
Python Loop
Python only have two type of loop which is for and while.
Python Loop : For
amrus-MacBook-Pro:Desktop amru$ pythonPython Loop : While
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
>>>
amrus-MacBook-Pro:Desktop amru$ pythonPython Import Module
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
We can import external module or internal python module using import keyword.
amrus-MacBook-Pro:Desktop amru$ pythonLet create external simple module, create testModule.py then put this code.
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)
>>>
def sum_it(a, b):Open python interpreter in folder contain testModule.py file then do this stuff.
print(a+b)
def pow_it(a, b):
print(a**b)
amrus-MacBook-Pro:Desktop amru$ pythonFinally we can call function from other file.
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
>>>
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$ pythonPython 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 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
>>>
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)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.
[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'
>>>
No comments:
Post a Comment