MindMap Gallery Python study notes (first introduction to Python)
Python concept learning and a preliminary understanding of what Python is. Python is already one of the most streamlined and easy-to-learn programming languages in the world. Python can be run on all major operating systems and computers, and can be used in everything from building web servers to creating desktop applications.
Edited at 2024-10-13 16:11:18CBT cognitive behavioral therapy, cognitive therapy, psychological counseling, CBT basic concept: ideas determine emotions, experience determines ideas, experience requires comparison to be meaningful, and there are individual differences in experience.
Psychological perception, perception is generated on the basis of sensation. It is the response of the human brain to the objective things and overall attributes that directly act on the sensory organs. The introduction is detailed, students in need can save it.
心理學知覺,知覺在感覺的基礎上產生它是人腦對直接作用於感覺器官的客觀事物,整體屬性的反應。介紹詳細,有需要的同學,可以收藏喲。
CBT cognitive behavioral therapy, cognitive therapy, psychological counseling, CBT basic concept: ideas determine emotions, experience determines ideas, experience requires comparison to be meaningful, and there are individual differences in experience.
Psychological perception, perception is generated on the basis of sensation. It is the response of the human brain to the objective things and overall attributes that directly act on the sensory organs. The introduction is detailed, students in need can save it.
心理學知覺,知覺在感覺的基礎上產生它是人腦對直接作用於感覺器官的客觀事物,整體屬性的反應。介紹詳細,有需要的同學,可以收藏喲。
Python study notes (first introduction to Python)
Part 1 Introduction to Programming
Chapter 1 First introduction to Python concepts
What is programming?
Programming refers to writing instructions for a computer to execute.
The instructions that a computer executes are called code.
What is Python?
Python is an open source programming language invented by Dutch programmer Guido van Rossum.
Python is already one of the most streamlined and easy-to-learn programming languages in the world. Python can be run on all major operating systems and computers, and can be used in everything from building web servers to creating desktop applications.
interactive shell
Python comes with a program called IDLE, which stands for Interactive Development Environment. We will enter Python code in IDLE.
The program IDLE is called an interactive shell. You can type Python code directly into it and the program will print out the results.
text editor
Start the IDLE application, click "File" and select "Create New File". A text editor will open.
Code can be written in a text editor and saved for later running.
The difference between text editing and interactive shell
1. Text editors are more suitable for programs that want to save and edit. If you type incorrect code in the interactive shell and cause an error, you must re-enter all the code. With a text editor, just correct and rerun.
2. The output of running the program from a file will be slightly different from that of running the program from an interactive shell. Please note where the program is run from.
Glossary
Programming: Writing commands for a computer to execute.
Code: Instructions written by a programmer for a computer to execute.
Low-level programming languages: Programming languages that are closer to writing instructions in binary (0s and 1s) than high-level programming languages (programming languages that sound more like English).
Assembly Language: A difficult programming language to learn.
High-level programming language: A programming language that sounds more like English than a low-level editing language.
Chapter 2 Programming Overview
Comment: A line (or part) of code written in English or other natural language. There is a special mark at the beginning of the line to tell the language to ignore this line of code. Python uses # to create comments.
The purpose of comments is to explain what the code does.
Comments are only needed when special operations are performed in the code, or when the code is not clear and easy to understand.
Print (print), the program can print anything, as long as you remember to add double quotes.
Lines of code: Python programs are composed of lines of code.
We usually distinguish code by the number of lines of code.
In IDLE, you can open the "Edit" menu and select the "Go to Line" button to jump to the specified line of the program.
In an interactive shell, you can only enter one line of code at a time, and you cannot copy and paste multiple lines of code.
Sometimes a piece of code is longer than one line and can be extended to a new line using triple quotes, parentheses, square brackets or curly brackets.
You can also use backslash\ to wrap the code.
Keywords: Some words with special meanings in programming languages such as Python.
Spacing: Indentation tells the Python interpreter where a block of code begins and ends. The indent distance in Python is always 4 spaces.
data type
Python divides data into different categories, namely data types.
String (str, abbreviation of string), a string is a sequence of one or more characters enclosed in quotation marks.
Integer data (int, the whole process is integer), integer data.
Float, floating-point number, decimal (number with decimal point) data type.
Boolean value (bool, boolean), only has two values: True and False.
None Type, its value is always None, used to indicate missing data.
In Python, each data value is called an object.
An object can be thought of as a data value with 3 properties
Unique identifier: refers to the address in computer memory, which will not change.
Data type: It is the data category to which the object belongs, which determines the properties of the object and will not change.
Value: The data representing the object.
constants and variables
A constant is a value that never changes.
A variable refers to a value that changes.
A variable consists of a one or more character name that is assigned a value using the assignment operator equals sign.
4 principles for variable naming
1. Variable names cannot contain spaces. If you want to use two words in a variable name, add an underscore in between.
2. Only specific letters, numbers and underscores can be used in variable names.
3. Variable names cannot start with numbers.
4. You cannot use Python keywords as variable names.
Grammar (syntax) refers to a set of rules and processes that regulate the structure of sentences in a language, especially the order of words.
Errors and Exceptions
Two types of errors in Python: syntax errors and exceptions.
arithmetic operators
Python divides operators into multiple types, and arithmetic operators are used for simple arithmetic calculations.
Chapter 3 Functions
Function: A compound statement that accepts input, executes instructions, and returns output.
Calling a function means providing the function with the input it needs to execute instructions and return output.
Parameter: Each input to the function is a parameter. When you provide parameters to a function, it is called "function parameter passing".
Required parameters: When the user calls the function, all required parameters must be passed in, otherwise Python will report an exception error.
Optional parameters: Functions are passed in only when needed and are not required to execute the program. If no optional parameters are passed in, the function will use their default values.
Define a function: To create a function in Python, you need to choose a function name and define its parameters, behavior and return value.
Function name: The keyword def tells the Python operator that a function is being defined.
After the def keyword, specify the name of the function. Name selection follows the same rules as variable names.
By convention, function names should not use capital letters, and words should be separated by underscores: like_this.
Parameters: After naming the function, add a pair of parentheses after the name. In the parentheses are the parameters you want the function to accept.
A function can have one or more parameters, or it can accept no parameters. If you define a function that does not require parameters, you only need to leave the parentheses empty when defining the function.
Definition: Add a colon after the parentheses, then wrap and indent 4 spaces. All code after the colon that is indented by 4 spaces is the definition of the function.
Return value: The keyword return specifies the value output when calling the function, which we call the return value of the function.
If you need to use the function return value later in the program, it is recommended to save the function return value in a variable.
The function must contain a return statement. If the function has no return statement, None will be returned.
Syntax: You can call a function using the syntax "[function name]([comma separated arguments])".
Built-in functions: The Python programming language comes with a function library called built-in functions, which can perform various calculations and tasks without any additional work.
len built-in function indicates the length of the returned object, such as the length of a string (number of characters)
str built-in function, str accepts an object as a parameter and returns a new object (string) with data type str
int built-in function, which accepts an object as a parameter and returns an integer object (integer)
The float built-in function accepts an object as a parameter and returns a floating point number object (decimal)
Note:
Parameters passed to str, int or float functions must be convertible to strings, integers or floating point numbers.
The str function accepts most objects as parameters, but the int function can only accept strings or floating point numbers whose content is numeric. The float function can only accept strings or integer objects whose content is numeric.
The input built-in function, mobile phone user information, accepts a string as a parameter and displays it to the user using the program.
The user enters the answer in the shell, and the program saves the answer in a variable.
Reuse functions: Functions can not only be used to calculate and return values, but can also encapsulate the functions we want to use.
Because functions can be reused, using functions can reduce the amount of code.
The functions of the new program are exactly the same as the previous program, but because the functions are encapsulated in a function that can be called at any time as needed, the amount of code is greatly reduced and the readability is improved.
Scope: a very important attribute of variables.
When you define a variable, its scope refers to which parts of the program can read and write to it.
The scope of a variable is determined by where in the program it is defined.
Define a variable outside a function or class
Global scope: It can be read and written anywhere in the program.
Global variable: A variable with global scope.
Define a variable inside a function or class
Local scope: That is, the program can read and write the variable only within the function in which it is defined.
Local variable: A variable with local scope.
A little caution is required in local scopes: the global keyword must be used explicitly and the variables you wish to modify must be negotiated afterwards.
Exception handling: Supports testing error conditions, catching exceptions when errors occur, and then deciding how to handle them.
try clause: contains errors that may occur.
except clause: Contains code that is executed only when an error occurs.
Note: Do not use variables defined by try statements in except statements.
Documentation string (docstring): used to explain function functions and record required parameter types.
Chapter 4 Containers
method
Methods are functions that are closely related to a specified data type.
Methods, like functions, execute code and return results.
Different from functions: methods can only be called on objects.
Parameters can be passed to methods.
Container 1: list (list)
Concept: A list is a container that stores objects in a fixed order.
Representation method: Lists are represented by square brackets ([ ]).
Create list syntax:
Use the list function to create an empty list.
Example: fruit = list( )
Use square brackets ( [ ] ) directly.
Example: fruit = [ ]
If there are objects in the list, they must be separated by commas.
Example: fruit = ["apple","orange","pear"]
List features
The elements in the list are ordered
The order of elements in a list is fixed unless the order of the elements in the list is rearranged.
You can use the append method to add a new element to the list, but the append method always adds the new element to the end of the list.
Example: fruit = ["Apple","Orange","Pear"] fruit.append("Banana") fruit.append("Peach") print(fruit) >>['Apple','Orange','Pear','Banana','Peach']
The index of the elements in the list. The index of the first element is 0, not 1.
Lists can hold any data type.
Lists are mutable. If a container is mutable, objects can be added or deleted from the container.
You can change an element in a list by assigning its index to a new object.
Example: colors = ["blue","green","yellow"] print(colors) colors[2] = "red" print(colors) >>['blue','green','yellow'] >>['blue','green','red']
You can also use the pop method to remove the last element from the list.
Example: colors = ["blue","green","yellow"] print(colors) item = colors.pop( ) print (item) print(colors) >>['blue','green','yellow'] >>'yellow' >>'blue','green']
You cannot use the pop method on an empty list.
You can use the addition operator to merge two lists
Example: colors1 = ["blue", "green", "yellow"] colors2 = ["orange", "pink", "black"] colors1 colors2 >> ['blue', 'green', 'yellow', 'orange', 'pink', 'black']
You can use the keyword in to check if an element is in the list
You can use the keyword not to check if an element is not in the list
Use the function len to get the size of the list (including the number of elements)
Container 2: tuple
Concept: A tuple is a container that stores ordered objects.
Representation method: Use parentheses to represent the ancestor, and commas must be used to separate the elements in the ancestor.
Create tuple syntax:
Use tuple function
Example: my_tuple = tuple( )
Use parentheses directly
Example: my_tuple = ( )
Even if there is only one element in the tuple, a comma needs to be added after the element.
Characteristics of tuple:
You can only create ancestors, you cannot add new elements or modify existing elements.
The element of the tuple can be obtained in the same way as a list, by referencing its index:
Example: dys = ("1984","Brave New World","Fahrenheit 452") dys[2] >>'Fahrenheit 451'
You can use the keyword in to check whether an element is in the ancestor.
You can add the keyword not in the in apology to check whether the element does not exist in the ancestor.
Tuple Purpose: Tuples are very useful when dealing with values that you know will never change, and you don't want other programs to modify them.
Container 3: dictionary
concept: A dictionary is another built-in container for storing objects. They are used to link two objects, key and value. Linking one object to another, also known as mapping, results in a key-value pair. You can add key-value pairs to a dictionary, and then query the dictionary using the key to obtain its corresponding value. But cannot query using value.
Representation method: Dictionaries are represented by curly brackets ( { } ).
Syntax for creating a dictionary:
Create using dict function
Example: my_dict = dict( )
Create directly using curly braces ({ })
Example: my_dict = { }
Key-value pairs can be added directly when creating a dictionary. Both syntaxes above require colons to separate keys and values, and each key-value pair to be separated by commas.
Example: fruit = {"Apple":"Red","Banana":"Yellow"}
Dictionary features:
The dictionary keys are not needed.
Dictionaries are mutable. After creating a dictionary, you can add new key-value pairs using the syntax "[dictionary name] [[key]]" and look up values using the syntax "[dictionary name] [[key]]".
Example: facts = dict ( ) #Add key-value pairs facts ["code"] = "fun" print(facts["code"]) #Add key-value pairs facts ["Bill"] = "Gates" #Find the value corresponding to the key print (facts ["Bill"]) #Add key-value pairs facts["founded"] = 1776 #Find the value corresponding to the key print (facts ["founded"])
Dictionary values can be any objects. But dictionary keys must be immutable. Strings or tuples can be used as dictionary keys, but lists or dictionaries cannot.
You can use keywords to check whether a key is in the dictionary, but you cannot use it to check whether a value is in the dictionary.
Example: bill = dict ({"Bill Gates":"charitable"}) print("Bill Gates" in bill)
Add the keyword not before the keyword in to check whether the key is not in the dictionary.
Use the keyword del to delete a key-value pair from a dictionary.
Example: books = {"Dracula":"Stoker", "1984":"Orwell", "The Trial":"Kafka"} print(books) del books["The Trial"] print(books)
Example of a program using a dictionary:
rhymes = {"1":"fun", "2":"blue", "3":"me", "4":"floor", "5":"live" } n = input("Type a number:") if n in rhymes: rhymes = rhymes[n] print(rhymes) else: print("Not found.")
Container nested container
Containers can be stored within containers.
Glossary
Method: A function closely related to the specified data type.
List: A container that stores ordered objects.
Iterable: An object is iterable if every element in the object can be accessed using a loop.
Iterable objects: Iterable objects such as strings, lists, and elements.
Index: A number that represents the position of an element in an iterable object.
Mutable: The contents of the container can change.
Immutable: The contents of the container cannot be changed.
Dictionary: A built-in container for storing objects, mapping an object called a key to an object called a value.
Key: used to find the corresponding value in the dictionary.
value: The value in the dictionary mapped to the key.
Mapping: Linking one object to another.
Key-value pairs: Keys map to values in a dictionary.
Chapter 5 String Operations
5.1 Triple quoted string
If the string spans more than one line, triple quotes can be used.
If you use single or double quotes to define a string that spans multiple lines, Python will report a syntax error.
5.2 Index
Like lists and tuples, strings are iterable.
The first character in the string is at index 0, and each subsequent index is incremented by 1.
Python also supports the use of negative indexes to find elements in lists: the search year that can be used to find elements in an iterable object from right to left (must be a negative number).
5.3 Strings are immutable
Strings, like tuples, are immutable and the characters in the string cannot be modified.
If you want to modify it, you must create a new string:
Example: ff = "F.Fitzgerald" ff = "F. Scott Fitzgerald"
5.4 String concatenation
You can use the addition operator to combine two or more strings together. The result is a new string composed of the characters in the first string plus the characters in the other strings.
Example: "cat" "in" "hat"
5.5 String multiplication
You can use the multiplication operator to multiply strings and numbers.
Example: "Sawyer" * 3 >>SawyerSawyerSawyer
5.6 Change case
You can use the upper method of a string to change each character in the string to uppercase.
Example: "We hold these truths...".upper( ) >>'WE HOLD THESE TRUTHS...'
You can use the lower method of a string to change each character in the string to lowercase.
Example: "SO IT GOES.".lower( ) >>'so it goes.'
You can use the capitalize method of a string to change the first letter of the string to uppercase.
Example: "four scour and ...".capitalize( ) >>"Four scours and..."
5.7 Formatting
You can use the format method to create a new string, which will replace the "{ }" in the string with the passed-in string.
Example: "William { }".format("Faulkner") >>"William Faulkner"
You can also use the format method to pass variables as parameters:
Example: last = "Faulkner" "William { }".format(last) >>"William Faulkner"
Curly braces ({ }) can be used repeatedly:
Example: author = "William Faulkner" year_born = "1897" "{ } was born in { }."format.(author , year_born) >>"William was born in 1897."
The format method is useful if you want to create a string based on user input:
Example: n1 = input("Enter a noun:") v = input("Enter a verb:") adj = input("Enter a adj:") n2 = input("Enter a noun:") r = """The { } { } the { } { } """.format(n1, v, adj, n2) print(r) >> Enter a noun:
5.8 Split
The split method can be used to split a string into two or more strings.
You need to pass in a string as the parameter of the split method and use it to split the original string into multiple strings.
Example: "I jumped over the puddle. It was 12 feet!".split(".") >>["I jumped over the puddle","It was 12 feet!"]
The split result is a list containing two elements: a string consisting of all characters before the period, and a string consisting of all characters after the period.
5.9 Connection
The join method adds new characters between each character of the string.
Example: first_three = "abc" result = " ".join(first_three) print(result) >>"a b c"
The join method can be called on an empty string or a string containing whitespace characters, passing in a list of strings as arguments, thereby concatenating these strings into a single string.
Example: words = ["The", "fox", "jumped", "over", "the", "fence", "."] one = "".join(words) ones = " ".join(words) print(one) print(ones) >>Thefoxjumpedoverthefence. >>The fox jumped over the fence.
5.10 Remove spaces
Use the strip method to remove whitespace characters at the beginning and end of a string.
Example: s = "The" s = s.strip() print(s) >>The
5.11 Replacement
replace method, the first parameter is the string to be replaced, and the second parameter is the string used to replace. You can use the second string to replace all the same content in the original string as the first string.
Example: equ = "All animals are equal." equ = equ.replace("a","@") print(equ)
5.12 Search index
You can use the index method to get the index of the first occurrence of a string in a string.
Pass in the character you want to find as a parameter, and the index method can return the index of the first occurrence in the string:
Example: print("animals".index("m")) >>3
If you are not sure whether there is a matching result, you can use the following exception handling method:
Example: fruits = ["pear","apple","banana","peach","grape"] n = input("Enter a fruit name:") #Try to find the entered fruit name retrieval try: print(fruits.index(n)) except: print("Not found") >>Enter a fruit name:banana >>2
5.13 in keyword
The keyword in can check whether a string is in another string, and the return result is True or False:
Example: print("Cat" in "Cat in the hat.")
Add the keyword not in front of in to check whether a string is not in another string.
5.14 String escaping
String escaping (escaping) refers to adding a symbol before a character with special meaning in Python to tell Python that the symbol represents a character in this case and has no special meaning.
Escape with backslash in Python.
5.15 Line breaks
Add to the string to indicate a newline:
Example: print("line1 line2 line3") >>line1 >>line2 >>line3
5.16 Slicing
Slicing creates a new iterable object from a subset of elements in an iterable object.
Example: fict = ["Tolstoy", "Camus", "Orwell", "Huxley", "Austin"] print(fict[0:3]) >>['Tolstoy', 'Camus', 'Orwell']
Syntax: [Iterable object] [[Start index: End index]]
The start index is the index at which slicing begins.
The end index is the position of the end index.
Note: 1. A slice includes elements at the starting index position, but does not include elements at the ending index position; 2. If the starting index is 0, then the starting index position can be left blank; 3. If the end index is the index of the last element in the iterable object, you can leave the position of the end index blank; 4. If both the starting index and the ending index are left blank, the original iterable object will be returned.
Chapter 6 Loop
Meaning of loop: Code that does not stop executing until a condition defined in the code is met.
6.1 for loop
Syntax: "for [variable name] in [iterable object name]: [instruction]"
[Variable name]: is the variable name planned to be assigned to the value of each element in the iterable object;
[Instruction]: It is the code to be executed in each cycle.
Function:
A loop that traverses an iterable object.
Example (using a for loop to iterate over list elements): shows = ["GOT", "Narcos", "vice"] for show in shows: print(show) >>GOT >>Narcos >>vice
You can also use for loops to modify elements in mutable and iterable objects.
Example: tv = ["GOT", "Narcos", "Vice"] i = 0 for show in tv: new = tv[i] new = new.upper() tv[i] = new i=1 print(tv) >>['GOT', 'NARCOS', 'VICE']
You can also use a for loop to pass data between mutable iterable objects.
Example: tv = ["GOT","Narcos","Vice"] coms = ["Arrested","Development","friends","Always Sunny"] all_shows = [] for show in tv: show = show.upper() all_shows.append(show) for show in coms: show = show.upper() all_shows.append(show) print(all_shows) >>['GOT', 'NARCOS', 'VICE', 'ARRESTED', 'DEVELOPMENT', 'FRIENDS', 'ALWAYS SUNNY']
6.2 range function
range function: and built-in function that creates a sequence of integers.
grammar:
The range function accepts two parameters: the sequence momentum number and the end number.
The integer sequence returned by the range function contains all integers from the first parameter to the second parameter (excluding the second parameter).
Example (use the range function to create a sequence of numbers and iterate over it): for i in range(1,11): print(i) >>1 ... >>9 >>10
6.3 while loop
while loop: It is a loop that executes code as long as the expression evaluates to True.
Syntax: "while [expression]: [execute code]"
"[expression]" is the expression that determines whether the loop continues.
"[Execution code]" is code that will be executed as long as the loop continues.
Infinite loop: If the expression of a defined while loop always evaluates to True, the loop will not stop executing. A loop that never stops executing is also called an infinite loop.
6.4 break statement
break statement: can be used to terminate the loop.
Whenever Python encounters a break statement, the loop terminates.
Example: qs = ["What is your name?", "What is your fav. color?", "What is your quest?"] n = 0 while True: print("Type q to quit") a = input(qs[n]) if a == "q": break n = (n 1)%3 >>Type q to quit >>What is your name?
Each time through the loop, the program will ask the user a question from the qs list. Among them, n is the index variable. Each loop will assign the value of the expression (n 1)%3 to n, which allows the program to loop through the questions in the qs list.
6.5 continue statement
continue statement: You can use the statement with the keyword continue to terminate the current iteration of the loop and proceed to the next iteration.
Example 1: #Achieve "print all numbers from 1 to 5 except 3" through for loop and continue statement. for i in range (1,6): if i == 3: continue print(i) >>1 >>2 >>4 >>5
When the value of i is equal to 3, the program executes the continue statement, but it will not completely terminate the loop like the break keyword does. Instead, it will continue to the next iteration, skipping other code that should be executed. When i equals 3, Python will execute the continue statement instead of printing 3.
Example 2: #Achieve "print all numbers from 1 to 5 except 3" through while loop and continue statement. i=1 while i <= 5: if i == 3: i=1 continue print(i) i=1 >>1 >>2 >>4 >>5
6.6 Nested loops
Nested Loops: Loops can be combined in many ways.
You can add another loop within a loop, or even add a loop within the added loop.
There is no limit to the number of loops that can be nested within a loop
A loop that contains a loop inside is called an outer loop.
Nested loops are called inner loops
When there are nested loops, the outer loop does not traverse once, and the inner loop traverses all the elements in its iterable object.
Example: #Use two for loops to add all the numbers in one list to all the numbers in the other list list1 = [1,2,3,4] list2 = [5,6,7,8] added = [ ] for i in list1: for j in list2: added.append(i j) print(added) >>[6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12]
For the first loop iterates over each integer in the list list1, the second loop iterates over each integer in its own iterable and adds it to the number in list1 and then adds the result to the list added.
6.7 Glossary
Loop: A section of code that continues to execute until a condition defined in the code is met.
Traversal: Use a loop to access each element in an iterable object.
for loop: A loop used to iterate over iterable objects such as strings, lists, tuples, or dictionaries.
Index variable: The value of the variable is a number that represents the index in the iterable object.
while loop: A loop that continues to execute as long as the value of the expression is True.
Infinite Loop: A loop that never ends.
break statement: A statement with the break keyword, used to terminate the loop.
continue statement: A statement with the keyword continue, used to terminate the current iteration of the loop and enter the next iteration.
Outer loop: A loop that contains nested loops inside.
Inner loop: A loop nested within another loop.
Chapter 7 Modules
The meaning of module:
In order to facilitate reading and checking the program, large programs are divided into multiple files containing Python code, called modules.
7.1 Import built-in modules
Import: Before using a module, you need to import the module first, which means writing code to let Python know where to get the module.
Import syntax: import[module name].
After importing a module, you can use its variables and functions.
Built-in module: It comes with the Python language and contains many important functions.
7.2 Import other modules
Create module
Create a new folder on your computer. In the folder, create a new .py Python file, add code to the .py Python file and report the file.
Import (import) Same as above
7.3 Glossary
Module: Another name for a Python file containing code.
Built-in modules: modules that come with the Python language, including many important functions.
Import: Write code that tells Python where to import the module you plan to use.
Chapter 8 Documentation
8.1 Write file operation
The first step in working with files is to open the file using Python's built-in open function.
The open function has two parameters:
A string representing the path to the file to open.
File path refers to the location of the file on the computer. For example, /Users/bob/st.txt is the file path of the file st.txt. Each word separated by a slash is the name of a folder.
If the file path contains only the name of the file (no slash-separated folders), Python will look for the file in the directory where the currently running program is located.
To avoid errors when the program runs on different operating systems, the built-in os module should be used to create the file path.
os module example: import os os.path.join("Users","bob","st.txt") >>"Users/bob/st.txt
Using the path function to create a file path ensures that it will work properly on any faulty system.
Represents the mode in which the file is opened.
The parameter mode passed into the open function determines what operations are performed on the opened file:
"r" opens the file in read-only mode.
"w" opens the file in write-only mode. If the file already exists, the file will be overwritten. If the file does not exist, a new file is created.
"w "Open the file in readable and writable mode. If the file already exists, the file will be overwritten. If the file does not exist, a new file is created.
The open function returns an object called a file object, which can be used to read/write files.
You can use the write method of the file object to write to the file, and close the file through the close method.
If the file is opened using the open function, it must be closed via the close method.
8.2 Automatically close files
The syntax to open a file using the with statement is: "with open([file path]),[mode]) as [variable name]:[execution code]"
[File path] represents the location of the file
[Mode] represents the mode in which to open the file
[Variable name] represents the variable name assigned to the file object.
[Execution code] is the code that needs to access the file object variables
Example: with open ("st.txt","w") as f : f.write("Hi from Python!")
As long as it is still within the with statement, the file object can be accessed.
8.3 Reading files
If you want to read a file, you can pass "r" as the second parameter of the open function. Then calling the read method of the file object will return an iterable object containing all the lines of the file.
8.4 CSV files
The suffix of the CSV file is .csv, which uses English commas to separate the data (CSV is the English abbreviation of comma separated values).
CSV files are often used by programmers who need to manage reporting software such as Excel.
Each comma-separated data in the CSV file represents a cell in the report, and each row represents a report row.
Delimiter is a symbol used to separate data in CSV files, such as comma or vertical bar "|".
8.5 Glossary
Read: Access the contents of the file.
Write: Add or modify data in the file.
File path: The location on your computer where the file is stored.
with statement: A compound statement that automatically performs an operation when Python exits the statement.
File object: An object that can be used to read and write files.
CSV file: File with .csv suffix, using commas to separate data. Commonly used in programs that manage reports.
Delimiter: The symbol used to separate data in CSV files, such as commas.
Part 2 Introduction to Object-Oriented Programming
Chapter 9 Programming Paradigms
Programming paradigm (program paradigm), that is, programming style.
9.1 Status
One of the fundamental differences between different programming paradigms is the treatment of state.
State is the value of its internal variables when the program is running.
Global state is the value of the internal global variables of the program when it is running.
9.2 Procedural programming
Procedural programming: This programming style requires you to write a series of subsidies to solve a problem, each step changing the state of the program.
In procedural programming, we store data in global variables and process it through functions.
Since the state of the program is stored in global variables, problems may arise if the program grows larger.
Global variables may be used in multiple functions, and it is difficult to record where a global variable has been modified. Can severely damage the data accuracy of the program.
As the program becomes more and more complex, the number of global variables will gradually increase. In addition, the program needs to continuously add new functions and modify global variables, so the program will soon become unmaintainable.
Procedures are side effects of programming, one of which is changing the state of global variables.
9.3 Functional programming
Functional programming: The world's smallest general-purpose programming language.
Functional programming solves the problems that arise in procedural programming by eliminating global state.
Functional programmers rely on functions that do not apply or change global state; the only state they use is the arguments passed to the function.
Advantages and Disadvantages
Advantage: It eliminates all errors caused by global state (global state does not exist in functional programming).
Disadvantages: Some problems are easier to conceptualize through states.
9.4 Object-oriented programming
The object-oriented programming paradigm also solves the problems caused by procedural programming by eliminating global state, but instead of using functions, it uses objects to save state.
A class defines a series of objects that can interact with each other.
Classes are a means for programmers to classify and group similar objects.
Every object is an instance of a class.
When a class is defined, all instances of the class are similar: they all have the attributes defined in the class, but the specific attribute values of each instance are different.
In Python, a class is a compound statement that contains a header and a body.
Syntax: class [class name]: [code body].
[Class name] is the name of the class.
Convention: Class names in Python all start with a capital letter and use camel case naming.
CamelCase nomenclature: that is, if the class name consists of multiple words, the first letter of each word should be capitalized (such as LikeThis, rather than separated by underscores (naming convention for functions)).
[Code body] is the specific code of the defined class.
The body of code in a class can be a single statement, or a compound statement called a method.
Methods are similar to functions, but because they are defined in a class, they can only be called on objects created by the class.
Method names follow the function naming rules, all are lowercase and separated by underscores.
The difference between the way a method is defined and the way a function is defined:
Methods must be defined inside the class;
Must accept at least one argument (except in special cases).
By convention, the first parameter of a method is always named self.
When you create a method, you must define at least one parameter, because when you call a method on an object, Python will automatically pass in the object of the calling method as a parameter.
9.5 Glossary
Programming paradigm: programming style.
Status: The value of the variables within the program when it is running.
Global state: The value of global variables within the program when it is running.
Procedural programming: This programming style requires writing a series of steps to solve a problem, each step changing the state of the program.
Functional programming: Functional programming eliminates global state through function transfer and solves the problems of procedural programming.
Side effects: changing the value of global variables.
Object-oriented: A programming paradigm that defines objects that can interact with each other.
Class: A means for programmers to classify and group similar objects.
Method: Similar to a function, but it is defined in the class and can only be called on objects created by the class.
Instance: Every object is an instance of a class. Each instance of a class has the same data type as other instances of the class.
Instance variables: Variables that belong to an object.
Magic methods: Methods used by Python in special situations, such as object initialization.
Instantiation of a class: Create a new object using a class.
Chapter 10 The Four Pillars of Object-Oriented Programming
concept.
There are four major concepts in object-oriented programming:
encapsulation
Encapsulation includes two concepts.
The first concept, in object-oriented programming, is that an object collects variables (state) and methods (used to change state or perform calculations involving state) in one place - the object itself.
The second concept refers to hiding the internal data of a class to avoid direct access by client code (that is, code outside the class).
abstract
Abstraction refers to the process of "stripping away many characteristics of something so that it retains only its most basic qualities." In object-oriented programming, abstraction techniques are used when using classes to model objects.
Polymorphism
Polymorphism refers to "the ability to provide related interfaces for different basic forms (data types)." Interface refers to functions or methods.
inherit
Inheritance in the programming context is similar to genetic inheritance. When a class is created, the class can also inherit methods and variables from another class.
The inherited class becomes the parent class (parent class)
Inherited classes are called child classes
When a subclass inherits a method from a parent class, we can override the method in the parent class by defining a new method with the same name as the inherited method. The ability of a subclass to change the implementation of methods inherited from a parent class is called method overrding.
Composition: Through the combination technique, one object is saved as a variable in another object, and the "own" relationship can be modeled.
Glossary
The four pillars of object-oriented programming: encapsulation, abstraction, polymorphism, and inheritance.
Inheritance: In the genetic inheritance summary, children will inherit characteristics such as eye color from their parents. Similarly, when a class is created, it can inherit methods and variables from another class.
Parent class: The class that is inherited.
Subclass: A class that inherits from a parent class.
Method overriding: A subclass changes the ability to implement methods inherited from the parent class.
Polymorphism: refers to the ability to provide relevant interfaces for different basic forms (data types).
Abstraction: refers to the process of stripping away many characteristics of something so that it retains only its most basic qualities.
Client code: Code outside the applicable object's class.
Encapsulation: Encapsulation includes two concepts. The first concept is that objects in object-oriented programming collect variables (state) and methods (used to change state or perform calculations involving state) in one place - the object itself. The second concept refers to hiding the internal data of a class from direct access by client code.
Combination: Through the combination technique, one object is saved as a variable in another object, and the "own" relationship can be modeled.
Chapter 11 In-Depth Object-Oriented Programming
11.1 Class variables and instance variables
In Python, classes are objects. Every class in Python is an instance object of the type class.
There are two types of variables in a class:
class variable
Class variables belong to the objects Python creates for each class definition, as well as the objects created by the class itself.
Class variables are defined in the same way as ordinary variables (but must be defined inside the class) and can be accessed through class objects or through objects created using the class.
The access method is the same as that of instance variables (prefixed with self. in the variable name).
Class variables allow data to be shared among all instances of a class without the use of global variables.
instance variable
Instance variables are defined with the syntax self.[variable name]=[variable value].
11.2 is
If the two objects are the same object, the keyword is returns True, otherwise it returns False.
You can check if a variable is None using the keyword is.