--- name: Title class: middle, center # Kerala Police CyberDome Python Workshop .footnote[By [Rejah Rehim](https://rejahrehim.com)] --- name: Title class: middle, center # Python? --- class: middle, center # Free and open-source You can freely use and distribute Python, even for commercial use. You can even make changes to the Python's source code. Python has a large community constantly improving it in each iteration. --- class: middle, center # Portability You can move Python programs from one platform to another, and run it without any changes. It runs seamlessly on almost all platforms including Windows, Mac OS X and Linux. --- class: middle, center # Extensible and Embeddable Suppose an application requires high performance. You can easily combine pieces of C/C++ or other languages with Python code. This will give your application high performance as well as scripting capabilities which other languages may not provide out of the box. --- class: middle, center # A high-level, interpreted language Unlike C/C++, you don't have to worry about tasks like memory management, garbage collection and so on. Likewise, when you run Python code, it automatically converts your code to the language your computer understands. You don't need to worry about any lower-level operations. ??? # Interpreted - What does it mean for a language to be "interpreted?" - Trick question - "interpreted" and "compiled" refer to implementations, not languages - The most common Python implementation (CPython) is a mix of both: - Compiles source code to byte code (.pyc files) - Then interprets the byte code directly, executing as it goes - No need to compile to machine language - Essentially, source code can be run directly --- class: middle, center # Large standard libraries to solve common tasks Python has a number of standard libraries which makes life of a programmer much easier since you don't have to write all the code yourself. ??? # For example: - Need to connect MySQL database on a Web server? - You can use MySQLdb library using import MySQLdb . - Standard libraries in Python are well tested and used by hundreds of people. - So you can be sure that it won't break your application. --- class: middle, center # Object-oriented Everything in Python is an object. Object oriented programming (OOP) helps you solve a complex problem intuitively. With OOP, you are able to divide these complex problems into smaller sets by creating objects. --- # Simple Elegant Syntax It's easier to understand and write Python code. Why? The syntax feels natural. Take this source code for an example: ``` a = input() b = input() sum = a + b print(sum) ``` Even if you have never programmed before, you can easily guess that this program adds two numbers and prints it. --- class: middle, center # Not overly strict You don't need to define the type of a variable in Python. Also, it's not necessary to add semicolon at the end of the statement. Python enforces you to follow good practices (like proper indentation). These small things can make learning much easier for beginners. ??? # Dynamically typed --- # Important Things!! To represent a statement in Python, newline (enter) is used. The use of semicolon at the end of the statement is optional (unlike languages like C/C++, JavaScript, PHP). In fact, it's recommended to omit semicolon at the end of the statement in Python. Instead of curly braces { }, indentations are used to represent a block. ``` python im_a_parent: im_a_child: im_a_grand_child im_another_child: im_another_grand_child ``` ??? - Configure the IDE - Do not use tab, Set tab to 4 spaces --- name: Zen of Python class: middle, center # The Zen of Python -- - Beautiful is better than ugly - Explicit is better than implicit - Simple is better than complex - Complex is better than complicated - Readability Counts --- # Python2 vs. Python3 - January 1994: Version 1.0 released -- - October 2000: Version 2.0 released -- - December 2008: Version 3.0 released -- - June 2009: Version 3.1 released -- - July 2010: Version 2.7 released with backports -- - Dec 2016: current Python versions are 2.7.11 and 3.5.1 --- # Python3 is backwards incompatible! -- - print and exec become functions -- - Massive usage of generators instead of lists -- - All text (str) is Unicode and encoded text is binary data (bytes) -- - Other minor changes in std lib --- name: Environment class: middle, center #Setting up environment -- Mac OS X or Linux installation might have a Python Interpreter pre-installed with it. To find out if you have one, open terminal and type `python`. --- name: REPL class: middle, center # The REPL (Read Evaluate Print Loop) -- ``` python $ python Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>print('hello world!') hello world! ``` ??? # Why should I use it?? - Quick! - Helps test Python behaviour - But... doesn't play nice with multiline code (i.e. classes, functions) -- To exit use ctrl+d on *nix, and ctrl+z on windows. --- class: middle, center # Setting up in Linux -- - Debian / Ubuntu Linux / Kali Linux users ``` sudo apt-get install python2 ``` - Red Hat / RHEL / CentOS Linux user ``` sudo yum install python ``` --- class: middle, center # Setting up in Windows .left[ - Go to Python's [download page](https://www.python.org/downloads/windows/) - Download Python installer which is compatible with your system. - 32-bit installers which will work on both cases - but 64-bit will only work on 64-bit systems ] --- name: Calculator class: middle, center # Python as a calculator ??? ``` python >>> 10 + 10 20 >>> 50 * 2 100 >>> 10 + 20 * 3 70 >>> (10 + 20) * 3 90 ``` - What does ** do? - What does % do? - What does import this do? --- name: Files class: middle, center # .py files -- - Python source files - (No compilation needed) ``` python $ python /tmp/example.py hello world! ``` --- name: IDE class: middle, center # IDE (Integrated development environment) --- class: middle, center # PyCharm # Geany ??? - PyCharm's [website](https://www.jetbrains.com/pycharm/) - You can set up both python 2 and python 3 side by side. - A commercial and a community versions are available for download. - To install Geany - Debian / Ubuntu Linux / Kali Linux users ``` sudo apt-get install geany geany-common ``` --- # PyCharm Keyboard Short Cuts .left[ - `Alt+Enter` - Quick fixes, including auto import - `Ctrl+Shift+A` - Find any command or setting - `Ctrl+Alt+L` - Reformat code - `Ctrl+Shift+F10` - Run the current file - `Shift+F10` - Run again the last file - `Ctrl+Space` - Method/variable autocomplete ] --- class: middle, center # Style guide -- .left[ - Python puts a strong emphasis on readability - Hence [PEP 8](https://www.python.org/dev/peps/pep-0008/) was created. - It holds style guidelines for how Python code should look ] ??? - Use 4 spaces per indentation level. - Spaces are the preferred indentation method. - Python 3 disallows mixing the use of tabs and spaces for indentation. - Limit all lines to a maximum of 79 characters. - Surround top-level function and class definitions with two blank lines. - Imports should usually be on separate lines --- .middle[.center[ # Installing third party libraries ]] - With Setuptools & Pip ``` $ easy_install pip ``` - With distribution Package Managers - On Debian, Ubuntu and Kali Linux: ``` sudo apt-get install python-pip ``` - On Fedora: ``` sudo yum install python-pip ``` ### Now you could run pip from command line ``` $ pip install packagename ``` --- class: middle, center # Working with Virtual Environments ??? Helps to separate dependencies required for different projects, by working inside virtual enviromnet it also helps to keep our global site-packages directory clean --- class: middle, center # virtualenv `virtualenv` is a python module ``` sudo pip install virtualenv ``` --- .middle[.center[ # Create a new virtual environment ]] -- - Create a folder and Enter to that folder ``` $ virtualenv name-of-virtual-environment ``` -- - With specific Python interpreter ``` $ virtualenv -p /usr/bin/python2.7 name-of-virtual-environment ``` -- - Activate before start using ``` $ source name-of-virtual-environment/bin/activate ``` -- - Exit ``` $ deactivate ``` --- # virtualenvwrapper ??? Better way to use virtualenv. It also organize all virtual environments in one place -- ### Linux ``` $ pip install virtualenvwrapper ``` - In shell startup file `.bashrc` or `.profile` ``` export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/virtualspace source /usr/local/bin/virtualenvwrapper.sh ``` `virtualspace` as the location for virtual environments -- ### windows ``` pip install virtualenvwrapper-win ``` --- # Working with virtualwrapper - Create a virtual environment ``` $ mkvirtualenv your-project-name ``` - Activate this environment ``` $ workon your-project-name ``` - Combined the above commands ``` $ mkproject your-project-name ``` - Exit ``` $ deactivate ``` - Delete ``` $ rmvirtualenv venv ``` --- class: middle, center # Variables In Python, a variable points to data stored in a memory location. This memory location can store different values such as integer, real numbers, Booleans, strings or more complex data structures like dictionaries or lists. ``` >> num = 9 >>> type(num) >>> num >>> num + 2 >>> num + ”pwn ``` ??? ``` >>> num = 9 >>> type(num)
>>> num 9 >>> num + 2 11 >>> num + ”pwn” Traceback (most recent call last): File ”
”, line 1, in
TypeError: unsupported operand type(s) for +: ’int’ and ’str’ ``` --- class: middle, center # Strings A string is a collection of characters we can save a string to a variable ``` >>> string = ”length” >>> type(string) >>> len(string) ``` ??? >>> string = ”length” >>> type(string)
>>> len(string) 6 --- # Slicing Strings ``` >>> string = ”hello, world” >>> print string[0] >>> print string[11] >>> print string[12] >>> print string[-1] ``` ``` >>> line = ’Jul 4 2009, 20’ ``` ??? ``` >>> string = ”hello, world” >>> print string[0] h >>> print string[11] d >>> print string[12] Traceback (most recent call last): File ”
”, line 1, in
IndexError: string index out of range >>> print string[-1] d ``` -- - How do you get the month? ??? ``` >>> line[0:4] ’Jul ’ ``` -- - How do you get the day? ??? ``` >>> line[4] ’4’ ``` -- - How do you get the year? ??? ``` >>> line[6:10] ’2009’ ``` -- - How do you get the value? ??? ``` >>> line[-2:] ’20’ ``` -- Finally, that strings are immutable meaning that you can’t modify one you’ve created ``` >>> string = ”test” >>> string[2] = ’p’ ``` ??? ``` >>> string = ”test” >>> string[2] = ’p’ Traceback (most recent call last): File ”
”, line 1, in
TypeError: ’str’ object does not support item assignment ``` --- # String Methods -- ``` string.count('x') ``` - returns the number of occurrences of 'x' in the string -- ``` string.find('x') ``` - returns the position of character 'x' in the string -- ``` string.lower() ``` - converts the string into lowercase --- # String Methods ``` string.upper() ``` - converts the string into uppercase -- ``` string.replace('a', 'b') ``` - replaces all a with b in the string -- ``` string.strip() ``` - Strip out whitespace at beginning and end of strings --- # Lists Lists let you store groups of values for later use. Helps to store more than one "variable" inside it and provide a better method for sorting arrays of objects in python. ``` >>> list = [1,2,3,4] >>> list >>> list[0] >>> list[3] >>> list[4] >>> list[-1] ``` ??? ``` >>> list = [1,2,3,4] >>> list [1, 2, 3, 4] >>> list[0] 1 >>> list[3] 4 >>> list[4] Traceback (most recent call last): File ”
”, line 1, in
IndexError: list index out of range >>> list[-1] 4 ``` -- ``` list = [1,2,3,4,5,6,7,8] for x in list: print (x) ``` --- # List Methods ``` list.append(value) ``` - appends an element at the end of list -- ``` list.count('x') ``` - get the the number of 'x' in list -- ``` list.index('x') ``` - returns the index of 'x' in list -- ``` list.insert('y','x') ``` - inserts 'x' at location 'y' --- # List Methods ``` list.pop() ``` - returns last element and also remove it from list -- ``` list.remove('x') ``` - removes first 'x' from list -- ``` list.reverse() ``` - reverses the elements in the list -- ``` list.sort() ``` - sorts the list alphabetically in ascending order, or numerical in ascending order --- # Dictionaries A python dictionary is a storage method for key:value pairs. In Python dictionaries are enclosed in curly braces, {}. ``` >>> a = {'apples': 1, 'mango': 2, 'orange': 3} >>> b = {'orange': 4, 'lemons': 2, 'grapes ': 4} >>> a.update(b) >>> Print a ``` ??? ``` {'mango': 2, 'apples': 1, 'lemons': 2, 'grapes ': 4, 'orange': 4} ``` -- To delete elements from a dictionary we can use del method ``` >>> del a['mango'] >>> print a ``` ??? {'apples': 1, 'lemons': 2, 'grapes ': 4, 'orange': 4} --- # Handling Exceptions Try to divide a number with zero in your Python interpreter ``` >>> 10/0 ``` ??? ``` Traceback (most recent call last): File "
", line 1, in
ZeroDivisionError: integer division or modulo by zero ``` -- So we can rewrite this script with try-except blocks ``` try: answer = 10/0 except ZeroDivisionError, e: answer = e print answer ``` -- ### One more thing: fail early, fail loudly --- # For Loops ``` >>> for i in range(0,10): print i ``` ``` >>> teams = [”Red Sox”, ”Yankees”, ”Rays”, ”Blue Jays”] >>> for team in teams: print team ``` --- # Logical Tests We use If Statements to check values ``` >>> nays = [”Coburn”, ”Specter”, ”DeMint”] >>> if ”Coburn” in nays: print ”No!” ``` ``` >>> if len(nays) > 50: print ”Bill does not pass” >>> if len(nays) <= 50: print ”Bill passes!” ``` --- # Functions ``` def functionname( parameters ): "function_docstring" function_suite return [expression] ``` -- ### Calling a Function ``` functionname(parameters) ``` -- ### To Do - Create a fuction to print your address -- --- # Class ``` class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary ``` --- # Module ``` import support ``` ``` support.print_func("Zara") ``` -- ## To Do - Convert the above function to a module --- # Package A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages. -- `Phone/Isdn.py` file having function Isdn() `Phone/G3.py` file having function G3() Now, create one more file `__init__.py` in directory ``` Phone/__init__.py ``` --- # Introduction to Version Controll ## Git --- # What is Git? - Open-source code management tool - Created by Linus Torvalds when he was building the Linux kernel. - Git is DSCS (Distributed Source Control System) - Git allows you to work on your code with the peace of mind that everything you do is reversible. ??? This means that even if you're using a centralized work-flow, every user essentially has a full backup of the main server. Each of these copies could be pushed up to replace the main server in the event of a crash or corruption. In effect, there is no single point of failure with Git unless there is only a single copy of the repository. --- # Staging Area ??? Unlike the other systems, Git has something called the "staging area" or "index". This is an intermediate area where commits can be formatted and reviewed before completing the commit. It's possible to quickly stage some of your files and commit them without committing all of the other modified files in your working directory --- # Install Git ``` $ sudo apt-get install git-core ``` --- # Setup Name and Email Run the following commands so that git knows - your name - your email ``` $ git config --global user.name "Your Name" $ git config --global user.email "you@digitalbrandgroup.com" ``` --- # Setup Line Ending Preferences - Unix/Mac users: ``` $ git config --global core.autocrlf input $ git config --global core.safecrlf true ``` - Windows users: ``` $ git config --global core.autocrlf true $ git config --global core.safecrlf true ``` --- # SetUp Editor & Diff tool ``` $ git config --global core.editor emacs ``` - Another useful option you may want to configure is the default diff tool to use to resolve merge conflicts. ``` $ git config --global merge.tool vimdiff ``` --- # CREATE/CLONE A PROJECT Create the Repository ``` $ git init Initialized empty Git repository in /Users/rejah/working/directory/.git/ ``` - Clone a Repository ``` $ git clone git@letzgame.com:testing.git Cloning into 'testing'... remote: Counting objects: 21, done. remote: Compressing objects: 100% (17/17), done. remote: Total 21 (delta 2), reused 0 (delta 0) Receiving objects: 100% (21/21), 2.50 MiB, done. Resolving deltas: 100% (2/2), done ``` --- # Add the program to the repository ``` $ git add hello.php $ git commit -m "First Commit" [master (root-commit) 9416416] First Commit 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 hello.php ```