python, basic (beginners one)

Keywords: PHP encoding Python ascii Mobile


Run the first py file:

Python3x: Python file path return
Python2x: Python file path return
Difference: The default encoding method for python2 is ascii. 
# -*- encoding:utf-8 -*-
python3 default utf-8
 

 

 

Variables:

Is to temporarily store the intermediate results of some operations in memory for subsequent code calls.

1, must consist of any number, letter, underscore, and cannot start with a number
2, cannot be a keyword in python,
3. Variables are descriptive.

 

Constant:

A constant variable.
For example, pi = 3.1415926
BIR_OF_CHINA = 1949

 

Note:

 

Convenient for yourself and others to understand the code

Single line comment: #
Multiline comment:'''Content''

 

 

 

User interaction input:

  

1, wait for input

2, assign your input to the previous variable.
3. All data types from input are str

 

 

 

The underlying data type is initially:

Numbers: int 1,2,6,7,type()
+ - * \ **% Take Remainder

 

Character string:

str, python is always a string caused by quotation marks.

Additive: Stitching of strings
Multiplicable: str * int
bool: Boolean value, True false

String to number: int(str) condition: STR must be numeric
Numbers are converted to strings: str (int)

 

 


while

while condition:
Circulatory body
Circulation-free

 

Initial encoding

Computer transmission and storage are actually 01010101
US: ascii code to solve this global word problem
, created a universal code, unicode
1 byte for all English, special characters, numbers, etc.
2 bytes 16 bit table for one Chinese, not enough, unicode
A Chinese is represented by four bytes


Upgraded utf-8 is represented by 3 bytes in one Chinese language.

gdk is used domestically, two bytes in one Chinese,

 

Chinese; over 90,000 words,
Beginning 
00000001 8 bit ==1 byte
1byte 1024byte == 1kb
1kb 1024kb == 1mb
1mb 1024mb == 1gb
1gb 1024mb == 1tb

ascii: letter; number; special character; 1 byte
8-bit

Unicode: Two bytes; Upgrade 32 bits; Four bytes

utf-8: At least one byte; 8-bit representation.
8-bit 1 byte
16-bit Europe; 2 bytes
Chinese 24-bit; 3 bytes

int; English 1 byte Chinese 2 bytes

 

 


operator

 

* Index and slicing of strings

Indexes

Take A
s = 'ABCDLSESRF'

s1 = [0]

#Section #Heads and tails

  

Take ABCD
s = 'ABCDLSESRF'


s3 = s[0:4]

Accept ACL

s = 'ABCDLSESRF' s[First: Last: Step]


s10 = s[0:5:2]

s = 'ABCDLSESRF'

  


Remove DCBA

s12 = s[3::-1]

s = 'ABCDLSESRF'

//Recall
s14 = s[::-1]

 

  

List additions and deletions check:

Increase

li.append('**')
print(li)

  

List increases many times, p stops

whlie l:
username = input('>>>')
if username.strip().upper() =='Q':
break
else:
li.append(username)
print(li)

Fixed list add element: insert

li.insert(4,'**')
print(li)

  

At the end of the list:

extend
li.extend([1,2,3,])

 

  

Delete: pop

li,pop(1)	#Delete last by default
print(li)	#Delete by Index

name = li.pop(li) #Return value
print(name,li)

  

li.remove('**')	#Delete by element: remove
print(li)

  

li.clear() #Empty:clear

print(li)

  

del li[2:]	#Slice deletion: del
print(li)

  

change

li(0) ='**' #Index to change
print(li)

li[0:3] = ['Worker','Zhang Ge','Yuge',]
print(li) #Slice to change

  

check

for i in li: 
print(i) #Slice to check
print(li[0: 2])

  

Public method

l = len(li)
print(l) #	Several elements: len

num = li.count('**')
print(num) #Number of occurrences of element: count

li.index('***')# Indexes
print(li.index('***'))#Direct results

  

sort

li.sort() #Forward Sort

li.sort(reverse=True)
print(li) #Reverse sort

  

Reversal

li.reverse()
print(li)

  

 


Nesting of lists

li = ['taibai','Wilfordia','Great Heaven',['alex','egon',89],23]

print(li[1][1])#Find the rattan

li[0] = li[0].copitalize()
print(li) #Capitalize the first letter, replace the string

li[2] = li[2]replace('Hao''Sunrise')
print(li)
#Found Hao Tian to Hao Xu Tian

 

  

Yuan Zu.Read-only list, circular query, sliceable.
#Son can't change.Grandchildren may be able to change

tu[4][3]=[4][3].upper() #Grandchildren uppercase

tu[4].append('sb') #Add sb elements to grandchildren

  

 

join

 

s = 'alex'
sl = '_'.join(s)
print(sl)

  


> a_l_e_x

List to String

s = '',join(list)
print(s)

  

Use split () for string conversion lists
str->list


range

for i in range(0,100)
print(i) #[1,2,3,4,...99]

for i in range(0,10,3):
print(i) #Step [0,3,6,9,]

for i in range(10,0,-1)
print(i) #Turn it upside down

  

 



Dictionaries

dict
#Classification of data types: variable data types, immutable data types
Invariant data type: meta-ancestor, bool int str hash
Variable data type: list dict set cannot be hashed 
dict key must be an immutable data type, hash
value: Any data type.
dict Advantage: Binary Lookup to Query
Store large amounts of relational data
Features: Unordered

 

 


increase

dicl['hige'] = 185    #No key-value pairs, add
dicl['age'] = 16    #Value override if healthy

dicl.setdefault('weight')    
#There are key-value pairs, no changes, no additions.
dicl.setdefault('welght',150)
dicl.setdefault('name','Second elder brother')

 

Delete

print(dicl.pop('age'))      #Return value, key delete
 print(dicl.pop('Second elder brother','None'))    #Return value can be set

print(dicl.popitem())
#Delete, return value, return meta-ancestor

del dicl['namel']
del dicl
dicl.clear()    #Empty Dictionary

 

change

dicl['age'] = 16

 dic = {"name":"jin","age":18,"sex":"male"}
 dic2 ={"name":"alex","welght":75}
 dic2.update(dic) #Add key-value pair overrides from an existing dictionary to an existing dictionary

 

check

dicl = {'age':19,'name':'jin','sex':'male',}

print(dicl.keys()) #key
print(dicl.values()) #value
print(dicl.items()) #Key-Value Pairs

for i in dicl: #key
print(i)
for i in dicl.values(): #value
print(i)
for k,v in dicl.items(): #k,v Remove brackets, commas
print(k,v) #Key-Value Pairs

print(dicl['name']) #value

dic. get(key,None)
print(dicl.get('namel')) #Prevent errors

 

Nested,

dic = {
'name' :['alex','wusir','taibai'],
'py9':{
'time' :'1213',
'lenrn_money' :19800,
'addr' :'cbd',
},
'age' :21
}
dic['age'] = 56 #Change age to 56

print(dic['name'])
dic['name'].append('ritian')#List Add'ritian'
print(dic)

dic['name'][1] = dic['name'][1].upper()
#Put the wusir Change to uppercase
print(dic)
dic['py9']['female'] = 6 #py9 Add 6 girls

 

 


######

info = input('>>>') #ysjs123hsh122jj12
for i in info: #3 occurrences
if i.isalpha():
info = info.replace(i," ")
l = info.split()
print(len(l)) #Number of occurrences of print number strings

 

 

Element Classification

With the following values, save all values greater than 66 to the first in the dictionary key Medium,
//Save values less than 66 to ('k1''k2')
li = [11,22,33,44,55,66,77,88,99,90,]
dic = {}
l_greater = [] #List of all values greater than 66
l_less = [] #List of all values less than 66
for i in li:
if i == 66:continue
if i > 66:
l_greater.append(i)
else :
l_less.append(i)
dic.setdefault('k1',l_greater)
dic.setdefault('k2',l_less)
print(dic)

 

 

Output commodity list, user input serial number, display user selected commodities
//Commodity li = ["Mobile phone", "Computer", "Mouse pad", "Yacht"]
//Requirement:1: Page Display Sequence Number + Commodity names, such as:
1 Mobile phone
2 Computer
. . . 
2: The user enters the serial number of the selected item and prints the name of the item
3: If the serial number of the goods entered by the user is incorrect, the user is prompted for incorrect input.if And re-enter:
4: User Input Q,Exit the program.

 

while 1:
li = ["Mobile phone", "Computer", "Mouse pad", "Yacht"]
for i in li:
print('{}\t\t{}'.format(li.index(i) + 1, i))
num_of_chioce = input('Please enter the item number/input Q Exit the program')
if num_of_chioce.isdigit():
num_of_chioce = int(num_of_chioce)
if num_of_chioce > 0 and num_of_chioce <= len(li):
print(li[num_of_chioce])
else:
print('Please enter a valid number')
elif num_of_chioce.upper() == 'Q' :break
else :print('please enter a number')

 

 

Collection, variable data type, elements inside it must be immutable data type out of order, not repeating,

setl = {'ales','wusir','ritian','egon','barry',}

//increase
app
 setl.add('goddess')
 print(setl)
 update
 setl.update('abc')
 print(setl)
//delete
 setl.pop() #Random deletion with return value
 print(setl.pop())
 print(setl)

 setl.remove('alex') #Delete by Element
 print(setl)

 setl.clear()
 print(setl) #set()

 del setl
 print(setl)

 //check
 for i in setl:
 print(i)

 

 

intersection
 

set1 = {1,2,3,4,5}
 set2 = {4,5,6,7,8}
 set3 = set1 & set2
 print(set3)

 

Union

 

set1 = {1,2,3,4,5}
 set2 = {4,5,6,7,8}
 print(set1|set2)

 

Inverse intersection

 set1 = {1,2,3,4,5}
 set2 = {4,5,6,7,8}
 print(set1^set2)

 

Difference set

 set1 = {1,2,3,4,5}
 set2 = {4,5,6,7,8}
 print(set1 - set2)

 

Subset and Superset

 set1 = (1,2,3)
 set2 = (1,2,3)
 print(set1 < set2) #Both are the same, both are instructions set1 yes set2 A subset of

 print(set1 >set2) #Both are the same, both are instructions set2 yes set1 Superset

//Invariant data type #set Variable data types #disorder

 s = frozenset('barry')
 print(s,type(s))
 sl = {1,2,3}
 print(sl,type(sl))

 

 

 


File Operation
    Exercise, txt
1, File Path, d:\Exercise.txt
2, Encoding method: utf-8, gdk,,,
3. Operation mode: Read-only, Write-only, Append, Read-write, Write-read.
              Files stored in any encoding will be opened in any encoding.

 


Read-only'r','rb'

File Operation
f = open('Practice.py',mode='r',encoding='utf-8')
content = f.read()
print(content)
f.close()

 

f = open('Practice.py',mode='rb',)
content = f.read()
print(content)
f.close()

 

Read and Write
f = open('log',mode='r+',encoding='utf-8')
print(f.read())
f.write('Hmm good story')
print(f.read())
f.close()

 

with bytes type
f = open('log',mode='r+b',)
print(f.read())
f.write('Hmm good story'.encode('utf-8'))
print(f.read())
f.close()

 



Write only. w. Without this file, a creation file will be created.
f = open('log',mode='w',encoding='utf-8')
f.write('Fetal Abortion and Bone Change Just')
f.close()
//Write and Read
f = open('log',mode='w+',encoding='utf-8')
f.write('Turn over a new leaf')
f.seek(0)
print(f.read())
f.close()
f = open('log',mode='w+b',)
f.write('Abortion and replacement,'.encode('utf-8'))
f.seek(0)
print(f.read())
f.close()

 

First clear all the contents of the source file, while writing,
f = open('log',mode='w',encoding='utf-8')
f.write('Don't fall in love with me.')
f.close()

f = open('log',mode='wb')
f.write('Fetal Abortion and Bone Change Just'.encode('utf_8'))
f.close()

 


Append

f = open('log',mode='a',encoding='utf_8')
f.write('All have no taste')
f.close()
f = open('log',mode='ab')
f.write('Ha-ha'.encode('utf_8'))
f.close()

 



Functional Explanation
f = open('log',mode='r+',encoding='utf-8')
content = f.read(6) #Characters are all read out
f.seek(3)           #Is the position of the cursor defined in bytes
print(f.tell())     #tai.ou.Tell you where the cursor is
content = f.read()
print(content)
line = f.readline() #Read line by line
line =f.readlines()     #Add each line as an element in the list lise in
for line in f:
    print(line)
f.close()


with open('log',mode='r+',encoding='utf-8')as f,\
open('log',mode='r+',encoding='utf-8')as f1:
print(f.read())
 

 


Summary. Document handling:
  Open File
        Open ('path','open mode','specify encoding mode')
        Open mode: r, w, a, r+, w+, a+.a+b
    r+: Open the file to write directly and finish reading before writing
    Encoding--utf-8
    Operation mode:
    read
        read One Time read
        readline read line by line
        readlines One-time Read
            Don't know where to end
            Video picture rb bytes read in bytes
        for loop--best!!
    write
        write
        Cursor--File Pointer
        seek_Specifies that the cursor moves to a location
        tell_Get the current position of the cursor
        truncate_intercept file
     Close File
        close

     Modify File

 

with open('sister.py',encoding='utf-8') as f,open('Ten thousand minutes.py','w',encoding='utf-8') as f2:
    for line in f:
        if 'Lotus' in line:
            line = line.replace('Lotus','Pear Blossom')
            //Write File
        f2.write(line)

import os
os.remove('sister.py')  #Delete Files
os.rename('Ten thousand minutes.py','sister.py')  #rename file

Posted by gonsman on Mon, 29 Jul 2019 14:41:59 -0700