Review of python basic grammar [3] control structure & file operation & Boolean logic

preface

Note: the picture & code comes from the Internet, such as mooc, Songtian teacher python course of Beijing University of technology, etc;

1, Branching structure

1. Basic knowledge

1) Format

if(condition): 
	statements
else: 
	statements

perhaps

if(Condition 1):
	statements
elseif(Condition 2):
	statements
elseif(Condition 3):
	statements
...
else: 
	statements

2) Use

Branch structure is often used for exception handling. When there are too many exceptions, there will be too much code in the exception handling part, which will affect the code reading experience. Using the branch structure to handle exceptions, you can run first and then find errors one by one.

Note:else and finally are optional
try: this part is the code executed first
except: code A executed when this error occurs
else: code executed if there are no errors
finally: a statement executed regardless of whether an error occurs

2, Cyclic structure

1. for loop Foundation

1) Format

for <var> in <sequence> 
	<body>
#Use the loop variable var to traverse every value in the queue, and execute the loop statement once in each loop;

2) Examples

3) Shortcomings

You must know the number of cycles. It is difficult to count when the data is too large. You need a while statement, but you can use the same conditions as branch statements to control the number of cycles;

2. while loop

1) Format

while(condition)
	<body>
#Where < condition > is a Boolean expression;
#<body>Is one or more statements;
#When < condition > is true, execute the loop, which is false, and the loop terminates;

2) Usage & Ex amp les

break usage

continue usage

The branch control condition is implied in the loop statement, and the usage of for/while and else

3) Sentry loop, interactive loop, file loop



Notes:
[1] Interactive loop: make good use of print and input to control, and input itself has some print functions;
[2] Sentinel cycle: condition control with a special sentinel value;
[3] File circulation: avoid repeatedly inputting the same type of data, and process it in the same input text. You don't have to deal with too much input.

3. Boolean logic

(1) In python, the control conditions of if and while are conditional operators "= =! = >" if these conditions are equivalent to Boolean expressions, following Boolean logic 1 or 0, i.e. True or false. The priority is not > and > or, and any non-zero value is True, even if the content is a string;
(2) The or operator guarantees that or is equivalent to an if – else statement.
Explanation:
Program example: the or of the program is equivalent to if judging ans, the control condition is ans true or false, and the value of null or zero is false false. If the input content is not empty, it is true, ans = the input content. Press the enter key directly without inputting the content in the input. If it is empty, it will be false. If the "vanilla" after or is a non empty string, it will be true, and flavor=vanilla.

3, File operation

1. Open operation

1)open function:
<var> = open(<name>,<mode>)
Name is the file path name, and mode is the open mode, both in string format.

Note: pit encountered using the open function
Problem: because the file path copied directly uses "", it may be understood according to the escape, and an error will be reported.
Solution:
Method 1: change "into" / ";
Method 2: add r in front of the string representing the file path

2) Open mode:

Opening files such as video and audio requires binary opening mode

2. Read operation

1)read():
Read the opened file and return all contents in the form of a string;
Note: the file content has multiple lines. At the line break, the string will contain \ n;
2)readline():
Only read the open file, one line of content, and return it in the form of a string;
3)readlines():
\ n each element in the list ends with a new line, and each element in the list represents a new line to be read;
4) The read operation is streaming and should be performed after each use close()

It can be seen that the escape character = = \ n = = only occupies one element bit

3. Write operation

1)write(): writes a string containing text data or binary data blocks to a file
2)writelines(): corresponding to readlines, write the list containing the data to be written into the file, where each element in the list is in the form of string, and the newline \ n will not be automatically added
3) Note that open() opens the file. If it is opened in w write mode. If the file does not exist, it will be automatically created in the current directory; If the file exists, it will be deleted and a new blank file with the same name will be created;
4) After each write, execute close() will update the text content;



Notes:
[1] It can be seen that in the middle of the string, only one line is changed at a time, and the extra \ n is automatically ignored. For example, in Notepad + +, python and 110 are separated by only one line. In fact, two lines are typed in the code;
[2] You can see that multiple at the end \ n are not ignored;
[3] As can be seen from readeline(), the last three \ nread forms belong to three lines;
[4] Question: according to the following text copying program and readlines() output, there should be only six lines of text. Why does Notepad + + display seven lines??? To be continued

4. File operation related functions

map()

1) Format: map(,)
2) Function:
[1] Call function in units of each element in the list;
[2] Realize the conversion from list to string;


As shown in the figure below, you can explain why function is called in the unit of element.

5. eg: text copy

def main():
    #The user directly enters the file name. Note that "r" means that the read file and the program are in the same file directory by default
    #Similarly, in the "w" write mode, a file is created in the same directory of the program by default
    #If the "r" mode is not in the same directory, an error will be reported if the file cannot be found. You must enter the correct path
    #Note that input() returns a string format
    f1=input("Enter a souce file:").strip() #The strip function is of little use, just eliminating the beginning and end
                                            #Shaking hands is just playing more spaces. The default is spaces
                                            #Change the contents in the strip brackets, and you can go to other symbols
    f2=input("Enter a souce file:").strip()
    #Pay attention to the suffix when entering the file name txt or an error will be reported


    #Open file
    infile=open(f1,"r")   #Copied sample source text
    outfile=open(f2,"w")  #Output text to be copied

    #Copy input
    countLines=countChars=0   #Initialize line and word counters
    for line in infile:
        print(line)
        countLines += 1
        countChars += len(line)  #Calculate the number of words in this line of copy
        outfile.write(line)    #Enter the text to be copied in the line you read
    print(countLines, "lines and",countChars,"chars copied")
    infile.close()
    outfile.close()
main()


6. eg: reading text data and drawing

import turtle
#This program is used to draw graphics with turtle according to the data stored in the text as parameters

def main():
#Set the information of the image window
    turtle.title("Data driven dynamic path drawing")
    turtle.setup(800,600,0,0) #Set the window size as 800 * 600 and the center as (0,0)

#Set brush
    pen=turtle.Turtle()
    pen.color("red")
    pen.pensize(5) #With pen Width (5) equivalent
    pen.shape("turtle")#Set the brush shape to turtle
    pen.speed(5)


#Read data file
    result=[]      #Set an empty result list
    file=open('data3.txt','r')
    for line in file:#The simplified traversal file content, read the value returned to line, and the type is string
        result.append(list(map(float,line.split(','))))
    #Note that Chinese commas are used as separators in the text, and Chinese commas should also be entered in split
    #Use split to turn the string read in this line into a list, perform float operation and add it to the empty result list
    #This row of data is only used as an element, which is added to the empty list as a list type
    #Each row of data generates a list and is added to the result as an element
    #result is stored from scratch
    print(result)


#Dynamic rendering
    for i in range(len(result)):#len measures the number of list elements
    #Each row of data in the list is traversed and rendered
    #You can use the matrix concept of array to receive text parameters, debug the brush and start drawing
        pen.color((result[i][3],result[i][4],result[i][5]))
    #If the. color() function uses the rpg value to represent the color, it is not a string format, but a numeric value, but it needs to be enclosed in parentheses
        pen.fd(result[i][0])#Easy to write 0 as 1
        if result[i][1]:#It can be seen that setting the second column representative steering data to 0 and 1 is convenient as a Boolean control condition
            pen.rt(result[i][2])#If it's a right turn, turn left at the third angle
        else:
            pen.lt(result[i][2])
    pen.goto(0,0)
    input("Press Any Key")#Used to prevent the console from closing automatically


main()

7. eg: merge text


4, References

Rookie tutorial
Songtian teacher mooc

Keywords: Python

Added by justoneguy on Sat, 19 Feb 2022 06:32:37 +0200