After reading this article, you can have a certain understanding of Python language characteristics and coding style, and write simple Python programs.
1, Installation and operation
Please refer to the resources for Python installation tutorials of various systems, which will not be repeated here.
Check the python version and enter Python on the command line. At the same time, it will enter the command line interaction mode, where you can execute Python commands.
If Python 2.0 is installed on your computer X and python 3 X two versions, input python, run 2 X version. Want to run 3 x. You need to enter Python 3.
At the command line, enter python:
Solo-mac:~ solo$ python Python 2.7.10 (default, Aug 17 2018, 19:45:58) [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
At the command line, enter Python 3:
Solo-mac:~ solo$ python3 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
Enter exit() to exit command line mode.
Run the python file from the command line
If you have written a python file and want to run it through the command line, enter this directory and enter the python file name on the command line py.
For example, there is a file hello on the desktop Py, the content is to print a sentence:
print("Hello, Python")
To run it, first enter the Desktop directory, and then enter Python hello. Com on the command line Py can run:
Solo-mac:Desktop solo$ python hello.py Hello, Python
2, Variables and simple data types
2.1 variable naming rules
- Variable names can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers. For example, you can name the variable message\_1, but it cannot be named 1\_message.
- Variable names cannot contain spaces, but underscores can be used to separate words. For example, the variable name is greeting\_message works, but the variable name greeting message raises an error.
- Do not use Python keywords and function names as variable names, that is, do not use Python to retain words for special purposes, such as print.
- Variable names should be short and descriptive. For example, name is better than n, student\_name ratio s\_n OK, name\_length ratio\_ of\_ persons\_ Name good.
- Use the lowercase letter l and the uppercase letter O with caution because they may be mistaken for the numbers 1 and 0.
The variable name should be lowercase. Although there is no mandatory provision, the common name rule is agreed.
2.2 string
A string is a series of characters. In Python, strings are enclosed in quotation marks. The quotation marks can be single quotation marks, double quotation marks, or both. For example:
"This is a string." 'This is also a string.' "I love 'python'"
2.2. 1 simple operation of string
The following describes the simple operation of string.
title()
title() displays each word in uppercase, that is, the first letter of each word is changed to uppercase.
>>> name = 'solo coder' >>> name.title() 'Solo Coder'
upper(),lower()
Change the string to all uppercase or all lowercase.
>>> name 'solo coder' >>> name.upper() 'SOLO CODER' >>> name.lower() 'solo coder' >>> name 'solo coder'
Note: title(), upper(), lower() do not change the original string, but output a new string.
2.2. 2 merge (splice) strings
Python uses the plus sign (+) to merge strings.
>>> first = 'solo' >>> last = 'coder' >>> full = first + ' ' + last >>> full 'solo coder'
2.2. 3 use tabs or line breaks to add white space
In programming, white space generally refers to any non printing characters, such as spaces, tabs and line breaks.
To add a tab character to a string, use the character combination \ t, and to add a newline character to a string, use the character combination \ n.
>>> print('\tPython') Python >>> print('Hello,\nPython') Hello, Python
2.2. 4 delete blank
rstrip() deletes the right blank, lstrip() deletes the left blank, and strip() deletes the blank at both ends.
>>> msg = ' Python ' >>> msg ' Python ' >>> msg.rstrip() ' Python' >>> msg.lstrip() 'Python ' >>> msg.strip() 'Python' >>> msg ' Python '
Note that after the space removal command is executed, msg will be printed out, which is the original string, indicating that strip() does not change the original string.
2.2. 5 print statement in Python 2
In Python 2, the syntax of the print statement is slightly different:
>>> python2.7 >>> print "Hello Python 2.7 world!" Hello Python 2.7 world!
In Python 2, you don't need to put what you want to print in parentheses. Technically, print in Python 3 is a function, so parentheses are essential. Some Python 2 print statements also contain parentheses, but their behavior is slightly different from that in Python 3. Simply put, in Python 2 code, some print statements contain parentheses and some do not.
2.3 figures
2.3. 1 integer
In Python, you can add (+) subtract (-) multiply (*) divide (/) integers.
>>> 2 + 3 5 >>> 3 - 2 1 >>> 2 * 3 6 >>> 3 / 2 1.5
Python also supports the order of operations, so you can use multiple operations in the same expression. You can also use parentheses to modify the operation order and let Python perform operations in the order you specify, as follows:
>>> 2 + 3*4 14 >>> (2 + 3) * 4 20
2.3. 2 floating point number
Python calls numbers with decimal points floating-point numbers. Most programming languages use this term, which points out the fact that the decimal point can appear anywhere in a number.
To a large extent, floating point numbers are used without considering their behavior. You just enter the numbers you want to use, and Python usually handles them the way you want:
>>> 0.1 + 0.1 0.2 >>> 0.2 + 0.2 9 0.4 >>>2 * 0.1 0.2 >>>2 * 0.2 0.4
However, it should be noted that the number of decimal places contained in the result may be uncertain:
>>> 0.2 + 0.1 0.30000000000000004 >>> 3 * 0.1 0.30000000000000004
All languages have this problem and there is nothing to worry about. Python will try to find a way to represent the results as accurately as possible, but given the way numbers are represented inside the computer, this is difficult in some cases. More processing methods will be learned later.
2.3. 3 use the function str() to avoid type errors
If you concatenate numbers with strings, you will have a type error. To avoid this problem, you can use str() to convert a number to a string and then operate.
>>> age = 18 >>> print('my age is ' + age) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> print('my age is ' + str(age)) my age is 18
2.3. 4 integer in Python 2
In Python 2, dividing two integers yields slightly different results:
>>> python2.7 >>> 3 / 2 1
Python returned 1 instead of 1.5. In Python 2, the result of integer division only contains the integer part, and the decimal part is deleted. Please note that when calculating the integer result, the method is not rounding, but deleting the decimal part directly.
In Python 2, to avoid this situation, make sure that at least one operand is a floating point number, so the result will also be a floating point number:
>>> 3 / 2 1 >>> 3.0 / 2 1.5 >>> 3 / 2.0 1.5 >>> 3.0 / 2.0 1.5
This division behavior is often confusing when switching from Python 3 to Python 2 or from Python 2 to Python 3. When using or writing code that uses both floating-point numbers and integers, be sure to pay attention to this abnormal behavior.
2.3. 5 notes
In Python, annotations are identified by pound signs (#). Everything after the pound sign is ignored by the Python interpreter. as
# Say hello to everyone print("Hello Python people!")
3, List
A list consists of a series of elements arranged in a specific order.
In Python, lists are represented by square brackets ([]) and elements are separated by commas.
>>> list = [] >>> list.append('haha') >>> list.append('heihei') >>> list.append('hehe') >>> list ['haha', 'heihei', 'hehe'] >>> list[0] 'haha'
You can use - 1 to get the last element. For example, list[-1] is to get the last element, and list[-2] is to get the penultimate element.
3.1 addition, deletion, modification and query of the list
3.1. 1 modify element
Modify the element directly with the index
>>> list[0] = 'nihao' >>> list ['nihao', 'heihei', 'hehe']
3.1. 2 add element
It can be added at the end or inserted anywhere.
Add: append at the end
>>> list.append('wa') >>> list ['nihao', 'heihei', 'hehe', 'wa']
Inserting: insert ing
>>> list.insert(1, 'hello') >>> list ['nihao', 'hello', 'heihei', 'hehe', 'wa']
3.1. 3 delete element
There are three ways to delete:
- del: delete by index
- pop(): deletes the last element of the list and returns the value of the last element. You can also transfer the index to delete the value at any position.
- remove(): delete by value
>>> list ['nihao', 'hello', 'heihei', 'hehe', 'wa'] >>> del list[1] >>> list ['nihao', 'heihei', 'hehe', 'wa'] >>> list.pop() 'wa' >>> list.remove('hehe') >>> list ['nihao', 'heihei']
Pass the index to pop() and delete the values in other locations
>>> list ['nihao', 'heihei'] >>> list.pop(0) 'nihao' >>> list ['heihei']
be careful:
The method remove() deletes only the first specified value. If the value to be deleted may appear multiple times in the list, you need to use a loop to determine whether all such values have been deleted.
If you are not sure whether to use del statement or pop() method, here is a simple criterion: if you want to delete an element from the list and don't use it in any way, use del statement; If you want to continue using the element after it is deleted, use the method pop().
3.2 organization list
This section describes the operations of sorting, reversing, and calculating the length of a list.
There are two main ways to sort lists:
- Permanently sort the list using the method sort()
- Use the function sorted() to temporarily sort the list
3.2. 1 permanently sort the list using the method sort()
Using the sort() method will change the original list. To reverse the sort, simply pass the parameter reverse=True to the sort() method.
>>> list ['zhangsan', 'lisi', 'bob', 'alex'] >>> list.sort() >>> list ['alex', 'bob', 'lisi', 'zhangsan'] >>> list.sort(reverse=True) >>> list ['zhangsan', 'lisi', 'bob', 'alex']
3.2. 2 use the function sorted() to temporarily sort the list
The function sorted() allows you to display list elements in a specific order without affecting their original order in the list.
To reverse the sort, simply pass the parameter reverse=True to sorted().
>>> list = ['douglas','alex','solo','super'] >>> sorted(list) ['alex', 'douglas', 'solo', 'super'] >>> list ['douglas', 'alex', 'solo', 'super'] >>> sorted(list, reverse=True) ['super', 'solo', 'douglas', 'alex'] >>> list ['douglas', 'alex', 'solo', 'super']
3.2. 3 reverse list
To reverse the order of the list elements, use the method reverse(). Reverse () also changes the original list.
reverse() only reverses the original order, without additional alphabetical sorting.
>>> list ['douglas', 'alex', 'solo', 'super'] >>> list.reverse() >>> list ['super', 'solo', 'alex', 'douglas']
3.2. 4 determine the length of the list
Use the function len() to quickly learn the length of the list.
>>> list ['super', 'solo', 'alex', 'douglas'] >>> len(list) 4
3.3 operation list
3.3. 1 cycle
Use the for... in loop.
python distinguishes code blocks by indentation, so you need to indent them correctly
>>> cats ['super', 'solo', 'alex', 'douglas'] >>> for cat in cats: ... print(cat) ... super solo alex douglas
3.3.2 range()
The Python function range() allows you to easily generate a series of numbers.
>>> for value in range(1,5): ... print(value) ... 1 2 3 4
Note: range() produces a series of values that contain the first parameter but not the second.
Create a list using range()
>>> numbers = list(range(1,6)) >>> numbers [1, 2, 3, 4, 5]
range() can also specify the step size. The following example generates an even number from 0 to 11:
>>> nums = list(range(0,11,2)) >>> nums [0, 2, 4, 6, 8, 10]
3.3. 3 simple calculation of list
There are several Python functions dedicated to dealing with numeric lists.
- min(): calculate the minimum value
- max(): calculate the maximum value
- sum(): calculate the sum
>>> numbers [1, 2, 3, 4, 5] >>> min(numbers) 1 >>> max(numbers) 5 >>> sum(numbers) 15
3.3. 4 list analysis
List parsing combines the for loop and the code that creates the new element into one line, and automatically attaches the new element.
>>> squares = [value**2 for value in range(1,11)] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
To use this syntax, first specify a descriptive list name, such as squares; Then, specify an open square bracket and define an expression to generate the value you want to store in the list. In this example, the expression is value ** 2, which calculates the square value. Next, write a for loop to provide a value to the expression, plus the right square brackets. In this example, the for loop is for value in range(1,11), which supplies values 1 to 10 to the expression value ** 2. Note that there is no colon at the end of the for statement here.
3.4 slicing
To create a slice, specify the index of the first and last element to use. Like the function range(), Python stops after reaching the element before the second index you specify. To output the first three elements in the list, you need to specify indexes 0 ~ 3, which will output elements with 0, 1 and 2 respectively.
>>> names = ['aa','bb','cc','dd'] >>> print(names[1:4]) ['bb', 'cc', 'dd']
If you do not specify the first index, Python will automatically start at the beginning of the list:
>>> print(names[:4]) ['aa', 'bb', 'cc', 'dd']
If no termination index is specified, it is automatically fetched to the end of the list
>>> print(names[2:]) ['cc', 'dd']
You can also use a negative index, such as returning the last three elements
>>> print(names[-3:]) ['bb', 'cc', 'dd']
Traversal slice
>>> for name in names[1:3]: ... print(name) ... bb cc
3.5 copy list
You can use tiles to quickly copy lists without specifying a start index and an end index.
>>> names ['aa', 'bb', 'cc', 'dd'] >>> names2 = names[:] >>> names2 ['aa', 'bb', 'cc', 'dd']
The new list copied by slicing is completely different from the original list. Changing one list will not affect the other.
>>> names.append('ee') >>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> names2 ['aa', 'bb', 'cc', 'dd']
If you simply assign names to names2 by assignment, you can't get two lists. In fact, they all point to the same list. If you change one of them, the other will be changed.
>>> names ['aa', 'bb', 'cc', 'dd'] >>> names2 = names >>> names2 ['aa', 'bb', 'cc', 'dd'] >>> names.append('ee') >>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> names2 ['aa', 'bb', 'cc', 'dd', 'ee']
3.6 tuples
Python calls immutable values and immutable lists tuples.
Tuples look like lists, but are identified by parentheses rather than square brackets. Once a tuple is defined, its elements can be accessed using an index, just like a list element.
>>> food = ('apple', 'orange') >>> food[0] 'apple' >>> food[1] 'orange' >>> food[1] = 'banana' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
The traversal usage is consistent with the list.
4, Conditional judgment
The core of each if statement is an expression with a value of True or False, which is called a conditional test.
- Check for equality with==
- Check for inequality, use=
- Number comparison >, <, > =<=
- Multiple conditions and
- Multiple conditions or
Determine whether the list contains an element in
>>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> 'bb' in names True
Determine whether the list does not contain an element
>>> names ['aa', 'bb', 'cc', 'dd', 'ee'] >>> 'ff' not in names True
if statement
Simple if else
>>> a = 10 >>> if a > 10: ... print('hello') ... else: ... print('bye') ... bye
if-elif-else
>>> if a<5: ... print(a<5) ... elif 5<a<10: ... print('5<a<10') ... else: ... print('a>10') ... a>10
5, Dictionary
In Python, a dictionary is a series of key value pairs. Each key is associated with a value, and you can use the key to access the value associated with it. The values associated with keys can be numbers, strings, lists, and even dictionaries. In fact, any Python object can be used as a value in the dictionary.
5.1 addition, deletion, modification and query of dictionary
Use dictionary
In Python, dictionaries are represented by a series of key value pairs placed in curly braces {}.
>>> user = {'name':'bob', 'sex':'male', 'age':20} >>> user {'name': 'bob', 'sex': 'male', 'age': 20}
Accessing values in the dictionary
To get the value associated with the key, specify the dictionary name and the key in square brackets.
>>> user {'name': 'bob', 'sex': 'male', 'age': 20} >>> user['name'] 'bob' >>> user['age'] 20
Add key value pair
A dictionary is a dynamic structure in which key value pairs can be added at any time.
>>> user['city']='beijing' >>> user {'name': 'bob', 'sex': 'male', 'age': 20, 'city': 'beijing'}
Modify values in the dictionary
To modify a value in a dictionary, specify the dictionary name, the key enclosed in square brackets, and the new value associated with the key.
>>> cat = {} >>> cat['color'] = 'white' >>> cat['age'] = 4 >>> cat {'color': 'white', 'age': 4} >>> cat['age'] = 6 >>> cat {'color': 'white', 'age': 6}
Delete key value pair
For information that is no longer needed in the dictionary, you can use the del statement to completely delete the corresponding key value pair. When using the del statement, you must specify the dictionary name and the key to delete.
>>> del cat['color'] >>> cat {'age': 6}
5.2 traversal dictionary
Dictionaries can be used to store information in a variety of ways, so there are many ways to traverse the dictionary: you can traverse all key value pairs, keys, or values of the dictionary.
Traverse all key value pairs (items)
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing'} >>> for k,v in cat.items(): ... print(k + '-' + str(v)) ... age-6 color-white city-beijing
Through for k, v in cat Traverse all key value pairs in the way of items (), k represents the key and v represents the value.
Note: even when traversing the dictionary, the return order of key value pairs is different from the storage order. Python does not care about the storage order of key value pairs, but only tracks the association between keys and values.
Traverse all keys()
If you don't need values, you can use keys() to iterate through all the keys.
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing'} >>> for k in cat.keys(): ... print(k.title()) ... Age Color City
The above example prints out all the keys of cat and capitalizes the first letter of each word with the title() method of the string.
When traversing the dictionary, all keys will be traversed by default, for k in cat Keys() has the same effect as for k in cat.
Traverse all keys in order, sorted by sorted(), which allows Python to list all keys in the dictionary and sort the list before traversal.
>>> for k in sorted(cat.keys()): ... print(k.title()) ... Age City Color
Traverse all values()
>>> for value in cat.values(): ... print(str(value)) ... 6 white beijing
If you need to weed out duplicates, you can use set()
>>> cat {'age': 6, 'color': 'white', 'city': 'beijing', 'city2': 'beijing'} >>> for value in cat.values(): ... print(str(value)) ... 6 white beijing beijing >>> for value in set(cat.values()): ... print(str(value)) ... beijing white 6
5.3 nesting
You can nest dictionaries in lists, lists in dictionaries, and dictionaries in dictionaries. Not here.
6, User input and while loop
6.1 user input
The function input() pauses the program and waits for the user to enter some text. After getting user input, Python stores it in a variable for your convenience.
>>> msg = input('Please input your name: ') Please input your name: solo >>> msg 'solo'
If you are using Python 2.7, you should use the function raw\_input() to prompt the user for input. This function, like input () in Python 3, interprets the input as a string.
Python 2.7 also includes the function input(), but it interprets user input as Python code and tries to run them. If you are using Python 2.7, use raw\_input() instead of input().
If you want to convert the input to numbers, you can convert it with int().
6.2 while loop
The for loop is used to create a code block for each element in the collection, while the while loop runs continuously until the specified conditions are not met.
>>> num = 1 >>> while num <= 5: ... print(str(num)) ... num += 1 ... 1 2 3 4 5
break
To exit the while loop immediately, stop running the rest of the loop, and use the break statement regardless of the result of the conditional test. Break statement is used to control the program flow. You can use it to control which code lines are executed and which code lines are not executed, so that the program can execute the code you want to execute according to your requirements.
continue
To return to the beginning of the loop and decide whether to continue the loop according to the conditional test results, you can use the continue statement, which does not execute the remaining code and exit the whole loop like the break statement.
7, Functions
Python uses the keyword def to define a function. The function name ends with a colon. The indentation after the colon is the function body.
>>> def greet(): ... print('Hello World!') ... >>> greet() Hello World!
7.1 function parameters
You can pass parameters to a function. The following example passes a parameter name to the function greet(). Where name is the formal parameter and solo is the argument.
>>> def greet(name): ... print('Hello,' + name) ... >>> greet('solo') Hello,solo
There are many ways to pass arguments to functions. Positional arguments can be used, which requires that the order of arguments is the same as that of formal parameters; Keyword arguments can also be used, where each argument consists of a variable name and a value; You can also use lists and dictionaries.
Position argument
When you call a function, Python must associate each argument in the function call with a formal parameter in the function definition. For this reason, the simplest association is based on the order of arguments. This association is called a positional argument.
>>> def student(name, age): ... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old') ... >>> student('solo', 18) Hello, My name is solo, I am 18 years old
Arguments passed in the order defined by formal parameters are called positional arguments.
Keyword argument
A keyword argument is a name value pair passed to a function. Keyword arguments let you not consider the order of arguments in the function call, and clearly point out the purpose of each value in the function call.
>>> student(age=18, name='solo') Hello, My name is solo, I am 18 years old
Following the example in the location argument, the first parameter of the student(name, age) method is name and the second parameter is age. We use keyword arguments to indicate which one is passed. Even if the order is written out of order, the results will not be out of order.
Default value
When you write a function, you can specify default values for each formal parameter. When an argument is provided to a formal parameter in the calling function, Python will use the specified argument value; Otherwise, the default value of the formal parameter is used. Therefore, after specifying the default value for the formal parameter, the corresponding argument can be omitted in the function call. Using default values simplifies function calls and clearly indicates the typical usage of functions.
>>> def student(name, age=18): ... print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old') ... >>> student('bob') Hello, My name is bob, I am 18 years old >>> student('nicole') Hello, My name is nicole, I am 18 years old >>> student('bob', 20) Hello, My name is bob, I am 20 years old
As mentioned above, the default value of 18 is set for the second parameter age defined by the student() function. If only one parameter is passed during the call, age is 18 regardless of what is passed. When two parameters are passed, the passed argument overrides the default value.
Note: when using default values, the formal parameters without default values must be listed in the formal parameter list, and then the arguments with default values must be listed. This allows Python to still interpret positional arguments correctly.
7.2 return value
Instead of always displaying the output directly, a function can process some data and return one or a set of values. The value returned by the function is called the return value. In a function, you can use the return statement to return the value to the code line of the calling function. Return values allow you to simplify the main program by moving most of the heavy work of the program into functions.
>>> def student(name): ... return name ... >>> name = student('solo') >>> name 'solo'
Return to dictionary
Function can return any type of value, including more complex data structures such as lists and dictionaries. For example, the following function accepts names and ages and returns a dictionary representing people:
>>> def build_person(name,age): ... person = {'name':name, 'age':age} ... return person ... >>> p = build_person('solo',18) >>> p {'name': 'solo', 'age': 18}
7.3 passing any number of arguments
Sometimes, you don't know how many arguments a function needs to accept in advance. Fortunately, Python allows a function to collect any number of arguments from the calling statement.
>>> def person(*args): ... print(args) ... >>> person('name','age','address') ('name', 'age', 'address')
The above defines a function person(), which has only one formal parameter * args. The asterisk in the formal parameter name * args allows Python to create an empty tuple named args and encapsulate all received values into this tuple.
Use a combination of positional arguments and any number of arguments
If you want a function to accept different types of arguments, you must put formal parameters that accept any number of arguments last in the function definition. Python first matches the position argument with the keyword argument, and then collects the remaining arguments into the last formal parameter.
>>> def person(city, *args): ... print('city: ' + city + ', other args:') ... for value in args: ... print(value) ... >>> person('beijing', 'name', 'age', 'tel') city: beijing, other args: name age tel
The function person() has two formal parameters. The first city is an ordinary location argument, and the second * args is a variable parameter.
Use any number of keyword arguments
Sometimes, you need to accept any number of arguments, but you don't know what information will be passed to the function in advance. In this case, the function can be written to accept any number of key value pairs as many as the call statement provides. An example is to create a user profile: you know you will receive information about the user, but you are not sure what it will be.
def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key,value in user_info.items(): profile[key] = value return profile user = build_profile('steven', 'bob', city='beijing', age=18) print(user)
Execute the code and the output is:
{'first_name': 'steven', 'last_name': 'bob', 'city': 'beijing', 'age': 18}
7.4 import and export
Functions can be stored in a separate file called a module, and then the module can be imported into the main program. The import statement allows the code in the module to be used in the currently running program file.
7.4. 1 import the whole module
The module has an extension of py file containing the code to be imported into the program.
def eat(food): print('I am cat, I eat ' + food)
import cat cat.eat('fish')
console output
I am cat, I eat fish
7.4. 2 import specific functions
You can also import specific functions in the module. The syntax of this import method is as follows:
from module_name import function_name
By separating function names with commas, you can import any number of functions from the module as needed:
from module_name import function_0, function_1, function_2
The above example only imports cat eat() method in PY
from cat import eat eat('fish')
Get the same result.
7.4. 3 use as to assign aliases to functions
If the name of the function to be imported may conflict with the existing name in the program, or the name of the function is too long, you can specify a short and unique alias - another name of the function, similar to a nickname. To assign this special nickname to a function, you need to do so when importing it.
from cat import eat as cat_eat cat_eat('fish')
Set cat The eat() method in py imports and specifies the alias cat_eat, which can be directly used as an alias.
7.4. 4 use as to assign an alias to a module
You can also assign aliases to modules. By assigning a short alias to the module, you can more easily call functions in the module.
General syntax: import module_name as mn
import cat as c c.eat('fish')
7.4. 5. Import all functions in the module
Using the asterisk (*) operator allows Python to import all functions in the module:
def eat(food): print('I am cat, I eat ' + food) def run(): print('cat run')
from cat import * eat('fish') run()
Output results
I am cat, I eat fish cat run
Since each function is imported, each function can be called by name without using period notation. However, when using a large module not written by yourself, it is best not to use this import method: if the name of a function in the module is the same as that used in your project, it may lead to unexpected results: Python may encounter multiple functions or variables with the same name, and then overwrite the functions instead of importing all functions separately.
The best practice is to either import only the functions you need to use, or import the whole module and use the period representation. This makes the code clearer, easier to read and understand.
7.5 function preparation guide
- Function should be given a descriptive name
- Function names should contain only lowercase letters and underscores
- Each function shall contain a comment briefly describing its function, which shall follow the function definition and be in the format of document string.
When specifying default values for formal parameters, there should be no spaces around the equal sign:
def function_name(parameter_0, parameter_1='default value')
This Convention should also be followed for keyword arguments in function calls:
function_name(value_0, parameter_1='value')
- If the program or module contains multiple functions, you can use two empty lines to separate the adjacent functions, which will make it easier to know where the previous function ends and where the next function starts.
- All import statements should be placed at the beginning of the file. The only exception is that comments are used at the beginning of the file to describe the whole program.
8, Class
8.1 creating and using classes
class Cat(): def __init__(self, name, color): self.name = name self.color = color def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') my_cat = Cat('Spring', 'white') print(my_cat.name) print(my_cat.color) my_cat.eat() my_cat.run()
The cat class is created above and my is instantiated_ Cat, and then call the class method eat() and run(). Output results:
Spring white cat Spring color white, now eat cat Spring color white, now run
Functions in a class are called methods__ init__ () is the construction method of the function. Python will automatically run it every time a new instance is created. Note that the constructor name must be specified.
In the above example__ init__(self, name, color) has three formal parameters. The first formal parameter self is essential and must precede other formal parameters. Other formal parameters can be adjusted as needed. Self is a reference to the instance itself, which enables the instance to access the properties and methods in the class.
You can also access the attribute: my directly through the instance_ cat. name. This is not recommended in other languages.
Creating classes in Python 2.7
When creating a class in Python 2.7, you need to make minor changes -- include the word object: in parentheses
class ClassName(object):
8.2 properties of class
8.2. 1 set default values for attributes
Every property in a class must have an initial value, even if the value is 0 or an empty string. In some cases, such as when setting the default value, in the method__ init__ It is feasible to specify such initial value in (); If you do this for a property, you do not need to include a formal parameter that provides an initial value for it.
Redefine Cat and set the default value for the attribute age in the construction method.
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age))
8.2. 2. Modify the value of the attribute
You can modify the value of an attribute in three different ways: directly through an instance and set through a method.
1. Directly modify the value of the attribute
The easiest way to modify the value of a property is to access it directly through an instance.
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age)) my_cat = Cat('Spring', 'white') my_cat.print_age() my_cat.age = 4 my_cat.print_age()
The output result is
cat`s age is 3 cat`s age is 4
The above example directly through my_cat.age = 4 modifies the value of the age attribute.
2. Modify the value of the attribute through the method
Then update the code and add update_ The age () method to modify the properties of the age.
class Cat(): def __init__(self, name, color): self.name = name self.color = color self.age = 3 def eat(self): print('cat ' + self.name + ' color ' + self.color + ', now eat') def run(self): print('cat ' + self.name + ' color ' + self.color + ', now run') def print_age(self): print('cat`s age is ' + str(self.age)) def update_age(self, age): self.age = age my_cat = Cat('Spring', 'white') my_cat.print_age() my_cat.update_age(10) my_cat.print_age()
Run code output:
cat`s age is 3 cat`s age is 10
8.3 succession
When a class inherits from another class, it will automatically obtain all properties and methods of the other class; The original class is called the parent class, and the new class is called the child class. A subclass inherits all the properties and methods of its parent class, and can also define its own properties and methods.
class Animal(): def __init__(self, name, age): self.name = name self.age = age def run(self): print('Animal ' + self.name + ' run') class Cat(Animal): def __init__(self, name, age): super().__init__(name, age) cat = Cat('Tony', 2) cat.run()
Run the program, output:
Animal Tony run
First, the class animal is defined, and then Cat inherits from animal. Animal is called the parent class and Cat is called the child class. Through the output, it can be verified that the subclass inherits the methods of the parent class.
In the construction method of the subclass, the construction method of the parent class must be implemented first: super()__ init__ (name, age).
You can also define your own methods for subclasses or override the methods of the parent class.
class Animal(): def __init__(self, name, age): self.name = name self.age = age def run(self): print('Animal ' + self.name + ' run') class Cat(Animal): def __init__(self, name, age): super().__init__(name, age) def play(self): print('Cat ' + self.name + ' play') def run(self): print('Cat ' + self.name + ' run') cat = Cat('Tony', 2) cat.run() cat.play()
Let's modify the program. The Animal class remains unchanged. The Cat class still inherits Animal, but defines its own method play() and rewrites the parent method run(). Run the program and get the output:
Cat Tony run Cat Tony play
Python2. Inheritance in 7
In Python 2.7, the inheritance syntax is slightly different. The definition of electrocar class is similar to the following:
class Car(object): def __init__(self, make, model, year): --snip-- class ElectricCar(Car): def __init__(self, make, model, year): super(ElectricCar, self).__init__(make, model, year) --snip--
The function super() requires two arguments: subclass name and object self. These arguments are essential to help Python associate parent and child classes. In addition, when using inheritance in Python 2.7, be sure to specify the object in parentheses when defining the parent class.
8.4 import class
When a file is too long, part of the code can be extracted and imported into the main file.
There are several import methods:
Import a single class
If Car Py defines the class Car
from car import Car
Importing multiple classes from a module
If Car Py contains three classes: Car, Battery and electrocar.
Import only one class:
from car import ElectricCar
Import multiple classes separated by commas:
from car import Car, ElectricCar
Import the entire module
You can also import the entire module and use the period notation to access the required classes. This import method is simple and the code is easy to read. Since the code that creates the class instance contains the module name, it will not conflict with any name used in the current file.
import car my_car = car.Car()
Import all classes in the module
To import each class in the module, use the following syntax:
from module_name import *
This import method is not recommended for two reasons.
First of all, if you just look at the import statement at the beginning of the file, you can clearly know which classes the program uses, which will be of great benefit; However, this import method does not clearly indicate which classes in the module you use. This import method can also cause confusion about names. If you accidentally import a class with the same name as other things in the program file, it will cause an error that is difficult to diagnose. This import method is introduced here because although it is not recommended, you may see it in the code written by others.
When you need to import many classes from a module, you'd better import the whole module and use module\_name.class\_name syntax to access the class. When doing so, although the file does not list all the classes used at the beginning, you clearly know where the imported modules are used in the program; You also avoid name conflicts that may arise from importing each class in the module.
9, File and exception
9.1 reading data from files
To use the information in the text file, you first need to read the information into memory. To do this, you can read all the contents of the file at once or step by step one line at a time.
9.1. 1 read the entire file
with open('test.txt') as file_obj: contents = file_obj.read() print(contents)
open() is used to open a file. The parameter is the path of the file.
The keyword with closes the file after it is no longer needed to access it. With with, you just open the file and use it when needed, and Python will automatically close it when appropriate.
The only difference between the output and the original file is that there is an empty line at the end. Why is there such an empty line? Because read() returns an empty string when it reaches the end of the file, and when it is displayed, it is an empty line. To delete the extra empty lines, use rstrip() in the print statement.
File paths can be relative or absolute.
9.1. 2 read line by line
with open('test.txt') as file_obj: for line in file_obj: print(line.rstrip())
To check the file one line at a time, use the for loop on the file object.
9.2 writing files
with open('test.txt', 'w') as file_obj: file_obj.write("I love python")
In this example, when calling open(), two arguments are provided, and the first one is the name of the file to be opened. The second argument ('w ') tells Python that we want to open the file in write mode.
Optional mode:
- r: Read only.
- w: write only. If the file does not exist, it is created. If the file exists, it is emptied before writing.
- a: In append mode, the written content is appended to the original file. If the file does not exist, it is created.
- r +: readable and writable.
If you omit the mode arguments, Python will open the file in the default read-only mode.
9.3 abnormality
Exceptions are handled using the try exception code block. The try except code block lets Python perform the specified operation and tells Python what to do when an exception occurs.
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
else code block
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") else: print("no exception")
If the code in try runs successfully without exception, execute the code in else code block.
9.4 storing data with json
Using json. XML in Python Dump () and json Load () to store and read json files.
import json userInfo = {'username': 'jack', 'age': 18} with open('test.txt', 'w') as obj: json.dump(userInfo, obj) with open('test.txt') as obj: content = json.load(obj) print(content)
In the above example, JSON Dump () stores the data in test Txt, and JSON Load() takes the data from the file and prints it.
Note that the json module should be imported before use.
10, Unit test
First define a function name that splices names_ function. py
def get_formatted_name(first, last): full_name = first + ' ' + last return full_name.title()
Then write a test class to test this function
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): def test_name_function(self): full_name = get_formatted_name('david', 'alex') self.assertEqual(full_name, 'David Alex') unittest.main()
The test class should inherit unittest Testcase, through self Assertequal asserts whether the result is equal to the expected result.
Common assertion methods
method | purpose |
---|---|
assertEqual(a, b) | Verify a == b |
assertNotEqual(a, b) | Verify a= b |
assertTrue(x) | Verify that x is True |
assertFalse(x) | Verify that x is False |
assertIn(item, list) | Verify that the item is in the list |
assertNotIn(item, list) | Verify that the item is not in the list |
setUp() method
If you include the method setUp() in the TestCase class, Python will run it first, and then run each to test\_ The way to start.
It is usually used for some initialization operations.
summary
python's language features and coding style are relatively easy to understand and basic. This article is only a foreshadowing for learning python in the early stage. You mainly need to learn how to use it well. Similarly, this is also a process and a good start.
This article is transferred from https://juejin.cn/post/6844903765410070535 , in case of infringement, please contact to delete.