I recently learned how to get started with Python, so I want to summarize the simple stuff.
Python installation
I'm learning from the fedora system myself, and the way I install Python is:
Just one command to install Python, I use the Python method is only used in vim and Python's command line, there is no Python programming artifact, there is a better editor and the way to recommend.
Once Python is loaded, we start the Python interactive interpreter with the Python command:
Program input and output
Using print in Python for the output of the program, in an example, we assign a string to the variable mystring, first using print to display the contents of the variable, followed by the variable name.
Typically in code, we use Print statements to output variable content, and in the interactive interpreter, you can not only display the variable with the print statement, but also display the variable's original value with the variable name.
Note that when you use only variables, the output string is enclosed in single quotes. This is so that a non-string object can also be string-first on the screen, that is, it shows the object's string representation, not just the string itself. The quotation marks indicate that the value of the variable you just entered is a string.
The print statement calls the STR () function to display the object, and the interactive interpreter calls the REPR () function to display the object.
Using an underscore (_) has a special meaning in the interpreter that represents the value of the last expression.
The print statement can be used in conjunction with the string format operator (%) to implement the string substitution function, which is very similar to the C language.
Program input and Raw _input () built-in functions
The easiest way to get data input from the user is to use the Raw_input () built-in function. It reads the standard input and assigns the read data to the specified variable. You can also use the Int () built-in function to convert a user-entered string to an integer.
The above example is for text input only. Here is an example of entering a numeric string (and converting the string to an int () function):
If you do not use an int () built-in function to convert a string to an integer value, it is treated as a string and can only be mathematically calculated if it is converted to an integer value.
Comments
Python uses the # notation to mark comments, starting with # until the end of a line is a comment.
There is a special note called a document string. You can add a string to the beginning of a module, class, or function to function as an example of an online document:
Unlike regular annotations, a document string can be accessed at run time, or it can be used to automatically generate documents.
Operator
+ - * / // % **
Add, subtract, multiply, divide, and withdraw are standard operators. Python has two division operators, a single slash used as a traditional division, and a double slash used as a floating-point number division (rounding the result). Traditional division means that if two operands are integers, the quotient of the division that it will perform is the largest integer that is smaller than the quotient.
There is also a exponentiation operator, the double star (* *), equivalent to the exponent a ** b 相当于 a^b .
The precedence of the operator is + and-the lowest priority, the *,/,//,% priority, the single-mesh operator + and-priority, and the highest priority of the exponentiation.
Python also has a standard comparison operator, and the comparison operator returns a Boolean value based on the true or false value of the expression.
<, <=, >, >=, = =,! =, <>
Python currently supports two types of non-equal comparison operators! = and <>.
Python also provides a logical operator.
And Or not
Use logical operators to concatenate arbitrary expressions together to get a Boolean value.
The last example is often illegal in other languages, but Python supports expressions that are simple and graceful, but are actually abbreviations for the following expressions:
Variables and Assignments
The variable name is just the identifier for the beginning of a letter-the so-called letter starts with an uppercase or lowercase letter, and also includes an underscore (_). The other characters can be numbers, letters, or underscores. The case of a Python variable is sensitive. In other words, "case" and "case" are two different variables.
Python is a dynamic type language, meaning that you do not need to declare the type of the variable beforehand. The type and value of the variable are initialized at the moment of assignment.
Digital
Python supports five basic numeric types, three of which are integer types.
- Symbolic Shaping
int eg:0101 84
- Long integer type
long eg:29979062458L -841401
- Boolean value
True False
- Floating point number
float eg:3.14159 4.2E-10
- Plural
eg:6.23+1.5j
Python's long integer can be expressed in far more than the long form of the C language, and the Python long Integer is limited to the total virtual memory of the user's computer.
In the long run, the integral type and the long integer are being gradually unified into an integral form. The integer overflow error is never reported, and the result is automatically converted to a long integer type. Perhaps in later versions, two integral types will be seamlessly combined, and the long integer suffix "L" will become dispensable.
The Boolean value is a special integral type. Although a Boolean value is represented by a constant of true and false, if a Boolean value is placed in a numeric context (such as adding true to a number), true is treated as an integral type of 1,false as an integer 0.
String
A string in Python is defined as a character set between quotation marks. Python supports the use of paired single-quote double quotes, with three quotation marks (three consecutive single or double quotes) that can be used to contain special characters.
Python strings usually have single quotes (' ... '), double quotation marks ("..."), three quotation marks ("" "..." "") or ("' ..."), or ("."), enclose a string consisting of multiple lines, which can generally represent a large segment of a descriptive string. There is no difference in use, but double quotes and three quotation marks ("" "" "" "" "" "") can contain single quotation marks, and three quotation marks ("" ... ") can contain double quotes without escaping
Use the index operator ([]) and the Slice operator ([:]) to get substrings. Substrings have their own index rules: The index of the first character is 0, and the index of the last character is-1.
The plus sign (+) is used for the connection of strings, and the asterisk (*) is used for string repetition.
Lists and tuples
Lists and tuples can be treated as normal "arrays", which can hold any number of arbitrary types of Python objects. As well as arrays, elements are accessed through a numeric index starting at 0, but lists and tuples can store different types of objects. 、
There are several important differences between a list and a tuple. The list element is wrapped in brackets ([]), and the number of elements and the value of the element can be changed. Tuple elements are wrapped in parentheses (()) and cannot be changed (in fact their content can).
Tuples can be seen as a list of systems. A subset can be obtained by slicing operations ([] and [:]), which is the same as the way strings are used.
List:
Meta-group:
Dictionary
A dictionary is a mapping data type in Python, consisting of key-value pairs. Almost all types of Python objects can be used as keys, but usually numbers or strings are most commonly used.
The value can be any type of Python object, and the dictionary element is wrapped in curly braces ({}).
code block and indent alignment
Instead of using curly braces, code blocks express code logic through indentation alignment. Because there are no extra characters, the program is more readable. And indentation can clearly express exactly what block of code a statement belongs to. Of course, code blocks can also consist of only one statement.
If statement
The standard if statement syntax is as follows:
if expression if_suite
If the value of the expression is not 0 or the Boolean value True, the code group If_suit is executed, or the next statement is executed. A code group is a Python term that consists of one or more lines of sentences that represent a block of child code. The conditional expression for Python does not need to be enclosed in parentheses.
if expression: if_suiteelif expression2: elif_suiteelse: else_suite
While loop
The syntax of a standard while conditional loop statement is similar to the IF. Again, you use indentation to split each sub-code block.
while expression: while_suite
The statement while_suite is continuously looped until the value of the expression becomes 0 or false, and Python executes the next code. Similar to the IF statement, the conditional expression in Python's while statement does not need to be enclosed in parentheses.
For Loop and range () built-in functions
The For loop in Python is not the same as a traditional for loop (count Loop), which is more like a foreach iteration in a shell script. The for receive in Python can iterate over an object as its argument, iterating over one of the elements at a time.
The print statement defaults to a line break at the end of the print statement. If you add a comma (,) at the end of the print statement, you can change this behavior.
, we find that a space is automatically added between the elements of the print statement output with a comma. By specifying the output format, programmers can control the output layout to the maximum extent, without worrying about these automatically added spaces.
Here we introduce two functions:
- Len (obj) returns the function of the object
- Range ([Start,]stop[,step]) returns an integer list. The start value is start and the end value is Stop-1,start the default value is 0,step the default value is 1
List parsing
List resolution means that we can use a for loop in a row to place all values in a single list:
We can also pick the values that fit the requirements into the list.
Files and built-in functions open (), file ()
We opened the file using the Open function:
- Handle = Open (file_name, Access_mode = ' R ')
The file_name variable contains the corpus we want to open love your string name, Access_mode ' R ' means read, ' W ' means write, ' a ' means add, and so on.
If Open () succeeds, a file object handle is returned. All subsequent file operations must be done through this file handle.
The following code prompts the user to enter a file name, and then opens the files and displays the contents to the screen:
filename = raw_input(‘Enter file name: ‘open‘r‘)forin fobj: print eachLine,fobj.close()
Errors and exceptions
When an error is detected, the Python interpreter has an exception and displays the details of the exception. The programmer can quickly locate the problem and debug it based on this information.
To add code error detection is exception handling, as long as they are encapsulated in a try-except statement. After a try is the code that you intend to manage. The code group after except is the code that handles the error.
try: filename = raw_input(‘Enter file name: ‘) ‘r‘) forin fobj: print eachLine fobj.close()except IOError, e: print‘file open error: ‘
Function
Similar to other languages, functions in Python are called with parentheses (()). Functions must be defined before they are called. If there is no return statement in the function, the None object is returned automatically.
Python is called by reference. This means that changes to the internal parameters of the function affect the original object. However, in fact, only mutable objects are affected by this, and for immutable objects, his behavior is similar to calling by value.
Defining functions
The syntax of a function is defined by the function name followed by the DEF keyword, plus several parameters required by the function. The function arguments are optional, so use parentheses. This statement ends with a colon (:), followed by a code group that represents the overall function.
How to call a function
Note that parentheses that contain parameters cannot be omitted, even if there are no arguments.
Default parameters
The parameters of a function can have a default value, and if provided with a default value, the parameter is provided in the form of an assignment and a sentence. It indicates that when the function call does not provide this parameter, he takes the value as the default value.
Module
A module is a form of organization that organizes Python code that is related to each other into separate files. A module can contain executable code, functions, and classes, or a combination of those things.
When you create a Python source file, the name of the module is the file name without the. py suffix. Once a module is established, it can be used to import the module from another module using an import statement.
How to import Modules
import module_name
How to access module functions or module variables
module_name.function()module_name.var
Learn to get started with Python