Alt p. alt n previous statements,next statement
array
Movies=["abc",12 ]. Can contain mixed type
Print(movies[1])
Movies.insert(1,sth)
movies.append()
for each_movie in movies
print(each_movie)
while condition:
string either double or single quotes
list of list
isinstance(movies,list)-----true
default recurtion limit 1000
BIF built in function
""" triple quotes add comments
a module is a file ends with.py
Pypi
build a module,distribute it, install
def functionname(arg1,arg2=0) default value make second arg optional
if booleanvariable:
All python code associated with name space
_main_
import nester
import os
os.getcwd() //get current directory
os.chdir(). // change directory
data=open('file.txt')
data.seek(0) // go to beginning of the file
for each line in data
print(each line,end=' ')
(v1,v2)=each line.split(":")
(v1,v2)=each line.split(":",1). //split at most to 2 partseach line.find(":")""" -1 find nothing
except IOError as err:
data.close()
try:
except:""" when no argument ,all exceptions
Or except ValueError:""" concrete exception
except IOError as err
print(str(err)) """ str() can be used to access the stringed representation of any data object that supports the conversion.
finally:
Two type of list, square brackets, you can change, regular brackets, immutable
in for loop, pass like continue in java
if os.path.exist('stretch.txt')
line.strip()""" trimming
out = open("out.txt", "w")
print("egghkk", file=out)
try:
data=open('file.txt')except IOError as err:
finally:
if 'data' in locals() """ locals() returns a collection of variables within the current scope
data.close()
try :
with open('file.txt') as data, open('file1.txt') as data2
When you use with,you don't need worry about closing any open files
---
Pickle
Python ships with standard library called picked, which can save and load almost any Python data object. Once you pickle your data to a file, it is persistent and ready to be read into another program at some later data/time. You can store your pickled data on disk, put it in a database, or transfer it over a network.
when you are ready, reversing this process unpickles your persistent pickled data and recreates your data in its original form within Python's memory.
import pickle
...
try:
with open('mydata.pickle', 'wb') as mysavedata:
pickle.dump([1,2,'three'], mysavedata) """ use dump to save
...
with open('mydata.pickle','rb') as myrestoredata:
a_list = pickle.load(myrestoredata) """ restore the data
except pickle.PickleError as perr:
in-place sorting sort()
Copied sorting sorted()
tt.txt looks like this: 2:34,4-45,2.35
def sanitize(time_string):
if '-' in time_string:
splitter = '-'
if ':' in time time_string:
splitter=':'
else:
return (time_string)
(mins,secs) = time_string.split(splitter)
return(mins+'.'+secs)
with open('tt.txt') as file:
data = file.readline()
list = data.strip().split(',')
cleanlist = []
for item in list
cleanlist.append(sanitize(item))
( this whole thing can be written as cleanlist = [sanitize(item) for item in list] )
print(sorted(cleanlist))
list.pop(1) """ get one element from a list
If you try to add a data item to a set
that already contains the data item, Python simply ignores it.
distances = set()
distances = {10.6, 11, 8, 10.6, "two", 7}
Any duplicates in the supplied list of data values are ignored like 10.6
print(sorted(set([sanitize(t) for t in james]))[0:3])
create dictionary
dictionary1 = {}
dictionary1['Name'] = 'John Cleese'
dictionary1['Occupations'] = ['actor', 'comedian', 'writer', 'film producer']
dictionary2 = dict()
dictionary2= {'Name': 'Michael Palin', 'Occupations': ['comedian', 'actor', 'writer', 'tv']}
---------
define a class
class Athlete:
def __init__(self):
# The code to initialize an "Athlete" object.
create instance
a = Athlete()
When Python processes this line of code, it turns the factory function call into
the following call, which identifies the class, the method (which is automatically
set to __init__()), and the object instance being operated on:
( Athlete.__init__(a) is called)
, not only does the __init__() method require self as its first
argument, but so does every other method defined within your class.
what you write,
d = Athlete("Holy Grail")
d.how_big()
Python executes
Athlete.__init__(d, “Holy Grail”)
Athlete.how_big(d)
, if you save your AthleteList class to a file
called athletelist.py, you can import the into your code
using this line of code:
from athletelist import AthleteList
---------
Python comes with its very own web server,
included in the http.server library module
Here are the five lines of code needed to build a web server in Python.
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8080
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
data_files = glob.glob("data/*.txt")
form_data = cgi.FieldStorage()
Grab all of the form data and put it in a dictionary
athlete_name = form_data['which_athlete'].value """ which_athlete is a radio button
check which radio button is selected
When your CGI script raises an exception, Python arranges for the error
message to display on STDERR (standard error). The CGI mechanism is
programmed to ignore this output because all it wants is the CGI script’s
standard output.
Python’s standard library comes with a CGI tracking
module (called cgitb) that, when enabled, arranges for detailed error
messages to appear in your web browser.
import cgitb
cgitb.enable()
@property
def top3(self):
return(sorted(set([self.sanitize(t) for t in self]))[0:3])
The use of the @property decorator allows the top3() method to appear
like an attribute to users of the class. So, instead of calling the top3()
method like this:
print(yate.u_list(athletes[athlete_name].top3()))
Treat the top3() method as if it was another class attribute, and call it like
this:
print(yate.u_list(athletes[athlete_name].top3))
The standard library string module
includes a class called Template,
which supports simple string substitutions.
The standard library cgi module
provides support for writing CGI scripts.
ƒ The standard library glob module is
great for working with lists of filenames.
The standard library cgitb module,
when enabled, lets you see CGI coding
errors within your browser.
ƒ Use cgitb.enable() to switch on
CGI tracking in your CGI code.
ƒ Use cgi.FieldStorage() to
access data sent to a web server as part
of a web request; the data arrives as a
Python dictionary.
--
Google provides a cross-platform
Android emulator that lets you develop for the phone as needed
http://developer.android.com/sdk/index.html
No comments:
Post a Comment