programming under linux in python

Download Programming Under Linux In Python

If you can't read please download the document

Upload: marwan-osman

Post on 16-Apr-2017

9.812 views

Category:

Technology


4 download

TRANSCRIPT

Programming Under Linux In Python

Marwan [email protected]

- needs Software Freedom Day@Alexandria University

Agenda

What is Python ???

Why Python ???

Syntax Walkthroughs

Linux and Python

What is Python ???

What is Python ???

Why Python ???

Syntax Walkthroughs

Linux and Python

History

Created by Guido von Rossum in 1990 (BDFL)

named after Monty Python's Flying Circus

http://www.python.org/~guido/

Blog http://neopythonic.blogspot.com/

Now works for Google

What is Python ???

general-purpose high-level programming language, often used as a scripting language.

interpreted, interactive, object-oriented.

incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes, automatic memory management.

remarkable power with very clear syntax.

has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++.

usable as an extension language for applications that need a programmable interface.

What is Python ???

supports multiple programming paradigms (primarily object oriented, imperative, and functional)

portable: runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, OS/2, FreeBSD Solaris, OS/2, Amiga,AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and even PocketPC !

What is Python ???

Developed and supported by a large team of volunteers - Python Software Foundation

Major implementations: CPython, Jython, Iron Python, PyPy CPython - implemented in C, the primary implementation

Jython - implemented for the JVM

Pypy - implemented in Python

IronPython - implemented in C#, allows python to use the .NET libraries

Why Python ???

What is Python ???

Why Python ???

Syntax Walkthroughs

Linux and Python

Why Python ???

Readability, maintainability, very clear readable syntax

Fast development and all just works the first time...

very high level dynamic data types

Dynamic typing and automatic memory management

Paradigm of your choice

Free and open sourceImplemented under an open source license. Freely usable and distributable, even for commercial use.

Simplicity , Great first language

Availability (cross-platform)

Interactivity (interpreted language)

Why Python ???

GUI support GUIs typically developed with Tk

Strong introspection capabilities

Intuitive object orientation

Natural expression of procedural code

Full modularity, supporting hierarchical packages

Exceptionbased error handling

The ability to be embedded within applications as a scripting interface

Scalable can play nicely with other languages

Batteries Included

The Python standard library is very extensive regular expressions, codecs

date and time, collections, theads and mutexs

OS and shell level functions (mv, rm, ls)

Support for SQLite and Berkley databases

zlib, gzip, bz2, tarfile, csv, xml, md5, sha

logging, subprocess, email, json

httplib, imaplib, nntplib, smtplib

and much, much more ...

Python Libraries

Biopython - Bioinformatics

SciPy - Linear algebra, signal processing

NumPy - Fast compact multidimensional arrays

PyGame - Game Development

Visual Python - real-time 3D output

Django - High-level python Web framework

and much more ...

E.g. Projects with Python

Websites: Google, YouTube, Yahoo Groups & Maps, CIA.govAppengine:http://code.google.com/appengine/

Google: Python has been an important part of Google since the beginning., Peter Norvig.

Python application servers and Python scripting to create the web UI for BigTable (their database project)

Systems: NASA, LALN, CERN, RackspaceNasa Nebula http://nebula.nasa.gov/about

Games: Civilization 4, Quark (Quake Army Knife)

Mobile phones: Nokia S60 (Symbian), PythonCE

P2P: BitTorrent

Python Problems

Scripting-like language and compiled and runtime - hence slower than C/C+ + and slightly slower than Java

Memory economy hard to achieve (high level data-structures)

Relies on a locking mechanism called the Global Interpreter Lock (GIL) in multi-threading

Turn Arounds

Write extension libraries in C or C++

Use multiple processes instead of multiple threads

Use a different language

Use Stackless Python

Syntax Walkthroughs

What is Python ???

Why Python ???

Syntax Walkthroughs

Linux and Python

Hello World

Python 2.6

Python 3.0

print(Hello World)

print Hello World

Basics

Numbers:Integers: 4 , 8 , 15, 16 , 23 , 42 ,108

Floating point: 4.23 , 42.8E-4

Complex Numbers: -5+4j , 2.3 4.6j

StringsImmutable , Unicode by default

Single quotes, double quotes ,triple quotes (multiline)

'Hello Word' , Hello World , '''Hello World''' , Hello World

Concatenation : 'What\'s ' 'your name?'automatically converted in to "What's your name?

Strings: format()

>>>age = 25 >>>name = 'Swaroop' >>>print('{0} is {1} years old'.format(name, age)) Swaroop is 25 years old>>> '{0:.3}'.format(1/3) '0.333' >>> '{0:_^11}'.format('hello') '___hello___' >>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')'Swaroop wrote A Byte of Python'

Variables

Naming identifiers: The first character be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore ('_').

The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores ('_') or digits (0-9).

Identifier names are case-sensitive. For example, myname and myName are not the same.

Valid identifier e.g.: i, __my_name, name_23, a1b2_c3,

resumTM _count.invalid identifier e.g.: 2things, my-name

Indentation

Python uses whitespace to determine blocks of code

def greet(person): if person == Tim: print (Hello Master) else: print (Hello {name}.format(name=person))

Control Flow

if guess == number: #do somethingelif guess < number: #do something elseelse: #do something else

while True: #do something #break when done breakelse: #do something when the loop ends

for i in range(1, 5): print(i)else: print('The for loop is over')#1,2,3,4

for i in range(1, 5,2): print(i)else: print('The for loop is over')#1,3

Data Structures

ListMutable data type, array-like

[1, 2, 4, Hello, False]

list.sort() ,list.append() ,len(list), list[i]

TupleImmutable data type, faster than lists

(1, 2, 3, Hello, False)

Dictionary{42: The answer, key: value}

Set([list, of, values])

Functions

Order is important unless using the name

Default arguments are supported

def sayHello(): print('Hello World!')

def foo(name, age, address) :pass

foo('Tim', address='Home', age=36)

def greet(name='World')

Functions

Variable length args acceptable as a list or dict

def total(initial=5, *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return countprint(total(10, 1, 2, 3, vegetables=50, fruits=100))

Functions

def printMax(x, y): '''Prints the maximum of two numbers. The two values must be integers.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: return x else: return yprintMax(3, 5)

Modules

Any python file is considered a module

Modules can be imported or run by themselves

if __name__ == '__main__': print('This program is being run by itself')else: print('I am being imported from another module')

Modules

#!/usr/bin/python# Filename: mymodule_demo.py

import mymodule

mymodule.sayhi()print ('Version', mymodule.__version__)

#!/usr/bin/python# Filename: mymodule.py

def sayhi(): print('Hi, this is mymodule speaking.')

__version__ = '0.1'# End of mymodule.py

OOP

class MyClass: """This is a docstring.""" name = "Eric" def say(self): return ('My name is {0}'.format(name))instance = MyClass() print instance.say()

OOP

class Person: def __init__(self, name): self.name = name def __del__(self): print('deleting this person',self.name) def sayHi(self): print('Hello, my name is', self.name) p = Person('Swaroop') p.sayHi() del p

OOP

All class members (including the data members) are public and all the methods are virtual in Python.

Double undersocre prefix turns them privatee.g.: __privatevar,

Inheritance

MetaClasses

class SchoolMember(metaclass=ABCMeta):

@abstractmethod def tell(self): pass

class Teacher(SchoolMember):

Input & Output

#inputsomething = input('Enter text: ')

#outputprint(something)

Files

myString = This is a test stringf = open('test.txt', 'w') # open for 'w'riting f.write(myString) # write text to file f.close() # close the file f = open('test.txt') #read modewhile True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print(line, end='') f.close() # close the file

Pickle

import pickle shoplistfile = 'shoplist.data' shoplist = ['apple', 'mango', 'carrot'] f = open(shoplistfile, 'wb') pickle.dump(shoplist, f) # dump the object to a file f.close() del shoplist # destroy the shoplist variable f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # load the object from the file print(storedlist)

More

Exception Handling

Standard Library

Passing Tuples

Logging Module

Linux and Python

What is Python ???

Why Python ???

Syntax Walkthroughs

Linux and Python

Linux and Python

Installed by default in most distros

Various editorsText editors, IDLE , plugins for eclipse & Netbeans

Embeddable in many applications as scripting interfaceRhythmbox, Blender, OpenOffice, BitTorrent, ...

Linux and Python

Talk is cheap. Show me the code. Linus Torvalds

Demos

Backup Script

Simple XML Processing

Simple Spell Checker

Python Virus

Open Office Script

Rhythmbox python console

Basic Twitter client

Open Office macro script for python syntax Highlighing Demo

#!usr/bin/python#Send a new Tweet

from getpass import getpassimport tweepy

username = raw_input('Twitter username: ')password = getpass('Twitter password: ')basic_auth = tweepy.BasicAuthHandler(username, password)api = tweepy.API(basic_auth)api.update_status("Hello Twitter !!! I'm a Pythoneer")

More Resources

http://wiki.python.org/moin/BeginnersGuide

http://www.python.org/doc/faq/

Learn Python in 10 minutes: http://www.poromenos.org/tutorials/python

Byte of Python: http://www.swaroopch.com/notes/Python

Dive Into Python: http://diveintopython.org/

Google

Write most useful links for beginners starting

Any Questions ???

Write something more interactive

Thank You

Muokkaa otsikon tekstimuotoa napsauttamalla

Muokkaa jsennyksen tekstimuotoa napsauttamallaToinen jsennystasoKolmas jsennystasoNeljs jsennystasoViides jsennystasoKuudes jsennystasoSeitsems jsennystasoKahdeksas jsennystasoYhdekss jsennystaso

Muokkaa otsikon tekstimuotoa napsauttamalla

Muokkaa jsennyksen tekstimuotoa napsauttamallaToinen jsennystasoKolmas jsennystasoNeljs jsennystasoViides jsennystasoKuudes jsennystasoSeitsems jsennystasoKahdeksas jsennystasoYhdekss jsennystaso