Python Learning (DAY3)

Source: Internet
Author: User
Tags local time readable

1, the use of the collection:

Operation #1, Collection: List_1 = [1,4,5,7,3,6,7,9]list_1 = set (list_1) #创建集合list_2  = set ([ 2,6,0,22,66,8,4]) print (List_1,type (list_1), list_2) print (List_1.intersection (list_2)) #取两集合的交集print (list_1.union (list_2)) #并集print (List_1.difference (list_2)) #差集  in list_1 but not in list_2print (list_2. Difference (list_1)) #差集list_3  =set ([1,4,7]) print (List_3.issubset (list_1)) #子集print (List_1.issuperset (list_3 )) #父集print (List_1.symmetric_difference (list_2)) #对称差集print ("-------------") List_4 =set ([5,6,8]) print (list_ 3.isdisjoint (list_4)) #Return  True if two sets have a null  Intersectionprint ("operator". Center (+, '-')) print (list_1 &  (list_2)) #并集print (list_1 |  (list _2)) #并集print (list_1 -  (list_2)) #差集in  list_1 but not in list_2print (list_1  ^  (list_2)) #对称差集print (list_1 ^  (list_2)) #对称差集print (List_1.add (999)) #添加list_1. Update ([ 888,777]) #添加多项print (list_1) List_1.remove (1) #指定删除print (list_1) print (List_1.pop ()) #随机删除并返回 #list_1.remove () empty will error List_1.discard (888) #删除print (list_1)

2. File Operation:

The mode of opening the file is:

R, read-only mode (default).

W, write-only mode. "unreadable; not exist; create; delete content;"

A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

r+, can read and write files. "readable; writable; can be added"

w+, write and read

A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

RU

R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

Rb

Wb

Ab

F = open ("Yesterday.txt", ' r+ ') #文件句柄, Yesterday.txt: File name Data = f.read () print (data) print ( F.write ("123")) F = open ("Yesterday.txt", "r+", encoding= "utf - 8") #data  =  F.readlines () #high  bigecount = 0for line in f:    if  Count==9:        print ('----I am split line-----')          count += 1        continue     print (line)     count += 1print ("1111111231231211111", F.tell ()) F.close () F = open ("Yesterday.txt", ' r+ ', encoding= "utf - 8") print ("11111111111111111111", F.tell ()) #tell ()   method returns the current position of the file, which is the current position of the file pointer. Print (F.readline ()) print (F.readline ()) print (F.readline ()) print (F.tell ()) f.seek (0) #seek ()   method is used to move a file read pointer to a specified location. Print (F.readline ()) print (f.encoding) #文件字符编码print (F.fileno ()) #fileno ()   method returns a file descriptor for an integer type (file descriptor fd  integer), which can be used for the  I/O  operation of the underlying operating system. The print (f.name) #打印文件名print (F.flush ()) #flush ()   method is used to flush the buffer, and the data in the buffer is immediately written to the file, while the buffer is emptied, without the need to wait for the output buffer to be written passively. #一般情况下, the buffer is refreshed automatically when the file is closed, but sometimes you need to refresh it before closing, so you can use the  flush ()   method. F.close () F = open ("Yesterday2.txt", ' r+ ') f.truncate () #truncate ()   method is used to truncate the file, if an optional parameter  size is specified, The truncation file is a  size  character.   Resets to the current position if  size is not specified. F.close () #f  = open ("Yesterday2.txt", "WB") #print (F.readline ()) F = open ("Yesterday2.txt", ' WB ') f.write (' hello binary\n '. Encode (encoding= ' utf-8 ')) f.close () ' #low  loopfor line in  F.readlines ():     print (line) "

2, 1with statement:

Import Sysprint (sys.getdefaultencoding ()) #打印系统默认编码with open ("Yesterday.txt", ' R ', encoding= "Utf-8") as F, open (" Yesterday2.txt ", ' R ', encoding=" Utf-8 ") as F2:for line #with代码块执行完毕时, internal automatically shuts down and frees file resources

2, 2 File modification:

f = open ("Yesterday1.txt", ' R ', encoding= "utf-8") f_new = open ("Yesterday2.txt", ' W ', encoding= "Utf-8") for line in F:if "the tip of the tongue On the Rain "in Line:line = Line.replace (" The Tip of the Rain "," 12345 ") The #replace () method replaces the old (older string) in the string with the new one, and if you specify the third parameter max, the replacement is no more than M    Ax times. F_new.write (line) F.close () F_new.close ()

3, character encoding:

# author:deyi Liuimport sysprint (sys.getdefaultencoding ()) #打印系统默认编码s = "Hello" S_GBK = S.encode ("GBK") print (S_GBK) print ( S.encode ()) Gbk_to_utf8 = S_gbk.decode ("GBK"). Encode ("Utf-8") print (Gbk_to_utf8)
#-*-CODING:GBK-*-import sysprint (sys.getdefaultencoding ()) #打印系统默认编码s = "Hello" #文件编码为gbk, but s = "Hello" encoded as Unicodeprint ( S.encode ("GBK")) Print (S.encode ("Utf-8")) Print (S.encode ("Utf-8"). Decode ("Utf-8"). Encode ("gb2312")) print ( S.encode ("Utf-8"). Decode ("Utf-8"). Encode ("gb2312"). Decode ("gb2312"))

4. Function:

function definition:

def test (x): #def定义函数关键字, test function name, () content definition formal parameter "the function definitions" #文档描述 x+=1# generic code block or program processing logic return X#return define return value
 #定义函数def  func1 ():     "Testing1"      print ("in the func1")     return 0# defines the procedure (a function with no return value) DEF FUNC2 ( ):     "Testing2"     print ("In the func2") x = func1 () Y = func2 () print ("from func1 return is: %s"%x) print ("from func2  return is: %s "%y) 
import timedef logger ():     time_format  =  '%y-%m-%d %x ' #年月日时,%x  Local corresponding time representation     time_current =  Time.strftime (Time_format) #time  strftime ()   function receives a time tuple and returns the local time as a readable string, in the format determined by the parameter format.     with open ("A.txt", ' A + ')  as f:         f.write (' time is %s end action\n '%time_current) def test1 ():     print ("Test1 starting action ...")     logger () Def test2 ():     print ("Test2 starting action ...")     logger () def test3 ():     print ("Test3 starting action ...")     logger () test1 () test2 () Test3 () 
#定义函数def test1 (): Print ("in the Test1") def test2 (): Print (' in the Test2 ') return 0def test3 (): Print ("in the T Est3 ") return 1, ' Hello ', [' Alex ', ' Wupeiji '],{' name ': ' alex '}x = test1 () y = test2 () z = test3 () print (x) print (y) print (z)
#定义函数def Test (x, y): #x, y parameter print (×) print (y) test #1, 2 arguments, corresponding to parameter one by one (positional parameter call) test (y=1,x=2) #与形参顺序无关 (keyword Call) test (3,y=1) #关键字不能再位置参数前面
def test (x,y=2): #y = 2 default parameter, default parameter must not pass print (x) print (y) test (1) #test (1,3)

Parameter group:

Def test (*args): #参数组, starting with *, accepting n positional arguments, converting the form of the Narimoto group     print (args) test (1,2,3,4,5) test (*[ 1,2,3,4,5]) #args =tuple ([1,2,3,4,5]) Def test1 (X,*args):     print (x)      print (args) test1 (1,2,3,4,5) Def test2 (**kwargs): #把n个关键字参数, converted to the form of a dictionary     print ( Kwargs)     print (kwargs[' name '])     print (kwargs[' age ')      print (kwargs[' sex ') test2 (name= ' Alex ', age=8,sex= ' F ') #kwargs ={' name ':  ' Alex ', ' age ':  8,   ' sex ':  ' n '}test2 (**{' name ':  ' Alex ', ' age ': 8,  ' sex ':  ' n '}) #kwargs ={' name ':  ' Alex ', ' age ': 8,  ' sex ':  ' N '}def test3 (Name,**kwargs):     print (name)     print (Kwargs) test3 (' Alex ', age=8) Def test4 (Name,age=8,*args,**kwargs): #参数组要放在后面     print (name)     print (age)     print (args)      print (Kwargs) test4 (' Alex ', age=3,sex= ' F ', hobby= ' Tesla ') 
def test4 (Name,age=8,*args,**kwargs): #参数组要放在后面 print (name) print (Kwargs) logger ("TES T4 ") def logger (source): Print (" from%s "%source) test4 (' Alex ', age=3,sex= ' F ', hobby= ' Tesla ')

Higher order functions:

def add (A, B, f): # ABS () function returns the absolute value of the number return F (a) + f (b) res = Add (3,-6,abs) # ABS () function returns the absolute value of the number print (res)

5. Local Variables:

School = "Oldboy edu."    #全局变量def change_name (name): Global School#global declares the globals variable school = "ASD" #局部变量 print ("Before Change", Name,school) Name = "Alex Li" #这个函数就是这个变量的作用域 print ("After Change", name) name = "Alex" Change_name (name) print (name) print (school)
names = ["Alex", "Jack", "Rain"]def change_name (): names[0] = "Golden Horn king" #字符串, integers can no longer be locally modified, lists, dictionaries, sets, classes of print ("Inside Func" , names) Change_name () print (names)

6. Progress bar:

Import Sys,time#sys.stdout.write ("ASD") #sys. Stdout.write ("ASD") #不换行for I in range: Sys.stdout.write ("#") sys.std Out.flush () #调用sys. Stdout.flush () force its "Buffer Time.sleep (0.1)

7. Recursion:

Def calc (n): print (n) if int (N/2) >0:return calc (int (N/2)) print ("--", N) Calc (10)


Python Learning (DAY3)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.