[Python] the most detailed basic tutorial on Python in the whole network (very detailed, sorted out)

Posted by skyagh on Fri, 04 Mar 2022 22:42:00 +0100


In Python, all identifiers can include English (case sensitive), numbers, and underscores (), But it cannot start with a number.

Start with a single underscore_ The class to be imported cannot be accessed directly through the class provided by XXX, but the class provided by foo.
Double underlined__ foo represents the private member of the class,
Beginning and ending with a double underscore__ foo__ Represents a special identifier for special methods in Python, such as__ init__ () represents the constructor of the class.


Python code blocks must use the same number of line indentation spaces

Begin with # single line comment in python.
Multiline comments in python use three single quotation marks ('') or three double quotation marks ("" ").

# Python statements generally use a new line as the end of the statement. However, we can use [slash (\)] to divide a line of statements into multiple lines,
# If the statement contains [], {} or () parentheses, you do not need to use multiline connectors.
# Python can use multiple statements in the same line, and use [semicolon (;)] between statements division
total = item_one + \
        item_two + \
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

# Python can use multiple statements in the same line, and use [semicolon (;)] between statements division.
import sys; x = 'runoob'; sys.stdout.write(x + '\n')

# Python can use [quotation marks ('), double quotation marks ("), three quotation marks (' '' or" ")] to represent strings
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
Contains multiple statements"""

# The default output of print is line feed. If you want to realize [no line feed, you need to add a comma at the end of the variable].
print x,y


counter = 100 # Assign integer variable
miles = 1000.0 # float 
name = "John" # character string

a = b = c = 1
a, b, c = 1, 2, "john"

# The default length is [1] from left to right
# From right to left, the default index is [- 1], and the maximum range is [beginning of string]
# The third parameter is used to [intercept step size]
s = "a1a2···an"   # n>=0


tinylist = [123, 'john']
print list[0]            # The first element of the output list
print list[1:3]          # Output the second to third elements 
print list[2:]           # Output all elements from the third to the end of the list

# The plus sign + is a list join operator, and the asterisk * is a repeat operation
print tinylist * 2       # Output list twice
print list + tinylist    # Print a list of combinations

list.append('Google')   ## Add elements using append()
del list1[2]			# You can use the del statement to delete the elements of the list

len([1, 2, 3])	3	#length
[1, 2, 3] + [4, 5, 6]	[1, 2, 3, 4, 5, 6]	#combination
['Hi!'] * 4	['Hi!', 'Hi!', 'Hi!', 'Hi!']	#repeat
3 in [1, 2, 3]	True	#Does the element exist in the list
for x in [1, 2, 3]: print x,	1 2 3	#iteration

Tuple (tuple)

# Tuples are identified by (). Internal elements are separated by commas. However, tuples cannot be assigned twice, which is equivalent to a read-only list.
tinytuple = (123, 'john')

Dict (Dictionary)

# The dictionary is identified by "{}". The dictionary consists of an index (key) and its corresponding value value.
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'runoob','code':6734, 'dept': 'sales'}
print dict['one']          # The output key is the value of 'one'
print dict[2]              # The output key is the value of 2

print tinydict             # Output complete dictionary
print tinydict.keys()      # Output all keys
print tinydict.values()    # Output all values

tinydict['Age'] = 8 # to update
tinydict['School'] = "RUNOOB" # add to

del tinydict['Name']  # Delete entries whose key is' Name '
tinydict.clear()      # Clear all entries in the dictionary
del tinydict          # Delete dictionary


/Divide - x divided by y
%Modulo - returns the remainder of the division
**Power - returns the y-power of x
//Integer division - returns the integer portion of the quotient (rounded down)

and x and y Boolean and - x and y return False if x is False, otherwise it returns the calculated value of y.
or x or y Boolean or - if x is non-zero, it returns the calculated value of X, otherwise it returns the calculated value of y.
not not x Boolean not - Returns False if x is True.

is is to judge whether two identifiers refer to an object
is not is not to judge whether two identifiers are referenced from different objects
is and = = difference:
Is is used to judge whether the two variable reference objects are the same (the same memory space), = = is used to judge whether the values of the reference variables are equal.

Conditional statement

if num == 3:            # Determine the value of num
    print 'boss'        
elif num == 2:
    print 'user'
elif num == 1:
    print 'worker'
elif num < 0:           # Output when the value is less than zero
    print 'error'
    print 'roadman'     # Output when none of the conditions are true

Circular statement

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # Skip output when not even
    print i         # Output even number 2, 4, 6, 8, 10
i = 1
while 1:            # If the cycle condition is 1, it must be true
    print i         # Output 1 ~ 10
    i += 1
    if i > 10:     # Jump out of the loop when i is greater than 10

flag = 1
while (flag): print 'Given flag is really true!'

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second instance
   print ('Current fruit: %s'% fruit)

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('Current fruit : %s' % fruits[index])

for letter in 'Python':     # First instance
   if letter == 'h':
   print 'Current letter :', letter

character string

+	Connection string	
>>>a + b

*	Duplicate output string	
>>>a * 2

[]	Get characters in string by index	

[ : ]	Intercepts a portion of a string	

in	member operator  - Returns if the string contains the given character True	
>>>"H" in a
not in	member operator  - Returns if the string does not contain the given character True	
>>>"M" not in a

r/R	Original string - Original string: all strings are used directly according to the literal meaning. There are no special escape characters or characters that cannot be printed. The original string is divided by adding letters before the first quotation mark of the string"r"(It has almost the same syntax as an ordinary string except that it can be case sensitive.	
>>>print r'\n'
>>> print R'\n'

String formatting

print "My name is %s and weight is %d kg!" % ('Zara', 21) 
%s	 format string 
%d	 Format integer
%f	 Format floating-point numbers to specify the precision after the decimal point

Three quotation marks

Allows a string to span multiple lines. The string can contain line breaks, tabs, and other special characters
 >>> hi = '''hi 
>>> hi   # repr()
>>> print hi  # str()


string.count(str, beg=0, end=len(string))
return str stay string The number of times it appears, if beg perhaps end If specified, the specified range will be returned str Number of occurrences
string.endswith(obj, beg=0, end=len(string))
Check whether the string is obj End, if beg perhaps end If specified, check whether the specified range is obj End, if yes, return True,Otherwise return False.
string.find(str, beg=0, end=len(string))
testing str Included in string Medium, if beg and end If the range is specified, check whether it is included in the specified range. If it is, return the starting index value; otherwise, return-1
format string 
string.index(str, beg=0, end=len(string))
Follow find()The same way, but if str be not in string An exception will be reported in.
with string As a separator, the seq All elements in(String representation of)Merge into a new string
string.replace(str1, str2,  num=string.count(str1))
hold string Medium str1 replace with str2,If num If specified, the replacement does not exceed num second.
string.split(str="", num=string.count(str))
with str Slice separator string,If num If there is a specified value, only separate num+1 Substring


In python, strings, tuples, and numbers are immutable objects, while list,dict, and so on are modifiable objects.

Immutable type: the variable is assigned a=5 and then a=10. Here, in fact, a new int value object 10 is generated, and then a points to it, while 5 is discarded. Instead of changing the value of a, it is equivalent to newly generating a.

Variable type: if the variable is assigned la=[1,2,3,4] and then assigned la[2]=5, it changes the value of the third element of list la. La itself does not move, but some of its internal values have been modified.

#Description of writable function
def printinfo( name, age = 35 ):
   "Print any incoming strings"
   print "Name: ", name
   print "Age ", age
#Call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

# Description of writable function
def printinfo( arg1, *vartuple ):
   "Print any incoming parameters"
   print "output: "
   print arg1
   for var in vartuple:
      print var
# Call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )

Anonymous function

# Description of writable function
sum = lambda arg1, arg2: arg1 + arg2
# Call sum function
print "The added value is : ", sum( 10, 20 )
print "The added value is : ", sum( 20, 20 )


import support

from fib import fibonacci

from math import *

Search path
1. Current directory
2. If it is not in the current directory, Python searches each directory under the shell variable PYTHONPATH.
3. If none is found, python looks at the default path. Under UNIX, the default path is generally / usr/local/lib/python /.
The module search path is stored in sys. Of the system module Path variable. The variable contains the current directory, PYTHONPATH and the default directory determined by the installation process.

Packages in Python
Package is a hierarchical file directory structure, which defines a Python application environment composed of modules, sub packages, and sub packages under sub packages.

In short, a package is a folder, but it must exist under it__ init__.py file, the contents of which can be empty__ init__.py is used to identify that the current folder is a package.

Consider one in package_runoob1. In the runoob directory py,runoob2.py, __ init__.py file, test Py is the code of the test call package, and the directory structure is as follows:
|-- __init__.py
|-- runoob1.py
|-- runoob2.py

# Import Phone package
from package_runoob.runoob1 import runoob1
from package_runoob.runoob2 import runoob2


str = input("Please enter:")
print "What did you enter: ", str

fo = open("foo.txt", "w")
print "file name: ", fo.name
print "Is it closed : ", fo.closed
print "Access mode : ", fo.mode
print "Whether to force spaces at the end : ", fo.softspace

# Open a file
fo = open("foo.txt", "w")
str = fo.read(10)
fo.write( "www.runoob.com!\nVery good site!\n")
# Close open files

Files and folders

import os
os.rename( "test1.txt", "test2.txt" )

# Change the current directory to "/ home/newdir"
# Give the current directory
print os.getcwd()
# Delete the "/ tmp/test" directory
os.rmdir( "/tmp/test"  )


    Normal operation
    If an exception occurs, execute this code
    If there are no exceptions, execute this code

    fh = open("testfile", "w")
    fh.write("This is a test file for testing exceptions!!")
except IOError:
    print "Error: File not found or failed to read"
    print "Content written to file successfully"

try-finally Statement executes the last code regardless of whether an exception occurs.
<sentence>    #Always execute when exiting try

    fh = open("testfile", "w")
        fh.write("This is a test file for testing exceptions!!")
        print "Close file"
except IOError:
    print "Error: File not found or failed to read"


class Employee:
   'Base class for all employees'
   empCount = 0
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount
   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
"establish Employee The first object of the class"
emp1 = Employee("Zara", 2000)
"establish Employee Class"
emp2 = Employee("Manni", 5000)
print "Total Employee %d" % Employee.empCount

The empCount variable is a class variable whose value will be shared among all instances of the class. You can use employee. Net in internal or external classes empCount access.

The first method__ init__ () method is a special method called the constructor or initialization method of a class. It will be called when an instance of this class is created

self represents the instance of a class. self is necessary when defining the method of a class, although it is not necessary to pass in the corresponding parameters when calling.


class A:        # Define class A

class B:         # Define class B

class C(A, B):   # Inherit classes A and B


class Parent:        # Define parent class
   def myMethod(self):
      print 'Call parent method'
class Child(Parent): # Define subclasses
   def myMethod(self):
      print 'Call subclass method'

Operator overloading

class Parent:        # Define parent class
   def myMethod(self):
      print 'Call parent method'
class Child(Parent): # Define subclasses
   def myMethod(self):
      print 'Call subclass method'

Class properties and methods
Private properties of class
__ private_attrs: it starts with two underscores and declares that the attribute is private and cannot be used or accessed directly outside the class. When used in methods inside a class, self__ private_attrs.

Class method
Inside the class, you can define a method for the class by using the def keyword. Unlike the general function definition, the class method must contain the parameter self, which is the first parameter

Private method of class
__ private_method: it starts with two underscores and declares that the method is private and cannot be called outside the class. Call self. Inside the class__ private_ methods

Single underline, double underline and double underline Description:
__ foo__: Special methods are defined. Generally, system defined names are similar__ init__ () or something.

_ foo: variables starting with a single underscore represent protected variables, that is, protected types can only be accessed by themselves and subclasses, not from module import*

__ foo: Double underscores represent variables of private type, which can only be accessed by the class itself.

Topics: Big Data hive Spark