Day3 python study notes in week 2, day3python

Source: Internet
Author: User

Day3 python study notes in week 2, day3python

1. String 'str' type, which cannot be modified.

2. Learning about collections:

(1) convert a list to a set: the set is unordered, and duplicate elements are not present in the set.

(2) Set Operations: intersection, union, difference set, symmetric difference set, parent set, subset, add, delete, and evaluate length, but cannot be modified

3. File Operations

(1) file operation process:

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

"2. Operations on files through a handle

"3. close the file

# File Operations
F = open ("B:/Python/PycharmCode/pyDay2/test.txt", "r +") # open the file
Print ("print the first line". center (50 ,"*"))
Print (f. readline () # Read a row
Print ("Remaining Content :")
Print (f. read ())
F. close () # close the file
# If the encoding problem is prompted, you can specify the encoding format when opening the file,
Encoding = UTF-8"

(2) file opening mode:

R: Read-only mode, r +: read/write mode

W: Write-only mode w +: Write-Read mode

A +: append read/write

Rb: Read Binary files, such as video and audio files.

Wb: Write Data to binary files

(3) Common Operations on files:

F. seek () # Move the file pointer in memory to the beginning of the file
Print ("print the first five rows ")
For I in range (5 ):
Print (f. readline ())
F. seek (0, 0)
Print (f. read (10) # read the tenth character after the file pointer starts at the current position
# Print all content
# For line in f. readlines ():
# Print (line. strip () # ignore Spaces

# High bige
Read a row and fetch a row. This method is more efficient and occupies less memory (recommended)

For line in f:
Print (line)
# In this way, the tenth line is not printed, and the rest are printed.
F. seek (0, 0)
I = 0
For line in f:
If I = 9:
Print ("------------ ++ ")
I + = 1
Continue
Print (line)
I + = 1


Print ("do not print the tenth line, and print the rest ")
# Low reads all the data in the large memory, and then wastes memory space in the output (poor)
For index, line in enumerate (f. readlines ()):
If index = 9:
Print ("------------------")
Continue
Print (line. strip ())

Print (f. tell () # display the current pointer location


Print (f. encoding) # Read the file encoding
Print (f. name) # name of the output file
Print ("...............................")
F. seek (0)
F. truncate (10) # file Truncation
Print (f. read ())

F. close () # close the file

4. Simulate printing progress bar Information

# Print progress bar Information
Import sys, time
For j in range (100 ):
Sys. stdout. write ("#")
Sys. stdout. flush ()
Time. sleep (0.2) # delay: 0.2 seconds

5. File Encoding Problems in python

In python2, the default encoding is ASCII, and in python3.x, the default encoding is Unicode.

 
The decode decoding parameter is the original encoding type, and the encode encoding parameter is the new encoding type.
During encoding conversion: Unicode must be used as the intermediary. UTF-8 ----> unicode ---> GBK; gbk ---> unicode ---> UTF-8
Add u before the string to indicate that it is Unicode encoded:Eg.
S = u "hello"
print(s) 
---------------------------------------------------------------------------------------------------------------
Import sysprint (sys. getdefaultencoding () # print the default encoding format s = "Hello, I am Wujian" # In python3, the default encoding is Unicodeprint (s) s1 = s. encode ("UTF-8") # encode the string 'str' type into a bytes packet using encode, and encode it into utf8print ("UTF-8:", s1) s2 = s1.decode ("UTF-8 "). encode ("UTF-8") print (s2) print ("gbk:", s1.decode ("UTF-8 "). encode ("gbk") print (s1.decode ())
 

6. File Content Modification

F = open ("test.txt", "r", encoding = "UTF-8") f2 = open ("test2.txt", "w", encoding = "UTF-8 ") # print (f. read () for line in f: if "Tears me" in line: line = line. replace ("let me shed tears", "Let us shed tears for each other") f2.write (line) else: f2.write (line) f. close () f2.close ()

7. Use with statement: automatically close the file

# With statement, it will automatically close the file with open ("test2.txt", "r", encoding = "UTF-8") as f: for line in f: print (line)

* Tips: when multiple files are opened, the programming specification officially recommended by python is that each line contains no more than 80 characters, and multiple line breaks use "\".

# If one row cannot be written, you can change multiple rows with open ("test.txt", "r", encoding = "UTF-8") as f, \ open ("test2.txt", "r ", encoding = "UTF-8") as f2: for line in f: for line2 in f2: if line2 = line: print (line) f2.seek (0)

8. Three programming paradigms: process-oriented, object-oriented, and functional programming

A simple understanding: the difference between a process and a function in python: A process is a function without return values,

# Process-oriented, object-oriented, functional programming def func1 (): "function instructions: func1 is a process" print ("hello, in the func1") func1 () def func2 (): "func2: A function" print ("in the func2") return 100 print (func2 ())
# Add the current time import timedef log (): # "log: This is a log printing function. "Time_format =" % Y-% m-% d % X "# defines the time style # % Y indicates the four-digit year (000-9999) % m month (01-12) % d in the month of one day (0-31) % X local corresponding time indicates time_current = time. strftime (time_format) with open ("test3.txt", "a +", encoding = "UTF-8") as f: f. write ("% s I'm writing the log now \ n" % time_current) def func3 (): log () func3 () time. sleep (2) def func4 (): log () func4 ()

TIPS: return in python can return multiple values: Different Types of Values

Conclusion: The number of returned values is 0: None.

The number of returned values is 1: object

Multiple return values: tuple tuples

Return value is a function: If printed, It is the address of the function.

9. Details about parameters in python:

# About the parameters in python # parameters: Shape Parameters and real parameters; default parameters, location parameters, keyword parameters, Dictionary parameters def func1 (x, y, z = 99 ): # z is the default parameter: print (x) print (y) print (z) func1 (5, 12) is not required for the default parameter # default position parameter: one-to-one correspondence with the location of the parameter func1 (x = 3, y = 4) # keyword parameter: irrelevant to the order of the parameter func1 (y = 10, x = 20) func1 (8, y = 9) # principle: the keyword parameter cannot be placed before the location parameter func1 (0, z = 25, y = 9) def func2 (* args): # Set a parameter group, multiple parameters can be passed. Convert N keyword parameters into tuples in the print (args) func2 (, 40, "hello", ["momoda ", "memn"]) # by default, func2 (* [1, 2, 3, 4, 5]) is transmitted as a tuples # args = tuple ([1, 2, 3, 4, 5]) def func3 (** kwargs): # dictionary parameter: converts N keyword parameters into a dictionary. print (kwargs) func3 (name = "jean", age = 22, sex = "M") func3 (** {"name": "jean", "age": 22, "sex": "M "}) # You can also retrieve the value def func4 (** kwargs): print (kwargs ["name"]) print (kwargs ["age"]) in the dictionary parameter. print (kwargs ["sex"]) print (kwargs) func4 (name = "Jean Steve", age = 25, sex = "Man ")
 
10. Local variables and global variables
# Description of local variables and global variables # global variables apply to the entire program. Local variables act on a function. # When local variables have the same name as global variables, in the subroutine that defines local variables: local variables take effect; other places: all variables take effect name = "Jean Steve" # global variable school = "SMU" def change_name (name): print ("before name: % s "% name) name =" Huadd "# This function is the scope of the local variable print (" after changed name: % s "% name) # To modify the global variable locally, you must declare global #!!! However, this is not recommended because the function is often called multiple times by other functions, so it is easy to confuse programmers themselves, and it is prone to errors such as global school = "UESTC" change_name (name) print (name) print (school) names = ["Jean", "Rawal", "Rosey"] def change (): names [1] = "Rwwww" # for global variables of the list type, you can directly modify change () print (names) without declaring global in a local function)
11. recursion of functions in python
# Recursive def func (n): while n> = 0: print (n) return func (n-1) func (5) def calculate (n) in python ): "calculate the factorial of a number" while n> 1: return n * calculate (n-1) else: return 1res = calculate (6) print ("the factorial result is:", res)

12. High-order functions: similar to compound functions in mathematics, they are nested with each other.
# High-Order Function def func (a, B, f): res = f (a) + f (B) print (res) # Calculate the sum of the absolute values of two numbers func (-5, 4, abs) # abs absolute value function
 
13. Job

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.