Python basics input and output of files for the use of the built in type dictionary operation
- 2020-04-02 13:18:24
- OfStack
Variables and expressions
>>> 1 + 1
2
>>> print 'hello world'
hello world
>>> x = 1
>>> y = 2
>>> x + y
3
Python is a strongly typed language and cannot be automatically parsed into appropriate types based on context. Python is a dynamic language in which the same variable name can represent different forms of values (integer, floating point, list, tuple) at different stages of a program run, and the variable name is just a reference to various data and objects. The variable name in C is the memory fragment used to hold the result.
1. In Python, variables are assigned by reference to objects, not by value.
2. The assignment operator is mainly "=", but incremental assignments, such as x+=1, can also be used. But there are no self - increment or self - decrement operators.
3. In C, an assignment statement can be used as an expression (a value can be returned), but in Python an assignment statement does not return a value, which is illegal as follows:
>>> x=1
>>> y=(x=x+1)
SyntaxError: invalid syntax
With #! The first is called the organization line, which tells your Linux/Unix system which interpreter to run when you execute your program. For example: #! The/usr/bin/python
The ones that start with # are called comment lines.
Conditional statements
Control flow statement: arbitrary conditional expressions can be created by using the or, and, not keyword
If-elf-else :(Python does not have a switch-case statement, which can be used in conjunction with dictionaries to do the same thing)
if something == 1:
doSomething1()
elif something == 2:
doSomething2()
else:
pass # Represents an empty block or an empty body, used pass statements
while-else:
while something:
doSomething1()
else:
doSomething2()
for-else:
for i in range(1, 10, 2): # i Values from 1 to 10 , step length 2
print i
else:
print 'The for loop is over'
Break and continue: used to break and continue the loop.
Input/output of documents
f=open("foo.txt")
line=f.readline()
while line:
print line,
line=f.readline() # Reads a line, including a newline character 'n' , reads to the end of the file and returns an empty string
f.close()
f=open("out.txt","w")
year=1
money=1000
while year<=5:
money=money*(1+0.05)
f.write("%3d %0.2fn" % (year,money)) # print>>f,"%3d %0.2f" % (year,money)
year+=1
f.close()
for line in f.xreadlines():
# Do something with line
4. Built-in type
4.1 None type
None represents an empty object. If a function returns a value that is not displayed, None is returned. The bool value of None is false
4.2 numerical type
Python has four numeric types: integers, long integers, floating point Numbers, and complex Numbers. All numeric types are immutable.
Python does not support the ++, --, ++ I, which means +(+ I)
Operators and expressions: are basically similar to other languages, with the following differences:
X *y: multiplication. 2 times 3 is 6. 'la' times 3 is 'lalala'.
X **y: power operation, returns x to the y.
X /y: x divided by y, 4/3 gives 1. 4.0/3 or 4/3.0 gets 1.333333333333333333.
X //y: divide by PI. Returns the integer part of the quotient. 4 // 3.0 gets to 1.0.
Division // : floor division cuts the decimal part to 0 at any time
- x
Change the sign bit of x
4.3 the string
String: single quotation marks (') and double quotation marks (") are used in the same way to create a single line string. The escape character is (\).
Everything between the three quotes (such as "" or "") is the content of the string.
Natural string: the addition of R (or R) to the string indicates that some strings do not require special processing such as escape characters. For example, print R "Hello\n World" will print "Hello\n World" directly without any line breaks.
a="hello world"
b=a[0,5] # b="hello"
c=a+" I love you" # c="hello world I love you"
s="The value of x is "+ str(x)
Gets the substring: s[I :j], returns the substring between s from I to j (excluding j). If I is omitted, I =0; if j is omitted, j=len of s minus 1
The STR () repr() function or backward-quoted (') can convert other types of data to strings.
Unicode string: adds U (or U) to a string. If a=u'hello', each character with 16 bits to represent "hello" 'world' will be automatically connected to a string "helloworld", "s1" u"s2" will generate u"s1s2"
Strings, Unicode strings, and tuples are immutable sequences.
4.4 lists and tuples (list & A tuple)
Lists and tuples are sequences of arbitrary objects.
len()
append()
insert(index,aMember)
list[index]=aNewMember
Tuple of an element: a=(12,)
Be sure to add an extra comma!
You cannot modify or add elements in a tuple
Lists are mutable sequences that allow you to insert, delete, and replace elements
Operations supported by variable sequence:
s[i]=v
s[i:j]=t # t It has to be a sequence
del s[i]
del s[i:j]
4.5 the dictionary
A dictionary is an associative array (or hash table), a collection of objects indexed by a keyword.
Use {} to create a dictionary
a={
"username":"loo"
"home":"/home/loo"
"uid":500
}
u=a["username"] # access
a["username"]="lu" # Modify the
a["shell"]="/usr/bin/tcsh" # add
del a["shell"] # delete
len(a) # Number of elements
a[("loo",123)]="abc"
Dictionary keys are objects that cannot be modified (such as Numbers and tuples).
Five, the loop
for i in range(1,5):
print "2 to the %d power is %d" % (i,2**i)
The built-in function range([I,]j[,stride]) creates a list of parameters I and stride, which are optional and default to 0 and 1, respectively.
a=range(5,1,-1) # a=[5,4,3,2]
s="hello world"
for c in s: # Print each character
print c
The range() function creates a list in memory, which takes up memory and time when a large list is needed. To overcome this, python provides xrange(). The xrange() function only temporarily computes the supplied value when needed, greatly saving memory.
Six, functions,
Def say(message, times = 1):
The default parameter value of # time is 1
Print a message * times
The return time
Functions with no return value can omit return, which is equivalent to return None
Only those parameters at the end of the parameter list can have default parameter values, that is, you cannot declare the parameter with default value and then declare the parameter without default value when declaring the function parameter. This is because the value assigned to the parameter is based on the position. For example, def func(a, b=5) is valid,
But def func(a=5, b) is invalid.
Global a. Get the global variable a
User-defined functions:
def foo(x,y):
print '%s+%s is %s' % (str(x),str(y),str(x+y))
bar=foo
bar(3,4)
d={}
d['callback']=foo
d['callback'](3,4) # call foo
User-defined functions have the following properties:
F. __module__
The module name of the # function
F. __doc__ or f.f unc_doc
# docstring
F. S/s/s/s/s/s/s/f
F. __dict__ or f.f unc_dict
Function namespaces that support arbitrary function attributes
F.f unc_code
Bytecode generated after compilation
F.f unc_defaults
# contains tuples for all default parameters
F.f unc_globals
Dictionary of the global namespace of the module in which the # function resides
F.f unc_closure
#None or a tuple of cells that contain bindings for the function's free variables.
Seven, classes,
class Stack(object):
def __init__(self):
self.stack=[]
def push(self,object):
self.stack.append(object)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
s=Stack()
s.push("Dave")
s.push(42)
s.push([3,4,5])
print s.length()
print s.pop()
y=s.pop()
print y
del s
Class method definition:
# Static method:
class AClass(object):
@staticmethod
def astatic():
print 'a static method'
# Methods:
class ABase(object):
@classmethod
def aclassmethod(cls):
Isinstance (s,C) is used to test whether s is an instance of C or a subclass of C
Issubclass (A,B) is used to test whether A is A subclass of B
Eight, abnormal
Use try and except statements to catch exceptions:
try:
f=open("file.txt","r")
except IOError,e:
print e
except TypeError,e:
print e
...
try:
do something
except:
print 'An error occurred'
If there is an IOError exception, place the cause of the error in object e, and then run the except code block, if any other type of exception occurs, control will be transferred to the exception of the except code block, if the code block is not found, the program will terminate
Codes are ignored.
Nine, modules,
The import module name
Import module name as alias
From module import object (function)
From module import *
The built-in dir() function lists all the accessible contents of a module
Modules that can be imported:
1. Programs written in python (.py)
2.C or C++ extensions (compiled Shared libraries or DLLS)
3. Package (contains multiple modules)
4. Built-in modules (written in C and linked to the python interpreter)
X. references and copies (reference counting)
Everything in python is an object.
For mutable objects, changing one reference changes all references to that object:
a=[1,2,3,4]
b=a
b[2]=100
print a # a=[1,2,100,4]
To avoid this, you need to create a copy of the mutable object and then operate on that copy.
Two copies of creating mutable objects:
(1) shallow copy: create a new object, but the child elements it contains are still references to the child elements of the original object:
b=[1,2,[3,4]]
a=b[:]
a.append(100)
print b # b=[1,2,[3,4]] b Does not change
a[0]=100
print b # b=[1,2,[3,4]] b Does not change
a[2][0]=100
print b # b=[1,2,[100,4]] b Has been changed
(2) deep copy
import copy
b=[1,2,[3,4]]
a=copy.deepcopy(b)
S/s () is called while the object is being destroyed. Del x simply reduces the reference count of object x and does not call this function.
Type conversion
int(x[,base]) # convert int
long(x[,base])
float(x)
tuple(x)
list(x)
chr(x) # Convert to character
unichr(x) # convert Unicode character
ord(x) # Converts characters to integer values
str(x)
a=[1,2,3,4]
s=repr(a) # s='[1,2,3,4]' Can also be used s='a'
b=eval(s) # b=[1,2,3,4] Convert to a list
eval('3+4')
f=open("foo")
a=repr(f) # a="<open file 'foo',mode 'r' at dc030>"
Xii. Miscellaneous
DocStrings: if the first statement of a module, class, or function body is an unnamed string, it automatically becomes a docstring for that object.
The convention for docstring is a multi-line string that begins with a capital letter and ends with a period. The second line is a blank line, starting with the third line is a detailed description. You can call the document string property of the function (the name belonging to the function) with s/s (note the double underscore). Python treats everything as an object, including this function.
Help () in Python, all it does is grab the s/s of the function and show it to you neatly.
Automated tools can also extract documents from your programs in the same way. The pydoc command, which comes with the Python distribution, USES DocStrings similar to help().
def printMax(x, y):
'''Prints the maximum of two numbers.''' # Here is the docstring
print "DocStrings" # Here is the body command line argument
>>>print printMax.__doc__
Prints the maximum of two numbers.
Id (a) can view the identity of the object (the current implementation is the location of the object in memory)
if type(a) is type(b):
print 'a and b have the same type'
if type(a) is types.ListType
print 'Is a list'
Isinstance (s,C) is used to test whether s is an instance of C or a subclass of C
import types
isinstance(3,types.IntType) # return True
X is equal to y and compare the values of x and y
X is y and x is not y compare whether x and y point to the same object in memory