What is Python? – Who uses python? – Python's features?



What is Python? – Who uses python? – Python's features?

0 0


present-python

A simple presentation about python

On Github jangm / present-python

Easy, Powerful, Modular Programming Language

Created by Jan Maghuyop / @jangm

Introductions

Jan Maghuyop

  • I go by Jan
  • Government lap dog
  • 2nd year Computer Science student
  • Open Source user and advocate

Prerequisites

  • Basic understanding of programming
  • Any computer will do
  • Windows OS since all of you knows how to use it
  • Google Chrome
  • Text Editor
  • Python 3 installed

What is Python?

We're not talking about the SNAKE!

Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby, Scheme, or Java.

Python is an easy to learn, powerful programming language.

Ideal language for scripting and rapid application development in many areas on most platforms.

English like porgramming language, good for novices and experts.

Scientists love python because it simulates and graphs thier studies.

www.python.org

Who uses python?

And more I and you don't even know . . .

Python's features?

Elegant, clear, readable Syntax

>>> "three " * 3

'three three three '

>>>
						

Is'nt it nice a string and an integer multiplied results to 3 Three's.

Large Standard Library

>>> # list modules in the library

>>> help('modules')

>>>
						

"Batteries included"

docs.python.org/3/library/

Prototype Development

me@computer: alias server = 'python3 -m http.server'

me@computer: server

Serving HTTP on 0.0.0.0 port 8000 ...
						

Web prototypes as well, because deployment is a breeze!

Interactive Mode

>>> 8 ** 2 / 3.43 + 7.34 - .4

25.598892128279882

>>> im_using_python = 'yes'

'yes'

>>> if im_using_python:

		'You are!'

'You are!'

>>>
						

Evaluate and test python code real fast.

Multi - platform

me@linux:~$ python
						
C:\my\path\in\windows> python
						
mac:~ me$ python
						

So python wont stop developing on one platform.

Web Development

me@pc:~$ python ez_setup.py

me@pc:~$ python get-pip.py

me@pc:~$ echo "install webserver"

me@pc:~$ echo "install database"

me@pc:~$ pip install django
						
Web development using python! Web frameworks!

Python plays well with others

  • Jython for Java
  • IronPython for .NET
  • PyObjc for Objective-C
  • Pip for PHP
  • Elmer for C
  • PyPerl for PERL

Write once, run all, pythomatic integration!

OSI Certified

Python is OPEN

Not free as in free beer!

Appetizers

Tired of compile cycle?

me@pc: compiler program.extension -o program.executable
						

C C++ Obj-C C# Java Delphi Visual Basic; Low level?

Tired in routinely typing this?

// source c

#include <library>

datatype function(parameter) {

	// statements

	return 0;

} // compile and execute
						

Brackets, semicolons, datatypes, library inclusion

Too limited to sys admin tasks?

#!/bin/bash

# setting up an application using shell script

package-manager install application

cd /path/to/application/config/

mkdir backup

cd ..

mv -frv *.config backup/

mv -frv /your/config/*.config /path/to/appl/config
						

Powershell, Batch files, shell script

Python is the solution.

Web Teasers

Websites that use python.

Text Editors

Sublime Text 3

Notepad + +

Vim

Nano

Emacs

Coda

Textmate

I D E s

Intergrated Development Environments

Eclipse

Geany

Comodo Edit

PyCharm

Setting up Python

Download Python

www.python.org/getit/

Install Python

me@pc:~/download$ ls

python33-installer.msi

me@pc:~/download$ python33-installer.msi
						
next next next next next ... done ( windows )

Invoke Python

me@pc:~$ cd python/folder

me@pc:~/python/folder/$ python
						
Python 3.3.3 ...

Type "help", "copyright", ...

>>>
						

Nice successfully installed python!

Check python's version

Python 3.3.3 ...

Type "help", "copyright", ...

>>> import sys # include sys module

>>> print(sys.version)

>>> 3.3.3 (v3.3.3:c3896275c0f6 ...
						

We're ready to program python know.

Using the interpreter

>>> im_using_python = 1

>>> if im_using_python:

... 	print("Absolutely!")

'Absolutely!'
						

All right, everything seems to work.

Executing python scripts

me@pc:~$ echo "print('Python rocks!')" >> pyscript.py

me@pc:~$ python pyscript.py

Python rocks!

me@pc:~$
						

Create a file with a py extension.

Execute it by typing "python pyscript.py" without quotes.

Quick Start

Hello World!

#!/usr/bin/python3

print("Hello, World!")
						

Focus on development cycle not the syntax.

Conditionals

a, b = 5, 1

if a < b:

	print("{} < {}".format(a, b))

else:

	print("{} ! {}".format(a, b))
						
# condition expression

print("true" if a < b else "false")
						

Selecting blocks / suites in python using conditions.

While Loop

a, b = 0, 1

while b < 50:

	print(b)

	a, b = a, a + b

print("Finish.")
						

Simple While loop fibonacci sequence.

For Loop

a , b = 0, 1

for a in range(a, 5):

	a, b = a, a + b

	print(b)

						

Simple For loop fibonacci sequence.

Function

def isEven(n):

  if n % 2 == 0:

	print("{} is even.".format(n))


for n in range(1, 10):

  isEven(n)
						

Code reuse using functions.

Generators

def simple_generator_function():

	yield 1

	yield 2


for value in simple_generator_function():

	print(value)


our_generator = simple_generator_function()


next(our_generator)

next(our_generator)
						

A generator is a function that has a yield suite.

Class

class dog:

  def bark(self):

    print('Arf! ' * 3)


  def eat(self):

    print('Looks for a bone!')


retriever = dog()


retriever.bark()

retriever.eat()
						

Code reuse using class to make objects and methods.

Inheritance

class actions:

  def eat(self):

    print('Looks for food!')


class dog(actions):

  def bark(self):

    print('Arf! ' * 3)


doberman = dog()

doberman.eat()
						

Object inheritance in python.

Error Handling

try:

    file = open('file.txt')

except IOError as e:

    print("Something went wrong!: {}".format(e))


print("After error.")
						

Handling errors without execution halt and reporting.

General Syntax

Main Script

#!/usr/bin/python3

def main():

    print("Main function!")


if __name__ == "__main__": main()
						

Define functions first before they are called.

Whitespace

#!/usr/bin/python3

def main():

    print("Main function!")

    print("This is inside main function!")

print("See this line printed first!")

if __name__ == "__main__": main()
						

Indent 4 space is a tradition in python.

# of spaces must be consistent inside a function.

# Comments

def isOdd(n):
  if n % 2 == 1:   # remainder of 1 is odd
    return True
  else:
    return False

def numbers(n = 1):
  while(True):
    if isOdd(n): yield n   # yeild n makes it a generator
      n += 1

for n in numbers():
  if n > 50: break
    print(n)
						

Use comments to make the code more clear.

Assignments

>>> two = 2

>>> n = two

>>> type(n)

>>> type(two)

>>> a, b = 5, 10 # parallel assignments

>>> a, b = b, a # exchange values

>>> tuple = (11 ,22 ,33) # tuples use parenthesis

>>> tuple
						

Assignment operator = assigns values and creates object of type.

Conditionals

a, b = 5, 10

# common else if statements
if a < b:

  print("a is < than b")

elif a > b:

  print("a is > than b")

else:

  print("a is = to b")

# conditional expression / conditional value
answer = "greater than" if a > b else "not less than"

print(answer)
						

Cond~ execution and cond~ expression, 2 types, clear syntax.

Functions

#!/usr/bin/pyton3

def main():

  function(10)

  function(5)


  def function(a):

    for i in range(a):

      print(i, end=" ")

    print()

if __name__ == "__main__": main()
						

Purpose is not usability but modularity.

Objects

#!/usr/bin/python3

class car:

  def __init__(self, type = "Muscle") # constructor
    self.type = type

  def whatType(self):
    return self.type

def main():

  mustang = car()
  print(mustang.whatType())

  lancer = car("Tuner")
  print(lancer.whatType())

if __name__ == "__main__": main()
						

Classes defines objects, a class instance is an object.

Variable Objects & Values

Variable & Objects

>>> x = 100

>>> x

>>> id(x) # id of an object, address

>>> type(x)

						

All variables is a first class object.

Im || Mutable Objects

>>> x = 9

>>> type(x)

>>> id(x)

>>> x = 99

>>> id(x)

>>> x = 9

>>> ide(x)
						

Immutable Objects: Numbers, Strings, Tuples.

Mutable Objects: Lists, Dictionaries, other objects.

Numbers

>>> var = 5 # int

>>> var

>>> type(var)

>>> var = 5.0 # float

>>> 5 / 9

>>> val = round(32 / 3, 2)

>>> 5 // 9

>>> 5 % 9

>>>
						

Float and Int are actually object constructors.

Strings

>>> word = "battery"

>>> print(word)

>>> word = r"show\nme\nthe\nmoney!"

>>> x = 14

>>> word = "word {}".format(x)

>>> print(word)
						
words = '''\
hello mars!
hello world!
hello saturn!
'''

print(words)
						

Strings in python are enclosed in quotes, the same as others.

Lists & Tuples

>>> t = (10, 20 ,30)
>>> print(t, type(t))

>>> l = [11, 22, 33]
>>> print(l, type(l))
>>> l.append(5)
>>> l, insert(1, 99)

>>> s = "string"
>>> print(s, type(s))
>>> print(s[2]) # index 2
>>> print(s[2:4]) # slicing

>>> for i in l:
...   print(i)

>>> for i in s:
...   print(i)
						

Tuple is an immutable object, lists, strings are mutable.

Dictionary

>>> d = {'one': 1, 'two', 2, 'three': 3}

>>> print(d)

>>> for i in d:

...   print(i, d[i])

						
>>> d = dict(

...   one = 1, two = 2, three = 3

... )

>>> d['nine'] = 9

>>> print(d, type(d))
						

Dictionary are mutable objects, lists that are assosciative.

Type & identity of a variable

>>> n = 31 # immutable

>>> id(n)

>>> type(n)

>>> type(42)

>>> id(42)

>>> y = 42

>>> n = y

>>> n == y

>>> n is y

>>> n = dict(x = 42) # type?, id?, compared to y?
						

Everything in python is an object. Id refers to a specific object.

Logical Values

>>> x, y = 1, 2

>>> x == y

>>> x < y

>>> x > y

>>> x = True

>>> id(x)

>>> type(x)
						

True and False are objects of class Bool.

Conditionals

if and else

x, y = 1, 5

if a < b: # replace codition with bool values

  print("this is true")

else:

  print("it is not true")
						

If and else keyword followed by a suite of code and executes it.

Switch ?

switch(variable) {

	case value1: printf("this is value 1"); break;

	case value2: printf("this is value 2"); break;

	case value3: printf("this is value 3"); break;

	default: printf("no hit")
}
						

Python doesn't have switch condition statements, elif does the job.

elif || else if

c = 'two'

if c == 'two':

  print("v is two")

elif v == 'one':

  print("v is one")

elif v == 'three':

	print("v is three")

else:

  print("v is not 1, 2, 3")
						

Several different conditions using elif. One only gets to execute.

Other methods on selection

choices = dict(

  one = 'first',

  two = 'second',

  three = 'third'
)

v = 'three'

print(choices.get(v, 'other'))
						

Get method of the dictionary object. Value to find and the return value.

Conditional Expression

x, y = 1, 2

x = "this is 1" if x < b else 'x is not one'

print(v)
						

One easy line of code, easy to read and understand. If else shorthand.

Loops

While Loop

# simple fibonacci

x, y = 0, 20

while x < 50:

	print(y, end=" ")

	x, y = x, x + y
						

Simplest loop in python. While keyword then the condition follows.

Iterating with For

for i in range(10):

	print(i, end=" ")

for l in "letter": # a string is an object container

	print(l, "", end=" ")

for n in [1, 2, 3, 4, 5]: # list is an object container

	print(n, end=" ")
						

Iteration is a common thing to do in python. Some python objects are iterators.

Enumerating Iterators

s = "string string string"

for i, l in enumerate(s):

	print(i, l)

	if l == 's':

		print('index {} is an i'. format(i))
						

Enumerating the index is a useful thing in python. Enumerate function returns index and the iterator.

Loop Control

str = "string string string"

for l in s:

	if l == 'g': break # halts the loop

	print(l, end="")

for l in s:

	if l == 'g': continue # skips g

	print(l, end="")

for l in s:
	print(l, end="")

else: # when the loop returns false
	print("false")
						

Controls that escape the entire loop, shortcut the loop, else when it returns false.

Operators

Arithmetic Operators

>>> 4 + 3 		# addition

>>> 4 * 9 		# multiplication

>>>  3 - 10 	# subtraction

>>> 7 / 54 		# division
>>> 15 // 2 	# floor division
>>> 15 % 4 		# modulo

>>> divmod(10, 4) # 2 results together

>>> n = 10

>>> n += 1     # compound operators for incrementing
>>> n //= 4  	# for division
						

Basic arithmetic operators in python.

Binary Operators

>>> 5

>>> 0b0101

>>> def bin(n): print('{:08b}'.format(n))

>>> bin(5)

>>> x ,y = 0x55, 0xaa

>>> b(x)

>>> b(y)
						

Created a bin function that converts the parameter to an eight bit binary form.

Binary Operators

>>> b(x | y)

>>> b(x & y)

>>> b(x ^ y) # exclusive or

>>> b(x ^ 0)

>>> b(x ^ 0xff)

>>> b(x << 4) # shift to left

>>> b(x >> 4) # shift to right

>>> b(~ x) # one's compliment of x
						

or, and, shifters and one's compliment in python.

Comparison Operators

>>> 5 > 6

>>> 5 < 6

>>> 5 => 6

>>> 5 <= 6

>>> 5 == 6

>>> 5 == 5

>>> 5 != 6
				

Comparing two values with comparison operators returns a bool value.

Comparison Operators

>>> x, y = 4, 3

>>> id(x)

>>> id(y)

>>> x is not y

>>> x is y

>>> y = 4

>>> id(y)

>>> x is y
						

is and is not comparison operators in python.

Comparison Operators

>>> x, y = [5], [5]

>>> x == y

>>> x is y

>>> id(x)

>>> id(y)
						

Comparison for immutables like lists in python.

Boolean Values

>>> 5 == 5

>>> 7 == 5

>>> type(True) # Boolean Class

>>> True and False

>>> True and True

>>> True or True

>>> True or False

>>> True & True # bitwise operator
						

Boolean Values in python are special True and False objects.

Slice Operator

>>> list = [0, 2, 3, 8, 5]

>>> list[::-1] # reverse the list

>>> list[4]

>>> list[0:3] # slice operator

>>> list[0:5:3] # step, third element

>>> # non inclusive to last number like c arrays

>>> for i in range(0, 10): print(i)

>>> list[0:5] = (5, 5, 5, 5, 5) # change

>>> for i in list[0:5]: print(i)
						

The slice operator is a way to get items from lists, as well as change them.

Regular Expressions

Using regular expressions

  • Regular expressions are a very powerful method of matching patterns in a text.
  • Actually a small language in itself, regexes can be very simple or very complex.
  • Implemented in Python with the "re" module
import re

pattern = re.compiler(r'\d\d\d')

	if re.search(regex, line): print(line)
					

Searching with regular expressions

import re

def main():

    file = open("text.txt")

    for line in file:

        if re.search("(Len|neverm)ore", line):

            print(line, end="")

if __name__ == "__main__": main()
						

Searching for string patterns using re module in python.

Replacing using regular expressions

import re

def main():

    file = open("text.txt")

    for line in file:

        print(re.sub("(Len|neverm)ore", "@ @ @", line),
            end="")

if __name__ == "__main__": main()
						

Using sub method in re module to replace characters from matched patterns.

Reusing regular expressions

import re

def main():

    file = open("text.txt")

    pattern = re.compile("(Len|neverm)ore")

    for line in file:

        if re.search(pattern, line):

            print(pattern.sub("@ @ @", line), end="")

if __name__ == "__main__": main()
						

Use compile method from re module to reuse regular expression.

Exceptions

Using exceptions

  • Exceptions are the key method of handling errors in Python
  • "try" something, then catch an exception with "except"
file = open("filename")

except IOError as e:

    print(e)

else:

    for l in file: print(l)
							
You may raise your own exceptions with "raise"

Handling Exceptions

def main():

    try:

        file = open('file.txt')

    except IOError as e:

        print("Error: {}".format(e))

    print("After error.")

if __name__ == "__main__": main()
						

Using try to catch the error except when error occurs.

Raising Exceptions

def main():

    if filename.endswith(".txt"):

        file = (filename)

        return file.readlines()

    else: raise ValueError("filename must end with .txt")

if __name__ == "__main__": main()
						

We use the raise keyword and give the exception.

Functions

Defining functions

def main():

    function()

    function_pass(9, 8, 1)

# can be assigned, none value

def function(para, paras, params):

    print("This is a function.", para, paras, params)

def function_pass():

    pass # a function that does nothing

if __name__ == "__main__": main()
						

Functions in python are the primary unit of reusable code.

Using lists of arguments

def main():

    function(9, 8, 1, 9, 8, 7, 6, 5, 4)

def show_arguments(a, ar, arg, *args):

    print("arguments: ", a, ar, arg, args)

    for a in args:

        print(a, end = " ")

if __name__ == "__main__": main()
						

Using *args to add infinite arguments to your function. It's a tuple so its immutable.

Using named function arguments

def main():

    kwargs(9, 8, 1, 2, 22, 222, one = 1, two = 2)

# kwargs stands for key word arguments

def kwargs(a, ar, arg, *args, **kwargs):

    print("arguments: ", a, ar, arg, args,

        kwargs['one'], kwargs['two'])

    for a in args:

	    print(a, end = " ")

if __name__ == "__main__": main()
						

Passing named arguments in python using kwargs in the function definition.

Returning values from functions

def main():

    print(function1())

    for n in function2():

        print(n, end=" ")

def function1():

	return "Returned this string!"

def function2():

	return range(25)

if __name__ == "__main__": main()
						

Return any object from a function using a return statement.

Sequence using generator function

def main():

    for n in inclusive_range(0, 25, 1):

        print(n, end = " ")

def inclusive_range(start, stop, step):

    n = start

    while n <= stop:

        yield n

        n += step

if __name__ == "__main__": main()
						

A generator function returns an iterator object.

Classes

Classes and Objects

  • Classes are how you create your own objects
  • A class is a blueprint for an object
class Duck:

    def quack(self):

        print("quack!")

    def walk(self):

        print("*walks like a duck*")
						

A class Duck which has 2 methods quack() and walk().

Classes and Objects

donald = Duck() # class instantation

# results to donald object

donald.quack()

donald.walk()
						

An object is an instance of a class.

Using methods

class Duck:

    def __init__(self, value): # constructor method

        self.val = value

    def quack(self):

        print("Quaack!",  self.val)

    def walk(self):

        print("Walks like a duck.", self.val)
						

Constructors are for initializing data first before methods can be called.

Using object data

class Duck:
    def __init__(self, **kwargs):
	    self.vars = kwargs

    def set_var(self, key, val):
        self.vars[key] = val

    def get_var(self, key):
        return self.vars.get(key, None)

def main():
    donald = Duck(feet = 2)
    donald.set_var("color", "blue")
    print(donald.get_var("feet"))
    print(donald.get_var("color"))
if __name__ == "__main__": main()
						

This is just one of different ways to use object data in objects.

Understanding inheritance

class Animal:

    def talk(self):

        print("I have something to say!")

class Duck(Animal):

	pass

def main():

	donald = Duck()

	donald.talk()
						

In OOP Inheritance is inheriting properties from a class to another class.

Applying polymorphism to classes

class Dog:

    def bark(self):

        print("Arf! Arf! Arf!")

class Duck:

    def bark(self):

        print("Duck cannot bark!")

def main():

	donald = Duck()

	donald.bark()
						

Polymorphism is using another object in another class.

Using Decorators


						

String Methods

Strings as objects

>>> "This is a string!"

>>> s = "This is a string!"

>>> s

>>> s.upper()

>>> "This is {}".format(32)
						

Strings are objects.

Common String methods

>>> s = "This is a string!"

>>> s.capitalize()

>>> s.upper()

>>> s.lower()

>>> s.swapcase

>>> s

>>> s.find("s")

>>> id(s)
						

Common String methods

>>> s = ss

>>> id(ss)

>>> "	strip!	".strip()

>>> "strings".strip("gs")

>>> s.alnum()

>>> s.alpha()

>>> "12345".isdigit()
						

Formatting Strings

>>> a, b = 1, 2

>>> print(a, b)

>>> "this is {}, that is {}.".format(a, b)

>>> "this is {}, that is {}."

>>> id(s)

>>> new = s.format(a, b)

>>> id(new)
						

Using format to add variables on strings.

Splitting and Joining strings

>>> s = "string strings stringss"

>>> s.split()

>>> s.split("i")

>>> words = s.split()

>>> for word in words: print(w)

>>> new = ":".join(words)

>>> new
						

Using split and join string methods.

Standard string methods

>>> s = "this is a string"

>>> new = s.center(80)

>>> len(new)

>>> s.lower()

>>> s.center(80)
						

Check and read python string methods in documentation.

Containers

Tuples and Lists

>>> t = 1, 2, 3, 4, 5 # tuple

>>> t

>>> t[0]

>>> len(t)

>>> min(t)

>>> max(t)

>>> tt = tuple(range(20))

>>> l = list(range(20))

>>> tt[3] = 19 # tuples are immutable!
						

Tuples are fast to implement and don't allow you to change stuff.

Sequences with methods

>>> t = tuple(range(20))
>>> type(t)
>>> 10 in t
>>> 50 in t
>>> 50 not in t
>>> for n in t: print(n)
>>> t[3]
>>> len(t)
>>> l = list(range(10)) # methods are the same with lists
>>> l.append(10)
>>> l.extend(range(10))
>>> l.insert(0, 100)
>>> l.pop(0) # l.pop()
						

Methods on tuples and lists, lists can pop, insert and extend.

Dictionaries

>>> d = {"one": 1, "two": 2, "three": 3 }

>>> type(d)

>>> "one" in d

>>> "four" in d

>>> for key in d: print(key)

>>> for key, value in d.items()L print(key, value)

>>> d["three"]

>>> d.get("three") # exception for items not found
						

Indexes are data, which means faster searching, manageable.

Character data with bytes arrays


						

File IO

Opening files

file = open("lines.txt", "r") # r, r+, w, a, rt, rb

for line in file:

    print(line, end="")
						

Opening files and its, arguments read, write, append, read and write, text, binary modes.