Day3 Python Basics

Source: Internet
Author: User
Tags define local function definition readline variable scope

First, the use of the collection

A collection is an unordered, non-repeating combination of data, and its main functions are as follows:

    • Go to the weight, turn a list into a set, and then automatically go heavy.
    • Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set
List_1 = [1, 4, 5, 7, 3, 6, 7, 9]list_1 = set (list_1) print (list_1, type (list_1)) list_2 = Set ([2, 6, 0,,, 8, 4]) print (list_1, list_2) print (List_1.intersection (list_2)) # Intersection print (list_1.union (list_2)) # Seek and set PR               Int (list_1.difference (list_2)) # differential set, in list_1 and not in List_2print (List_2.difference (list_1)) # differential set, in List_2 and not in List_1print (List_1.issubset (list_2)) # Determine if List_1 is a list_2 subset of print (List_1.iss                 Uperset (list_2) # to determine if List_1 is a list_2 parent set list_3 = Set ([1, 3, 7]) print (List_3.issubset (list_1)) # List_3 is list_1 subset print (List_1.issuperset (list_3)) # list_1 is list_3 parent set print (List_1.symmetric_difference (list_2) # symmetric difference Set, two sets are removed from each other, duplicate values List_4 = Set ([5, 6, 8]) print (List_3.isdisjoint (list_4)) # intersection is NULL return true# symbol p Rint (List_1 & list_2) # intersection print (list_1 | list_2) # SET Print (List_1-li                   st_2)      # difference set, in list_1 but not in List_2print (list_1 ^ list_2) # Symmetric difference Set # basic Operation List_1.add (999) # Add print (list_1) list_1.update ([888, 777, 555]) # Add multiple print (list_1) list_1.remove (888 # Delete the specified element print (list_1) print (List_1.pop ()) # randomly deletes an element and returns the element list_1.                                    Discard ("ddd") # deletes the specified element, if the element is deleted in the collection, and does nothing if it is not (remove is an error if the element is no longer in the collection) x = 5x in List_4 # Test if X is a member of List_4 x not in List_4 # Test x is not a member of List_4 List_4.issubset (list  _2) # Test if every element in List_4 is in list_2 list_4 <= list_2list_4.issuperset (list_2) # Test whether each element in the list_2 is in List_4 list_4 >= list_2
Second, the file operation

1. To the file, get the file handle and assign a value to a variable

2. Manipulating files with a handle

3. Close the file

The existing files are as follows

Somehow, it seems the love I knew is always the most destructive kind I don't know why, I went through the most devastating of the kind yesterday when I am young yesterday when I Young and frivolous The taste's life is sweet as rain upon my tongue like the tip of the tongue I teased at live as if it were a foolish game I tease life See it For the stupid game the evening breeze is like the night breeze may tease the candle flame tease Candle flames The Thousand dreams I dreamed I've dreamed of the splendid T Hings I planned those I plan the brilliant blueprint I always built-last on weak and shifting sand but I've been building it on the sands of the perishable I lived by night and shunned the N aked light of day I singer to escape the day naked sun and just now I saw how the time ran away it was time for me to see how the years passed yesterday Mad so many lovely songs were waiting to be sung there are so many sweet longtaisheng so I sing so many wild pleasures lay in store for me there are so many wanton pleasures that I enjoy and so Mu CH pain my eyes refused to see there's so much pain in my eyes but I'm blind I ran so fast it time and youth at the last run out I'm running away and my youth is gone I never Stopped to think what life is all about I never stopped to think about the meaning of living and every conversation that I can now recall all the conversations recalled today concerned its Elf with me and nothingelse at all except for anything that's relevant to me. The game of love I played with arrogance and pride I'm playing with conceit and arrogance. Every flame I lit too quickl Y, quickly died all the flames that I lit were extinguished too fast the friends I made all somehow seemed to slip away all my friends seem to have left without knowing and just now I'm leaving Alo Ne to end the play, yeah I'm the only one on stage to end this farce Oh, yesterday when I am young oh yesterday when I am so many, many songs were waiting to be sun G There's so many sweet Longtaisheng I sing so many wild pleasures lay in store for me there's so much wanton joy I enjoy and so much pain my eyes refused to see there's so much pain in my eyes But there is so many songs in me, won ' t be sung I have too many songs that will never be sung I feel the bitter taste of tears upon my tongue I tasted the tongue of tears Bitter taste the time had come for me-pay-yesterday finally came to the cost of the day for yesterday when I was young as I was younger and frivolous
data = open("yesterday",encoding="utf-8").read()  
f = open("yesterday",‘r‘,encoding="utf-8")  # 文件句柄,r为只读模式data = f.read()data2 = f.read()print(data)print(‘--------data2----%s---‘ %data2)      # 打印结果data2为空f.close()
f = open("yesterday2",‘w‘,encoding=‘utf-8‘)  # w是创建一个文件去写,会覆盖已有的文件f.write("我爱北京天安门,\n")f.write("天安门上太阳升")f.close()
f = open("yesterday2",‘a‘,encoding="utf-8")  # a 追加模式,不能读f.write("\n我爱北京天安门,\n天安门上太阳升")f.close()
f = open("yesterday","r",encoding="utf-8")   # 读前五行for i in range(5):    print(f.readline())                      # readline每执行一次读一行f.close()
f = open("yesterday","r",encoding="utf-8")print(f.readlines())                         # readlines将所有行读取到一个列表中,适合读小文件f.close()
f = open("yesterday","r",encoding="utf-8")for line in f.readlines():                   # 循环读每一行    print(line.strip())f.close()

Low loop

f = open("yesterday","r",encoding="utf-8")for index,line in enumerate(f.readlines()):                   # 不打印第9行    if index == 9:        print("----我是分割线---")        continue    print(line.strip())f.close()

High Bige, fastest, F not list

f = open("yesterday","r",encoding="utf-8")count = 0for line in f:    if count == 9:        print("----我是分割线----")        count += 1        continue    print(line)    count += 1f.close()
f = open("yesterday", "r", encoding="utf-8")print(f.tell)                   # 打印字符位置print(f.readline())print(f.readline())print(f.readline())print(f.tell())f.seek(0)                       # 回到首位print(f.readline())f.seek(10)                      # 回到位置10print(f.readline())print(f.encoding)               # 打印文件编码print(f.fileno())               # 打印文件句柄编号print(f.name)                   # 打印文件名字print(f.flush())                # 将缓存文件刷新到硬盘f.close()

Progress bar

import sys,timefor i in range(20):    sys.stdout.write("#")    sys.stdout.flush()    time.sleep(0.1)
f = open("yesterday2", "a", encoding="utf-8")f.seek(10)                      # 这个操作失效,不会影响截断位置f.truncate(10)                  # 截断,从10个字符位置后开始截断
f = open("yesterday2", "r+", encoding="utf-8")      # r+读追加模式print(f.readline())print(f.readline())print(f.readline())print(f.tell())f.write("--------diao--------")                     # 会追加到文件内容最末尾,并不会在第sanprint(f.readline())f.close
f = open("yesterday2", "w+", encoding="utf-8")      # w+写读模式,先写后读f.write("------diao------1\n")f.write("------diao------1\n")f.write("------diao------1\n")f.write("------diao------1\n")print(f.tell())f.seek(10)print(f.tell())print(f.readline())f.write("should be at the begining of the second line")     # 从最后位置写f.close()
f = open("yesterday2", "a+", encoding="utf-8")          # 追加读
f = open("yesterday2", "rb")              # 二进制格式去读文件,不需要encoding;python3只能用二进制网络传输(python2可以用字符);视频文件;print(f.readline())f.close()
f = open("yesterday2", "wb")                # 二进制格式写f.write("hello binary\n".encode())          # 将二进制转换为程序默认字编码f.close()
f = open("yesterday2", "ab")                  

Summarize

    • Mode of open File

      • 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 +, readable and can be added
    • "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

Modify a string in a file, read the original file, write a new file

f = open("yesterday","r",encoding="utf-8")f_new = open("yesterday2.bak","w",encoding="utf-8")for line in f:    if "肆意的快乐等我享受" in line:        line=line.replace("肆意的快乐等我享受","肆意的快乐等Alex享受")    f_new.write(line)f.close()f_new.close()

With statement, do not need close each time ()

with open("yesterday2","r",encoding="utf-8") as f:    for line in f:        print(line)

Open multiple Files

with open("yesterday2","r",encoding="utf-8") as f,    open("yesterday","r",encoding="utf-8") as f2:    for line in f:        print(line)
Three, character encoding and transcoding

1. In Python2 the default encoding is ASCII, the default is Unicode in Python3

2.unicode is divided into utf-32 (4 bytes), utf-16 (accounting for two bytes), Utf-8 (1-4 bytes), so utf-16 is now the most commonly used Unicode version, but in the file is still utf-8, because the UTF8 save space

3. Encode in Py3, while transcoding will also change the string to bytes type, decode decoding will also turn bytes back to string

Encoding conversion in the Python2

#-*- coding:utf8 -*-import sysprint(sys.getdefaultencoding())  # 打印系统默认编码s="你好"print(s)# utf-8要先转换为unicodes_to_unicode=s.decode("utf-8")print(s_to_unicode,type(s_to_unicode))# unicode转换为gbks_to_gbk=s_to_unicode.encode("gbk")print(s_to_gbk)# gbk转换为utf-8,需要先将gbk转换为Unicode,再转换为utf-8gbk_to_utf8=s_to_gbk.decode("gbk").encode("utf-8")print(gbk_to_utf8)t=u"你好"               # u默认代表Unicode格式,不需要再将t转换为Unicodet_to_gbk= t.encode("gbk")print(t_to_gbk)

Python3 default encoding is Utf-8

import sysprint(sys.getdefaultencoding())s = "你哈"s_gbk=s.encode("gbk")print(s_gbk)print(s.encode())gbk_to_utf8= s_gbk.decode("gbk").encode("utf-8")print("utf8",gbk_to_utf8)

The encoding of the file is set to GBK, but the default encoding for the program is Unicode

#!/usr/bin/env python3# -*- coding:gbk -*-# Author: Erick Zhangimport sysprint(sys.getdefaultencoding())s="你哈"print(s.encode("gbk"))print(s.encode("utf-8"))print(s.encode("utf-8").decode("utf-8").encode("gb2312").decode("gb2312"))
Iv. functions

Three Ways to Program

Object-oriented: Huashan---"category----" class

Process-oriented: Shaolin Faction---"Process---" def

Functional programming: The---of the carefree faction---"DEF"

The definition of a function in a programming language:

function is a kind of programming method of logical structure and process

The function definition method in Python:

def test(x):    """the function definitions"""    x+=1    return xdef:定义函数的关键字test:函数名():内可定义形参""" """:文档描述(非必要,但是强烈建议为你的函数添加描述信息)x+=1:泛指代码块或程序处理逻辑return:定义返回值

The procedure return value in Python is None

# 函数def func1():    """testing"""    print(‘in the func1‘)    return 0# 过程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)运行结果:in the func1in the func2from func1 return is 0from func2 return is None

function action

    • Reduce duplicate code
    • To make the program extensible
    • Make programs easier to maintain
import timedef logger():    time_format = ‘%Y-%m-%d %X‘    time_current = time.strftime(time_format)    with open(‘a.txt‘,‘a+‘) as f:        f.write(‘%s end action\n‘ % time_current)def test1():    print(‘in the test1‘)    logger()def test2():    print(‘in the test2‘)    logger()def test3():    print(‘in the test3‘)    logger()test1()test2()test3()

return value

def test():    print(‘in the test1‘)    return 0x=test()print(x)

Three forms of return

def test1():    print(‘in the test1‘)def test2():    print(‘in the test2‘)    return 0def test3():    print(‘in the test3‘)    return 1,‘hello‘,[‘alex‘,‘wupeiqi‘],{‘name‘:‘alex‘}x=test1()y=test2()z=test3()print(x)print(y)print(z)运行结果:None0(1, ‘hello‘, [‘alex‘, ‘wupeiqi‘], {‘name‘: ‘alex‘})

Summarize:

    • Number of return values = 0, return None
    • Number of return values = 1, return object
    • Returns the number of values >1, returns a tuple

Parameters of the function

1. Position parameters

The actual argument that is actually present in memory, and the argument must correspond to the parameter one by one

# x,y为形参,1,2为实参def test(x,y):    print(x)    print(y)test(1,2)

2. Keyword invocation

is independent of the parameter order, the key argument must be to the right of the positional argument and cannot be repeated on the same parameter

def test(x,y):    print(x)    print(y)test(y=2,x=3)test(3,y=2)test(3,x=2) 报错test(x=2,3) 报错

3. Default parameters

When a function is called, the default parameter must not be passed; The default parameter should be defined to the right of the location parameter; The default parameter should usually be defined as an immutable type

def test(x,y=2):    print(x)    print(y)test(1)test(1,3)test(1,y=1)

4. Variable length parameters

Variable length refers to the number of arguments is not fixed, and the actual parameters are defined by position and by the keyword, for the two forms of variable length, formal parameters corresponding to two solutions to the complete storage of them, respectively, *args,**kwargs

def test(*args):    print(args)test(1,2,3,4,5,5)test(*[1,2,3,4,5,5])    # args=tuple([1,2,3,4,5,5])def test1(x,*args):    print(x)    print(args)test1(1,2,4,5,6,7)def test2(**kwargs):    print(kwargs)test2(name=‘alex‘,age=8,sex=‘F‘)test2(**{‘name‘:‘alex‘,‘age‘:8})def test3(name,**kwargs):    print(name)    print(kwargs)test3(‘alex‘,age=18,sex=‘m‘)def test4(name,age=18,**kwargs):    print(name)    print(age)    print(kwargs)test4(‘alex‘,sex=‘m‘,hobby=‘tesla‘,age=3)def test5(name,age=18,*args,**kwargs):    print(name)    print(age)    print(args)    print(kwargs)test5(‘alex‘,‘a‘,age=34,sex=18,hobby=‘tesla‘)

Global variables and local variables

A variable defined in a subroutine is called a local variable, and a local variable scope is a subroutine that defines the variable.

def change_name(name):    print("before change",name)    name = "Alex li"    age = 23    print("after change", name)name = "alex"change_name(name)print("age", age)运行结果:before change alexafter change Alex liTraceback (most recent call last):  File "/Users/erick/PycharmProjects/oldboy_python/day2/局部变量.py", line 14, in <module>    print("age", age)NameError: name ‘age‘ is not defined

A variable defined at the beginning of a program is called a global variable, and the scope of the global variable is the entire program

When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.

school = "Oldboy edu"def change_name(name):    school = "Mage Linux"    print("before change",name,school)    name = "Alex li"    print("after change", name)name = "alex"change_name(name)print(school)运行结果:before change alex Mage Linuxafter change Alex liOldboy edu

Global variables can be declared in a subroutine via global

school = "Oldboy edu"def change_name(name):    global school    school = "Mage Linux"    print("before change",name,school)    name = "Alex li"    print("after change", name)name = "alex"change_name(name)print("school",school)运行结果:before change alex Mage Linuxafter change Alex lischool Mage Linux

Day3 Python Basics

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.