Agenda
- What is Python
- Hello World
- Data Types
- Web Frameworks
What is Python ?!
Python
What is python
Python is :
- a widely used - general-purpose, - high-level programming language.
Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C.The language provides constructs intended to enable clear programs on both a small and large scale.
wikipedia.com
Who use python ?!
Python is almost every where
- Web Applications
- Games
- Graphics
- Software Development
- etc ...
Examples
At Google, python is one of the 3 "official languages" alongside with C++ and Java. Official here means that Googlers are allowed to deploy these languages to production services. (Internally Google people use many technologies including PHP, C#, Ruby and Perl). Python is well suited to the engineering process at Google.
Examples
Examples
Examples
www.cia.gov
Let's Python !!!
Install python
Linux :
$> apt-get install python2.x.x
Windows :
http://www.python.org/download/
IDE
Hello World App
From the ide
$> python
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello World"
Hello World
>>> a = "Hello "
>>> b = "World"
>>> print a + b
Hello World
>>> exit()
$>
Save our code
$> vi hello.py
OR
$> gedit hello.py
a = "Hello "
b = "World."
print a + b
$> python hello.py
Hello World.
Let's Welcome the Interns
hello_interns.py
$> vi hello_interns.py
names = ['Morcos','Negm','Raghda']
h = "Hello "
for x in names:
print h + x + "!!"
$> python hello_interns.py
Hello Morcos!! Hello Negm!! Hello Raghda!!
interns_projects.py
intern_list = [
{'name': 'Negm','project':'Raspberry PI'},
{'name': 'Raghda','project':'News Crawler'},
{'name': 'Morcos','project':'Amazonian'}
]
for x in intern_list:
print "Intern : "+ x['name'] + " is Working on "+ x['project']
$> python interns_projects.py
Intern : Negm is Working on Raspberry PI Intern : Raghda is Working on News Crawler Intern : Morcos is Working on Amazonian
Better Syntax
Before
print "Intern : "+ x['name'] + " is Working on "+ x['project']
After
print "Intent : %s is working on %s" %(x['name'],x['project'])
Let's Complicate it
#!/usr/bin/python
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print 'Hello there', sys.argv[1]
# Command line args are in sys.argv[1], sys.argv[2] ...
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
$> python hello.py Ahmed
Hello there Ahmed
Data types
Strings
some basics
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there
pi = 3.14
##text = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes
raw = r'this\t\n and that'
print raw ## this\t\n and that
multi = """It was the best of times.
It was the worst of times."""
common methods
-
s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
-
s.strip() -- returns a string with whitespace removed from the start and end
-
s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
-
s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
-
s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
-
s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
-
s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arg) splits on all whitespaces
- s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
String slices
s = 'Hello'
s[1:4] # 'ell'
s[1:] # 'ello'
s[:] # 'Hello'
s[1:100] # 'ello'
s[1] # 'H'
s[-1] # 'o' -- last char (1st from the end)
s[-4] # 'e' -- 4th from the end
s[:-3] # 'He' -- going up to but not including the last 3 chars.
s[-3:] # 'llo' -- starting with the 3rd char from the end
Lists
Basics
colors = ['red', 'blue', 'green']
print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3
b = colors ## Does not copy the list
More Methods
list = ['larry', 'curly', 'moe']
list.append('shemp') ## append elem at end
list.insert(0, 'xxx') ## insert elem at index 0
list.extend(['yyy', 'zzz']) ## add list of elems at end
print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly') ## 2
list.remove('curly') ## search and remove that element
list.pop(1) ## removes and returns 'larry'
print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']
More ...
list = ['larry', 'curly', 'moe']
if 'curly' in list:
print 'yay' # 'yay'
## Access every 3rd element in a list
i = 0
while i < len(a):
print a[i]
i = i + 3
## print the numbers from 0 through 99
for i in range(100):
print i
Sorting
a = [5, 1, 4, 3]
print sorted(a) ## [1, 3, 4, 5]
print a ## [5, 1, 4, 3]
strs = ['aa', 'BB', 'zz', 'CC']
print sorted(strs) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
print sorted(strs, reverse=True) ## ['zz', 'aa', 'CC', 'BB']
strs = ['ccc', 'aaaa', 'd', 'bb']
print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa']
## a list of strings we want to sort by the last letter.
strs = ['xc', 'zb', 'yd' ,'wa']
## Write a function that takes a string, and returns last letter.
##(takes in 1 value, returns 1 value).
def MyFn(s):
return s[-1]
## Now pass key=MyFn to sorted() to sort by the last letter:
print sorted(strs, key=MyFn) ## ['wa', 'zb', 'xc', 'yd']
Dict
Basics
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
print dict['a'] ## Simple lookup, returns 'alpha'
dict['a'] = 6 ## Put new key/value into dict
'a' in dict ## True
## print dict['z'] ## Throws KeyError
if 'z' in dict: print dict['z'] ## Avoid KeyError
print dict.get('z') ## None (instead of KeyError)
print dict.items()
## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
for k, v in dict.items(): print k, '>', v
## a > alpha o > omega g > gamma
dict FORMATTING
The % operator works conveniently to substitute values from a dict into a string by name:
hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
s = 'I want %(count)d copies of %(word)s' % hash
# %d for int, %s for string
# 'I want 42 copies of garfield'
Delete
var = 6
del var # var no more!
list = ['a', 'b', 'c', 'd']
del list[0] ## Delete first element
del list[-2:] ## Delete last two elements
print list ## ['b']
dict = {'a':1, 'b':2, 'c':3}
del dict['b'] ## Delete 'b' entry
print dict ## {'a':1, 'c':3}
Functions & Classes
define a function
# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
"""Returns the string s repeated 3 times.
If exclaim is true, add exclamation marks.
"""
result = s + s + s
if exclaim:
result = result + ' !!!'
return result
print repeat('Yay ', False) ## Yay Yay Yay
print repeat('Woo Hoo', True) ## Woo HooWoo HooWoo Hoo !!!
Classes
Define a class
class rect:
width = 8
height = 4
x = rect()
print x.width # 8
class rect:
width = 8 height = 4
def area(self): return self.width * self.height
x = rect()
print x.area() # 32
__init__() method
class rect:
def __init__(self,w,h): self.width = w self.height = h
def area(self): return self.width * self.height
x = rect(2,2)
print x.area() # 4
inheritance
class Espacian(object):
def __init__(self,name,tools): self.name = name self.tools = tools
def listTools(self): tools_string = 'The Employee : '+self.name +' uses : ' for tool in self.tools: tools_string += tool + ', ' return tools_string
class Developer(Espacian):
def __init__(self,name,tools,languages): Espacian.__init__(self,name,tools) self.languages = languages
class Designer(Espacian):
def __init__(self,name,tools,portfolio): Espacian.__init__(self,name,tools) self.portfolio = portfolio
cont.
m = Developer('Mohammed',['github','redmine'],['ruby','python']) print m.listTools()
# The Employee : Mohammed uses : github, redmine,
Quizz !!
x = 3
def new(): x = 2 print x
print x # ??
new() # ??
print x # ??
files & Database
files - The basics
types :
-
Text
- Binary
The Syntax is :
file_object = open(filename, mode)
Mode :
'r' # Read-only mode
'w' # Write-only mode [erase any existing file with the same name]
'a' # Append mode
'r+' # Read-Write mode ( File should exist )
'w+' # Read-Write mode ( File will be over-written if exist )
write files
file = open("newfile.txt", "w")
file.write("hello world in the new file\n")
file.write("and another line\n")
file.close()
$> cat newfile.txt
hello world in the new file
and another line
read files
file = open('newfile.txt', 'r') print file.read()
#hello world in the new file #and another line
print file.read(5) # hello
print file.readline() # hello world in the new file
print file.readline() # and another line
print file.readlines()
# ['hello world in the new file\n', 'and another line\n']
for line in file: print line,
#hello world in the new file #and another line
Error Handling
f = open ("not_file.non","r")
# IOError: [Errno 2] No such file or directory: 'not_file.non'
try:
f = open ("not_file.non","r") print f.read()
except IOError: print "File Doesn't exist"
mysql database
$> sudo apt-get install python-mysqldb
database methods
.connect()
.cursor()
.execute()
.close()
database query
import MySQLdb
conn=MySQLdb.connect(host, user, passwd, DBname)
cur=conn.cursor()
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
for row in cur.fetchall() : print row[0]
.fetchall()
.fetchone()
Web frameworks
web app 2
Web app 2
import webapp2
from google.appengine.ext import db
from datetime import datetime, timedelta
class Station(db.Model):
station_id = db.StringProperty(required=True)
status = db.StringProperty()
date = db.StringProperty()
class AddComment(webapp2.RequestHandler): def post(self): station_id = self.request.get('station_id') comment = self.request.get('comment') status = self.request.get('status') date = str(datetime.now() + timedelta(hours=2))
station = Station(station_id=station_id,status=status,date=date) key = station.put()
app = webapp2.WSGIApplication([
('/comment', AddComment),
], debug=True)
Thank you !!
Python
By mohheader
Python
- 225