Xu Songliang's Python Special Teaching-Foundation-Introduction and Foundation Source Code

Keywords: Programming Python Unix Windows Lambda

Copyright Statement: This article is the original work of blogger Xu Songliang. It can not be reproduced without permission. Thank you for your support. QQ:5387603

Catalog

First, source code

I. Introduction to python

Second, the construction of development environment

Third, original basic source code

Fourth, the results of original basic source code operation

I. Introduction to python

  • Dynamic Object-Oriented Scripting Language
  • Running directly without compiling
  • With the rise of micropython, python has a tendency to develop embedded products, which may one day replace the embedded status of some C languages.
  • Large data processing, hackers, testing and other commonly used languages have gained momentum recently, and even some countries have incorporated them into primary school curricula.
  • Easy to learn, easy to maintain, strong scalability, free, free, free, important things to say three times.

Second, the construction of development environment

  • Official website
  • Version problem
    • There is a distinction between 2.X and 3.X versions. The grammar is different and incompatible.
    • As for 2.X and 3.X which is better, online debate is strong, but I personally suggest that if beginners directly learn 3.X, after all, the new version is the trend. My code is based on 3.X.
  • Editor selection
    • In fact, the official editor can be used for daily operation, so it is not necessary to waste too much time on it when you are just getting started.
    • A free editor is recommended, which is Visual Studio Code, a popular Microsoft free product in recent years. As for how to build an integrated development environment, this document will be improved in the future.

Third, original basic source code

  • Because there are detailed annotations in the source code, there is no further explanation.

 

#!/usr/bin/python

'''
//This is a multi-line comment.
'''

"""
//This is also a multi-line comment.
"""
StrLine = "--------------------"
LineNum = 1
#--------------------------------------------------
import keyword          # Keyword
import random           # random number
#import turtle           # Little Turtle Drawing
import sys              # system
import time             # time
import pickle           # Pickle "pickle" preservation module
#import tkinter          # tkinter drawing
#import zipfile          # Compression and Decompression
import threading        # Multithreading
import os               # system
#import nmap             # nmap tools
import platform         # Platform information
# thread
#from threading import Thread
# xsl
#--------------------------------------------------
print (StrLine,LineNum,"-Export the information to the specified file and print it on the console")
class Logger(object):
    def __init__(self, fileN="xsl_basic_1_base_log.txt"):
        self.terminal = sys.stdout
        self.log = open(fileN, "w")
 
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
        # Update content to disk, otherwise only to cache
        self.log.flush()
 
    def flush(self):
        pass
sys.stdout = Logger("xsl_basic_1_base_log.txt")
#--------------------------------------------------
print (StrLine,LineNum,"-To be solved")
LineNum+=1
print ("* logging Class applications")
print ("* Silent Access to Administrator Privileges")
print ("* Remove files completely, including deleting yourself")
print ("* Encryption and Decryption of File Content")
print ("* Transfer files to the server")
#--------------------------------------------------
print (StrLine,LineNum,"-Scattered knowledge points")
LineNum+=1
print ("* Similar C In language sprintf: Direct use%that will do,For example: str1='%02x %02d' % (i,j)")
#--------------------------------------------------
print (StrLine,LineNum,"-View System Information")
LineNum+=1
print (sys.version)
print ("platform.architecture():   " , platform.architecture())
print ("platform.system():         " , platform.system())
print ("platform.version():        " , platform.version())
print ("platform.machine():        " , platform.machine())
print ("platform.python_version(): " , platform.python_version())
#--------------------------------------------------

#--------------------------------------------------
# Basic operations: data type types (numbers, strings, lists, tuples, dictionaries)
"""
//number
                int		Signed integer
                long		Long shaping
                float	        float
                complex	        complex
//String string
                1,Single line can be used with single quotation marks'-',You can also use double quotation marks."-".
                2,Many lines need to be used.'''-'''
                3,Support for escape characters'\',
                4,Supports multiplication, often used to print a certain number(But you can't use subtraction and division.)
//List list
                1,Amount to C Arrays in language, but python There are several ways to add, delete, and so on
                2,.append()       -->     Append
                3,del             -->     Delete the entire list or specified elements
                4,Supports multiplication, often used to print a certain number(But you can't use subtraction and division.)
                
//Yuan Zu (Read Only) tuple
                1,Lists using parentheses,The difference from lists is that"read-only"
//Dictionary map
                1,The difference from lists is that each element has a key value
"""
print (StrLine,LineNum,"-data type")
LineNum+=1
counter = 100  # Integer variables
print ("Print integer variables:",counter)
print ("Be similar to C Medium printf : counter = %d" % (counter))
del counter
miles = 1000.0 # float
print ("Print floating-point variables:",miles)
del miles
name = "XSL"   # Character string    
print ("Print string multiplication:",name)
name = name*10
print ("Print strings    :",name)
del name
listname = ['item1', 'item2', 'item3'];
print ("Print list      :",listname)
listname.append('append')
print ("Print list(Append): ",listname)
del listname[2]
print ("Print list(Append): ",listname)
del listname
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 );
print ("Print the ancestor      : ",tuple)
del tuple
dict = {}
dict['one']="this is one"
dict[2]="This is two"
tinydict={'name':'xsl','code':824}
print ("Print Dictionary(member): ",dict['one'],dict[2])
print ("Print Dictionary(Whole): ",tinydict)
print ("Print Dictionary(Key value): ",tinydict.keys())
print ("Print Dictionary(value  ): ",tinydict.values())
del tinydict
#--------------------------------------------------
print (StrLine,LineNum,"-Built in function")
LineNum+=1
print ("-----------Number Type shift")
print ("int(x[,base])         take x Convert to an integer")
print ("long(x[,base])        take x Convert to a long integer")
print ("float(x)              take x Convert to a floating point number")
print ("complex(real[,imag])  Create a plural")
print ("str(x)                Will object x Convert to String")
print ("repr(x)               Will object x Convert to expression string")
print ("eval(str)             Used to calculate validity in strings Python Expressions and returns an object")
print ("tuple(s)              Sequence of sequences s Convert to a tuple")
print ("list(s)               Sequence of sequences s Convert to a list")
print ("chr(x)                Converting an integer to a character")
print ("unichr(x)             Converting an integer to an integer Unicode character")
print ("ord(x)                Converting a character to its integer value")
print ("hex(x)                Converting an integer to a hexadecimal string")
print ("oct(x)                Converting an integer to an octal string")
print ("bool(x)               Convert a parameter to Boolean type 0/empty-False Non 0/Not empty-True")
print ("-----------Mathematical function")
print ("abs(x)                Returns the absolute value of a number, such as abs(-10) Return to 10")
print ("ceil(x)               Returns the upper integer of a number, such as math.ceil(4.1) Return to 5")
print ("cmp(x, y)             If x < y Return -1, If x == y Return to 0, If x > y Return to 1")
print ("exp(x)                Return e Of x pow(ex),as math.exp(1) Return to 2.718281828459045")
print ("fabs(x)               Returns the absolute value of a number, such as math.fabs(-10) Return to 10.0")
print ("floor(x)              Returns the rounded integer of a number, such as math.floor(4.9)Return to 4")
print ("log(x)                as math.log(math.e)Return to 1.0,math.log(100,10)Return to 2.0")
print ("log10(x)              Returns base 10 x Logarithms, such as math.log10(100)Return to 2.0")
print ("max(x1, x2,...)       Returns the maximum value of a given parameter, which can be a sequence")
print ("min(x1, x2,...)       Returns the minimum value of a given parameter, which can be a sequence")
print ("modf(x)               Return x The integer part and the decimal part, the numerical symbols of the two parts and x Similarly, the integer part is expressed in floating-point form")
print ("pow(x, y)             x**y Value after operation")
print ("round(x [,n])         Returns floating-point numbers x A rounded value, as given. n Value represents the number of digits rounded to the decimal point")
print ("sqrt(x)               Return number x The square root, the number can be negative, and the return type is real, such as math.sqrt(4)Return to 2+0j")
print ("-----------Random Number Function")
print ("random.choice(seq)    Random selection of an element from a sequence, such as random.choice(range(10)),Random selection of an integer from 0 to 9.")
print ("random.randrange ([start,] stop [,step])Gets a random number from a set incremented by a specified cardinality within a specified range, with a default cardinality of 1")
print ("random.random()       Random generation of the next real number, it is in[0,1)Within limits")
print ("random.randint(min,max)  Random Generation of the Next Integer in a Certain Range")
print ("random.seed([x])      Changing the Seeds of Random Number Generators seed. If you don't understand the principle, you don't have to set it up specifically. seed,Python Will help you choose seed")
print ("random.shuffle(lst)   Random sorting of all elements of a sequence")
print ("random.uniform(x, y)  Random generation of the next real number, it is in[x,y]Within limits")
print ("-----------trigonometric function")
print ("acos(x)               Return x Anticosine radian value")
print ("asin(x)               Return x Inverse Sinusoidal Radius Value")
print ("atan(x)               Return x Anti-tangent radian value")
print ("atan2(y, x)           Returns the given X and Y Arbitrary tangent of coordinate values")
print ("cos(x)                Return x Cosine value of radian")
print ("hypot(x, y)           Return to Euclidean norm sqrt(x*x + y*y)")
print ("sin(x)                Returned x Sinusoidal value of radian")
print ("tan(x)                Return x Tangent value of radian")
print ("degrees(x)            degrees,as degrees(math.pi/2) , Return to 90.0")
print ("radians(x)            radians")
print ("-----------Mathematical Constants")
print ("pi                    Circumference, generally as followsπTo represent")
print ("e                     Natural constants")
print ("-----------All keywords")
print (keyword.kwlist)
print ("-----------Other")
print ("len(s)                Returns the length of an object")
print ("set(s)                Converting to Variable Sets")
print ("dict(d)               Create a dictionary. d Must be a sequence (key,value)Tuple.")
print ("frozenset(s)          Converting to an immutable set")
#--------------------------------------------------
print (StrLine,LineNum,"-operator")
LineNum+=1
print ("Arithmetic operators:          + ,- ,* ,/ ,% ,**,//")
print ("The comparison operator:          ==,!=,<>,> ,< ,>=,<=")
print ("Assignment operator:          = ,+=,-=,*=,/=,%=,**=,//=")
print ("Bit Operator:          & ,| ,^ ,- ,<< ,>>")
print ("Logical operators:          and ,or ,not")
print ("Membership operators:          in ,not in")
print ("Identity operator:          is ,is not")
print ("String operators:        +,*,[],[:],in,not in,r/R,%")
print ("String formatting operator:  %c,%s,%d,%u,%o,%x,%X,%f,%e,%E,%g,%G,%p")
print ("  Formatting Operator Assistance:  *,-,+,<sp>,#,0,%,(var),m.n")
print ("String complex references:      '''")
#--------------------------------------------------
print (StrLine,LineNum,"-condition")
LineNum+=1
print ("Conditional statement:            if-elif-else")
num = 5
if num==1:
	print ("Examples of conditions: if",num)
elif num==2:
	print ("Examples of conditions: elif",num)
else:
	print ("Examples of conditions: else")
del num
#--------------------------------------------------
print (StrLine,LineNum,"-loop")
LineNum+=1	
print ("Loop statement:            while,for")
print ("Loop control statements:        break,continue,pass")
for x in range(0,2):
        print('for Example hello %s' % x)
del x
#--------------------------------------------------
print (StrLine,LineNum,"-Printing")
LineNum+=1
# Array assignment
for x in range(0,10):
	print (x,end = '') 
print ('')
del x
#--------------------------------------------------	
print (StrLine,LineNum,"-time")
LineNum+=1

ticks = time.time()
print ("Unix Timestamp:       ",ticks)
localtime = time.localtime(ticks)
print (".localtime   :        ",localtime)
print (".asctime     :        ",time.asctime())
print ("delayed(second):             time.sleep(x)")
del ticks
#--------------------------------------------------	
print (StrLine,LineNum,"-file")
LineNum+=1
text1="1234567890"
fo = open("xsl_basic_1_base.txt","w+")
fo.write(text1)
print ("Establish xsl_basic_1_base.txt And write the string:",text1)
position=fo.tell();
print ("Current file location",position)
position = fo.seek(5,0)
str1=fo.read(5)
print ("Positioning to 5,Read 5 bytes of data:",str1)
fo.close();
#--------------------------------------------------
'''
print (StrLine,LineNum,"-File read and write---routine")
LineNum+=1
i=0
fi = open("xsl_basic_1_base_ascii.bin","rb")
fo = open("xsl_basic_1_base_asciiOut.bin","w+")
try:
	while True:
		i1=fi.read(1)
		i2=fi.read(1)

		print ("i1=",i1)
		print ("i2=",i2)
		
		if not i1:
			break;
		#i1=i1+1
		#i2=i2+1
		fo.write(str(i)+"\r\n")
finally:
	fi.close()
	fo.close()
del i
del fi
del fo
'''
#--------------------------------------------------	
print (StrLine,LineNum,"-File read and write---pickle Save module")
LineNum+=1
save_data={'name':'pickle_name','pickle_age':36}
save_file=open('pickle_test.dat','wb')
pickle.dump(save_data,save_file)
save_file.close()
print(".dump:",save_data)
del save_data
del save_file
loat_file=open('pickle_test.dat','rb')
loat_data=pickle.load(loat_file)
loat_file.close()
print(".loat:",loat_data)
del loat_data
del loat_file
#--------------------------------------------------	
print (StrLine,LineNum,"-Function usage")
LineNum+=1
def xslfun(str):
	print (str)
	return
xslfun("Calling a function!")
LineNum+=1
print (StrLine,'end')
#--------------------------------------------------	
print (StrLine,LineNum,"-Class usage")
LineNum+=1
#--------------------------------------------------	
print (StrLine,LineNum,"-Use of Modules(Modules are functions./class/Combination of variables)")
LineNum+=1
print ("turtle       :        Little Turtle Drawing")
print ("copy.copy    :        shallow copy,Changing the original object affects the new object")
print ("copy.deepcopy:        deep copy,Changing the original object does not affect the new object")
print ("keyword      :        Keyword")
#--------------------------------------------------	
print (StrLine,LineNum,"-Input and output")
LineNum+=1
# input
key=input("\n Please enter the key and press Enter to exit.(input)\n")
print (key)
print("\n Please enter the key and press Enter to exit.(sys.stdin.readline(max))")
key=sys.stdin.readline(5)
print (key)
del key
# output
print ("Output 0-9 (sys.stdout.write)")
sys.stdout.write("0123456789\n")
#----------------------------------------------------------------------------------------------------------------------------------------------------------------
print (StrLine)
print ("xsl Error-free exit of control system")
os._exit(0)
#--------------------------------------------------
sys.exit()
#--------------------------------------------------


Fourth, the results of original basic source code operation

=============== RESTART: E:\python\xsltest\xsl_basic_1_base.py ===============
-------------------- 1 -Export the information to the specified file and print it on the console
-------------------- 1 -To be solved
* logging Application of Class
* Silent Access to Administrator Privileges
* Remove files completely, including deleting yourself
* Encryption and Decryption of File Content
* Transfer files to the server
-------------------- 2 -Scattered knowledge points
* Similar C In Language sprintf: Direct use%that will do,For example: str1='%02x %02d' % (i,j)
-------------------- 3 -View System Information
3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
platform.architecture():    ('64bit', 'WindowsPE')
platform.system():          Windows
platform.version():         10.0.17134
platform.machine():         AMD64
platform.python_version():  3.7.0
-------------------- 4 -data type
//Print integer variables: 100
//Similar to printf: counter = 100 in C
//Print floating-point variables: 1000.0
//Print string multiplication: XSL
//Print string: XSLXSLXSLXSLXSLXSLXSLXSLXSLXSL XSLXSL
//Print list: ['item1','item2','item3']
//Print List (Addition): ['item1','item2','item3','append']
//Print List (Addition): ['item1','item2','append']
//Print Yuan Zu: ('runoob', 786, 2.23,'john', 70.2)
//Print dictionary (member): this is one This is two
//Print dictionary (whole): {name':'xsl','code': 824}
//Print dictionary (key value): dict_keys (['name','code'])
//Print dictionary (value): dict_values(['xsl', 824])
-------------------- 5 -Built-in function
-----------Number Type transition
int(x[,base])         take x Convert to an integer
long(x[,base])        take x Convert to a long integer
float(x)              take x Convert to a floating point number
complex(real[,imag])  Create a plural
str(x)                Target x Convert to String
repr(x)               Target x Convert to expression string
eval(str)             Used to calculate validity in strings Python Expressions and returns an object
tuple(s)              Sequence s Convert to a tuple
list(s)               Sequence s Convert to a list
chr(x)                Converting an integer to a character
unichr(x)             Converting an integer to an integer Unicode character
ord(x)                Converting a character to its integer value
hex(x)                Converting an integer to a hexadecimal string
oct(x)                Converting an integer to an octal string
bool(x)               Convert a parameter to Boolean type 0/empty-False Non-zero/Nonempty-True
-----------Mathematical function
abs(x)                Returns the absolute value of a number, such as abs(-10) Return 10
ceil(x)               Returns the upper integer of a number, such as math.ceil(4.1) Return 5
cmp(x, y)             If x < y Return -1, If x == y Return 0, If x > y Return 1
exp(x)                Return e Of x pow(ex),as math.exp(1) Return 2.718281828459045
fabs(x)               Returns the absolute value of a number, such as math.fabs(-10) Return 10.0
floor(x)              Returns the rounded integer of a number, such as math.floor(4.9)Return 4
log(x)                as math.log(math.e)Return 1.0,math.log(100,10)Return 2.0
log10(x)              Returns base 10 x Logarithms, such as math.log10(100)Return 2.0
max(x1, x2,...)       Returns the maximum value of a given parameter, which can be a sequence
min(x1, x2,...)       Returns the minimum value of a given parameter, which can be a sequence
modf(x)               Return x The integer part and the decimal part, the numerical symbols of the two parts and x Similarly, the integer part is expressed in floating-point form
pow(x, y)             x**y Value after operation
round(x [,n])         Returns floating-point numbers x A rounded value, as given. n Value represents the number of digits rounded to the decimal point
sqrt(x)               Return number x The square root, the number can be negative, and the return type is real, such as math.sqrt(4)Return 2+0j
-----------Random Number Function
random.choice(seq)    Random selection of an element from a sequence, such as random.choice(range(10)),Random selection of an integer from 0 to 9.
random.randrange ([start,] stop [,step])Gets a random number from a set incremented by a specified cardinality within a specified range, with a default cardinality of 1
random.random()       Random generation of the next real number, it is in[0,1)Scope
random.randint(min,max)  Random Generation of the Next Integer in a Certain Range
random.seed([x])      Changing the Seeds of Random Number Generators seed. If you don't understand the principle, you don't have to set it up specifically. seed,Python Will help you choose seed
random.shuffle(lst)   Random sorting of all elements of a sequence
random.uniform(x, y)  Random generation of the next real number, it is in[x,y]Scope
-----------trigonometric function
acos(x)               Return x Anticosine radian value
asin(x)               Return x Inverse Sinusoidal Radius Value
atan(x)               Return x Anti-tangent radian value
atan2(y, x)           Returns the given X and Y Arbitrary tangent of coordinate values
cos(x)                Return x Cosine value of radian
hypot(x, y)           Return to Euclidean norm sqrt(x*x + y*y)
sin(x)                Return x Sinusoidal value of radian
tan(x)                Return x Tangent value of radian
degrees(x)            degrees,as degrees(math.pi/2) , Return 90.0
radians(x)            radians
-----------Mathematical Constants
pi                    Circumference, generally as followsπTo Express
e                     Natural Constants
-----------All keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
-----------Other
len(s)                Returns the length of an object
set(s)                Converting to Variable Sets
dict(d)               Create a dictionary. d Must be a sequence (key,value)Tuples.
frozenset(s)          Converting to an immutable set
-------------------- 6 -operator
//Arithmetic operators: +,-,*,/,%,**,//
//The comparison operator: ==,!=,<>,>,<,>,<,>=,<=
//Assignment operators: =,+=,-=,*=,/=,%=,**=,/==
//Bit-by-bit operators: &, |, ^, -, <<, >>.
//Logic operators: and, or, not
//Membership operators: in, not in
//Identity operators: is, is not
//String operators: +, *, [], [:], in,not in,r/R,%
//String formatting operators:%c,%s,%d,%u,%o,%x,%X,%f,%e,%E,%g,%G,%p
  //Formatting Operator Assistance: *, -, +, <sp>, #, 0,%, (var), m.n
//Complex string reference:'''
-------------------- 7 -condition
//Conditional statement: if-elif-else
//Conditional examples:else
-------------------- 8 -loop
//Loop statement: while,for
//Loop control statements: break,continue,pass
for Example hello 0
for Example hello 1
-------------------- 9 -Printing
0123456789
-------------------- 10 -time
Unix Timestamp:        1540195124.3202357
.localtime   :         time.struct_time(tm_year=2018, tm_mon=10, tm_mday=22, tm_hour=15, tm_min=58, tm_sec=44, tm_wday=0, tm_yday=295, tm_isdst=0)
.asctime     :         Mon Oct 22 15:58:44 2018
//Delay (seconds): time.sleep(x)
-------------------- 11 -file
//Create xsl_basic_1_base.txt and write the string: 1234567890
//Current file location 10
//Locate to 5, read 5 bytes of data: 67890
-------------------- 12 -Reading and Writing of Documents---pickle Save Module
.dump: {'name': 'pickle_name', 'pickle_age': 36}
.loat: {'name': 'pickle_name', 'pickle_age': 36}
-------------------- 13 -Function usage
//Calling a function!
-------------------- end
-------------------- 15 -Use of classes
-------------------- 16 -Use of Modules(Modules are functions./class/Combination of variables)
turtle       :        Little Turtle Drawing
copy.copy    :        shallow copy,Changing the original object affects the new object
copy.deepcopy:        deep copy,Changing the original object does not affect the new object
keyword      :        Keyword
-------------------- 17 -Input and output

//Please enter the key and press Enter to exit.

 

Posted by kcpaige89 on Sun, 27 Jan 2019 08:21:15 -0800