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.
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.
$> apt-get install python2.x.x
http://www.python.org/download/
$> 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()
$>
$> vi hello.py
OR
$> gedit hello.py
a = "Hello "
b = "World."
print a + b
$> python hello.py
Hello World.
$> 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!!
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
print "Intern : "+ x['name'] + " is Working on "+ x['project']
print "Intent : %s is working on %s" %(x['name'],x['project'])
#!/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
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."""
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
colors = ['red', 'blue', 'green']
print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3
b = colors ## Does not copy the list
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']
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
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']
## 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
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'
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}
# 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 !!!
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
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
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
m = Developer('Mohammed',['github','redmine'],['ruby','python']) print m.listTools()
# The Employee : Mohammed uses : github, redmine,
x = 3
def new(): x = 2 print x
print x # ??
new() # ??
print x # ??
file_object = open(filename, 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 )
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
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
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"
$> sudo apt-get install python-mysqldb
.connect()
.cursor()
.execute()
.close()
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()
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)