This is the 12th day of my participation in the August Challenge
File to read and write
In Python, there are many applications for file manipulation, such as big data, which involves many data processing requests, basically analyzing, extracting, and rewriting data from a single file
How many steps are there to read and write a file? How do you put an elephant in a fridge
Let’s break it down:
- Open file: Used to open a file in Python
open
function
Open (filename,[access_mode],[buffering] filename: indicates the path of the file to be opened. Access_mode: Indicates the mode of opening the file. R is read-only, w is writable, a is writable, etc.. F =open(” song-txt “,”r”,encoding=” utF-8 “) f=open(” song-txt “,”r”,encoding=” utF-8 “)
The open function returns a File object. Only a File object can be used for subsequent read and write operations. Operate on files through handles
Read: FileObject.read ([count]) Count is the number of bytes, not passed by default to read the entire file, when the file is too large we do not recommend reading directly.
Read: fileObject.readline() # read the next line
Read: fileObject.readlines() # Read the entire file into an iterator for us to traverse
Write: fileObject.write(” la \n la la “)
Note: Read/write operations need to look at the open mode set by the open function, whether to read or write
- Close the file
Display off: fileObject.close();
Note: Normally a file object will be closed automatically after exiting the program, but to be safe, we close the file using the close method
Too fussy? Python thinks so too, so it gives us another way to automatically help you close():
with open("song.txt","r",encoding="utf-8") as f: for line in f: print(line)
function
A function is a well-organized, reusable piece of code that implements a single or related function to improve application modularity and code reuse
How to define a function
#sayhi is the name of the function. The parentheses are used to define the parameters required by the function
def sayhi() :
# function body
print("hello world");
sayhi(); The function body will not be executed if it is not called
Copy the code
Parameters of a function
#----------- The first type: the required parameter ------------------
#calc parameter we call parameter (x, y)
def calc(x,y) :
print(x+y);
#1, 2 we call arguments, parameters and arguments must correspond one to one
calc(1.2);
#----------- Second: the default parameter ------------------
def calc(x,y=10) :
print(x+y);
calc(2);# If the second argument is not passed, the default value is 10, if passed, whatever you passed
#----------- Third type: key parameter ------------------
def calc(x,y) :
print("x:",x);
print("y:", y);
calc(y=2,x=1);# Note that when passing a parameter name, the name must be consistent
#----------- Fourth type: variable parameter ------------------
def calc(x,y,*arg) : The arG is an empty tuple if there are no extra arguments
print("x:",x);
print("y:", y);
print("arg:", arg);
calc(1.2."zhangsan".20) X: 1 y: 2 arg: ('zhangsan', 20)
Copy the code
The return value of the function
We can think of a function as a separate box, so how does our outside world communicate with the inside of the box? We can return the desired result from the inside of the box by returning a value.
def calc(x,y) :
return x+y; # Note: A return in the body of a function stops subsequent code execution
print("here") This line will never be executed because the previous line has already returned
sum=calc(1.2);The #calc function has a return value, and something needs to receive the result
print(sum)
Copy the code
Local variables and global variables
- Local variable: A variable defined inside a function can only be used inside the function, not outside it. The scope of this variable is local
- Global variables: Outside of functions, the variable assigned at the beginning of a piece of code can be referenced by multiple functions.
count=1;# global variables
def calc(x,y) :
#count=2; # this count does not change to the global count
# How to modify the global variable count?
global count
count=4; Change to global variables
sum=x+y; #sum is a local variable
print(sum)
calc(1.2)
print(sum) Cannot print because sum is a local variable
print(count)The output is 4
Copy the code
Note: Although we can manipulate global variables inside functions, we do not recommend this change, because of the generality of functions, you do not know where to change global variables.
Recursive function
You call yourself from inside a function, which is called a recursive function, and if you think about it, we all know about recursion, like once upon a time there was a mountain, and there was a temple on the mountain, and in the temple there was an old monk telling a story, what was he telling, once upon a time there was a mountain…
So let’s look at it in code
def say() :
print("Once upon a time, there was a mountain, and there was a temple on the mountain. In the temple, an old monk was telling a story. What was he telling?")
return say()
say()
# Calculate the sum of 1-100 recursively
def Calc(i) :
if i==1:
return 1
else:
return i+Calc(i-1)
print(Calc(100))
# Reverse the string recursively
str = input('Please enter several characters:')
def f(x) :
if x == -1:
return ' '
else:
return str[x] + f(x-1)
print(f(len(str) -1))
Copy the code
Commonly used algorithm
# order search
def search(arr,n) :
for s in arr:
if s==n:
print("Find")
search([1.4.7.8.10.39.2].7)
# binary search
arr=[1.4.7.9.10.20.50]
def FindNumber(low,high,n) :
mid = (low + high)// 2
if arr[mid] == n:
return mid
if n > arr[mid]: # when the value you are looking for is greater than the middle number
return FindNumber(mid+1,high,n)
if n < arr[mid]: # when the value you are looking for is less than the middle number
return FindNumber(low,mid-1,n)
print(FindNumber(0.len(arr),7))
# Optimized version
# arr =,3,6,9,10,20,30 [1]
# def binary_search(data_source,find_n):
# # take the median
# mid=int(len(data_source)/2)
# if len(data_source)>=1:
# if data_source[mid]>find_n: # if the median is greater than the number to be searched, the number to be searched is in the left half
# binary_search(data_source[:mid],find_n)
# elif data_source[mid]
# binary_search(data_source[mid:],find_n)
# else: # The median is equal to the number being looked up
# print(" find: ",data_source[mid])
# else:
# print(" not found ")
# binary_search(arr,10)
# Binary search optimization (2)
# arr =,3,6,9,10,20,30 [1]
# def findnumber(l,h,number):
# mid=(l+h)//2
# if arr[mid]==number:
# print(mid)
# elif arr[mid]
# l=mid
# return findnumber(mid+1,h,number)
# elif arr[mid]>number:
# h=mid
# return findnumber(l,mid-1,number)
# else:
# print(" not found ")
# findnumber (0, len, 30 (arr) - 1)
# Bubble sort
arr=[1.4.2.10.33.99.20.0.100]
# outer loop
for i in range(0.len(arr)-1) :for j in range(0.len(arr)-1-i):
if arr[j]>arr[j+1]:
n=arr[j]
arr[j]=arr[j+1]
arr[j+1]=n
print(arr)
Copy the code
Anonymous functions
Anonymous functions are easy to understand. Anonymous functions have no name and are defined without def
Python uses lambda to create anonymous functions. Lambda is just an expression and the syntax is simple
# Normal function
def calc(x,y) :
return x+y;
# use lambda expressions
n=lambda x,y:x+y #x,y is the required argument, : is the separator x+y is the return value
print(n(2.3))
Copy the code
Using the above code we found that we write less code using lambda expressions to define anonymous functions than def. So when to use anonymous functions:
- Program use once
- Using anonymous functions can save space for variable definitions in memory
- Make your code cleaner
Nested function
Nesting is when you define a function inside a function by def
# function nesting
def outer() :
def inner() :
print('inner')print('outer')
inner()
outer()
inner() Inner is only scoped in outer
# function call
def inner() :
print('inner')
def outer() :
print('outer')
inner();
outer()
Copy the code
The second is that the nested function is only defined internally by def. Writing a function name directly is a function call
Higher-order functions
A function that takes another function as an argument is called a higher-order function
def sayhi() :
print("hello")
def outer(func) :
func();# Execute the function passed in
outer(sayhi) The result is hello
Copy the code
closure
Before we define what a closure is, let’s look at a little bit of code, okay
def outer() :
x = 1
def inner() :
print(x) Output 1 #
return inner
foo = outer()
Copy the code
So let’s read that x is a local variable in outer. When the function inner prints x at 1, the Python interpreter looks inside inner for the corresponding variable, which of course it won’t find, so it looks inside the enclosing scope and finds a match
But what about the lifetime of the variable?
Our variable x is a local variable of function outer, which means that it only exists when the function outer is running. Given what we know about how Python works, we can’t continue calling inner after outer has returned. By the time inner is called, the variable x is already gone, and a runtime error might occur.
To my surprise, the returned function inner worked properly. Python supports a feature called function closures, which in human terms means that a nested function defined in a non-global scope can remember the closed namespace it was in when it was defined. This can be concluded by looking at the func_closure property of the function, which contains values from the closed scope (only captured values, such as x, do not exist in the closed scope if other values are defined in outer).
Remember that inner is redefined every time outer is called. Now the value of x will not change, so the function inner will return the same logic each time. What if we changed it a little bit?
def outer(x) :
def inner() :
print x # 1
return inner
print1 = outer(1)
print2 = outer(2)
print1()
1
print2()
2
Copy the code
A decorator
Decorators are essentially functions (decorators for other functions) that add additional functionality to other functions. A decorator is essentially a closure that takes a function as an argument and returns a replacement function.
There are two principles for using decorators:
- You cannot modify the source code of the decorated function
- You cannot change how decorated functions are called
Based on our understanding of higher-order and nested functions, let’s first try writing a decorator
Define a function
def test1() :
print("in the test 1 ");
Test1 now needs to be extended to meet both of the decorator principles
def main(func) : Test1 =func
def deco() :
print("I'm a new feature.");
func();
print("Me too.");
return deco; #deco is a nested function of main
Test1 cannot be parenthesized
test1=main(test1)
test1()
Copy the code
The code above is decorated with higher-order functions + nested functions. If you can write it more succinctly, Python provides us with a syntax candy
@main Test1 =main(test1)
def test1() :
print("in the test 1 ");
test1()
Copy the code
But what if my function needs arguments? Deco with *args non-fixed arguments.
user,pwd='admin'.'123'
#login is a decorator
def login(func) :
def wrapper(*args) :
username=input("Please enter account number :").strip()
password=input("Please enter your password :").strip()
if(user==username and pwd==password):
print("Login successful")
func(*args)
else:
print("Verification failed")
return wrapper;
@login
def home() :
print("in the home")
home() # Simulate home page access
Copy the code
Finally, how to use a decorator with parameters? @login(parameter) will do
The generator
Data is generated only when called
# generator
generator1 = ( i*i for i in range(10))for i in generator1:
print(i)
# Generator function: Fibonacci sequence
def fib(max) :
n, a, b = 0.0.1
while n < max:
yield b # Since yield is used, it is no longer called a function, but a generator
a, b = b, a + b
n += 1
return 'done'
fib_generator = fib(20)
print(fib_generator)
Copy the code
How is it stored in memory
Let’s take a look at python’s memory storage for variables, functions, and so on
We can see that when we define a variable, we create a space in memory to store our values. We can think of this memory space as a small room in a mansion, so each room has a house number, which is the name in the figure above
? And how do we find the variables by name (house number), function also is same, keep the body of the function in a space, anonymous function is different, there is no house number, so after anonymous function will be recycling system, then the other name and function in the absence of reference will be recycled (that is, when the house number is removed, nobody quotes, Will be recycled by the system).