Python--python basic Knowledge (1)

Source: Internet
Author: User

Python identifiers

In Python, identifiers are composed of letters, numbers, and underscores.

In Python, all identifiers can include English, numeric, and underscore (_), but cannot begin with a number.

Identifiers in Python are case-sensitive.

Identifiers that begin with an underscore are of special significance. A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *";

A double underscore (foo) represents a private member of a class; (__foo) that begins and endswith a double underscore represents a special method-specific identifier for Python, such as init(), which represents the constructor of a class.

Python reserved characters

The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or as any other identifier name.

All Python keywords contain only lowercase letters.

Line and indent

The biggest difference between learning Python and other languages is that Python's code block does not use curly braces ({}) to control classes, functions, and other logical judgments. Python's most distinctive feature is the use of indentation to write modules.

The amount of whitespace indented is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced. As shown below:

ifTrue:    print"True"else:  print"False"

The following code will execute the error:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.pyifTrue:    print"Answer"    print"True"else:    print"Answer"    # 没有严格缩进,在执行时保持  print"False"

Executing the above code, the following error alert will appear:

$ python test.py
File "test.py", line 5
If True:
^
indentationerror:unexpected Indent

indentationerror:unexpected Indent error is the Python compiler is telling you "Hi, man, your file is not in the wrong format, it may be the tab and the space is not aligned", All Python is very strict in format requirements.

If the indentationerror:unindent does not match any outer indentation level error indicates that you are using an inconsistent indentation, there are tab indents, some spaces are indented, instead The same can be done.

Therefore, you must use the same number of indent spaces in a Python code block.

It is recommended that you use a single tab or two spaces or four spaces at each indent level, and remember not to mix

Multi-line statements

A new line is generally used as the Terminator for a statement in a Python statement.

But we can use a slash (\) to divide a line of statements into multiple lines of display, as follows:

                item_three

The statement contains [], {}, or () parentheses do not need to use a multiline connector. The following example:

days = [‘Monday‘‘Tuesday‘‘Wednesday‘,        ‘Thursday‘‘Friday‘]
Python Quotes

Python receives single quotation marks ('), double quotation marks ("), three quotation marks (" ' "" ") to denote a string, and the opening and closing of quotation marks must be of the same type.

Where three quotation marks can be composed of multiple lines, writing the shortcut syntax of multiple lines of text, common language file strings, at a specific location of the file, as a comment.

‘word‘"这是一个句子。""""这是一个段落。包含了多个语句"""
Python comments

A single-line comment in Python starts with #.

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.py# 第一个注释"Hello, Python!";  # 第二个注释

Output Result:

HelloPython!

Annotations can be at the end of a statement or an expression line:

name = "Madisetti" # 这是一个注释python 中多行注释使用三个单引号(‘‘‘)或三个双引号(""")。#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.py‘‘‘这是多行注释,使用单引号。这是多行注释,使用单引号。这是多行注释,使用单引号。‘‘‘"""这是多行注释,使用双引号。这是多行注释,使用双引号。这是多行注释,使用双引号。"""
Python Empty Line

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

Remember: Blank lines are also part of your program code.

Wait for user input

The following program will wait for user input after hitting enter:

#!/usr/bin/pythonraw_input("\n\nPress the enter key to exit.")

In the above code, "\ n" will output two new blank lines before the result output. Once the user presses the key, the program exits.

Show multiple statements on the same line

Python can use multiple statements in the same row, with semicolons (;) split between statements, and here's a simple example:

#!/usr/bin/python‘runoob‘; sys.stdout‘\n‘)

Execute the above code and enter the result:

$ python test.pyrunoob
Multiple statements form a code group

Indenting the same set of statements constitutes a block of code, which we call the code group.

Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group.

We refer to the first line and the following code group as a clause (clause).

The following example:

ifexpression :    expression :     suite  else :     
Command-line arguments

Many programs can perform some operations to see some basic letters, and Python can use the-H parameter to view the Help information for each parameter:

......in as string (terminates option list) -d     : debug output from parser (also PYTHONDEBUG=x) -E     : ignore environment variables (such as PYTHONPATH) -h     
Standard data types

There are several types of data that can be stored in memory.

For example, PERSON.S age is stored as a numeric value and his or her address is alphanumeric characters.

Python has some standard types for defining operations on them and for each of them as a storage method possible.

Python has five standard data types:

  • Numbers (digital)
  • String (String)
  • List (lists)
  • Tuple (tuple)
  • Dictionary (dictionary)
  • Python numbers

    Numeric data types are used to store numeric values.

    They are immutable data types, which means that changing the numeric data type assigns a new object.

    When you specify a value, the number object is created:

    var1 = 1var2 = 10

    You can also use the DEL statement to delete some object references.

    The syntax for the DEL statement is:

    delvar1[,var2[,var3[....,varN]]]]

    You can delete single or multiple objects by using the DEL statement. For example:

    del vardel var_a, var_b

    Python supports four different types of numbers:

  • int (signed integral type)
  • Long (longer integer [can also represent octal and hexadecimal])
  • Float (float type)
  • Complex (plural)
  • Instance

    Examples of some numeric types:

  • Long integers can also use lowercase "l", but it is recommended that you use uppercase "L" to avoid confusion with the number "1". Python uses "L" to display the long integer type.
  • Python also supports complex numbers, which consist of real and imaginary parts, and can be represented by a + BJ, or complex (a, b), where the real and imaginary parts of a complex number are floating-point
  • Python string

    A string or series (string) is a string of characters consisting of numbers, letters, and underscores.

    Generally recorded as:

    s="a1a2···an"(n>=0)

    It is the data type that represents the text in the programming language.

    The Python string list has 2 order of values:

  • Left-to-right index starts at default 0, with a maximum range of 1 less string lengths
  • Right-to-left index default string length 1, maximum range starts with string
  • If you want to get a substring, you can use the variable [head subscript: Tail subscript], you can intercept the corresponding string, where the subscript is starting from 0, can be positive or negative, subscript can be null to take the head or tail.

    Like what:

    ‘ilovepython‘

    S[1:5] The result is love.

    When using a colon-delimited string, Python returns a new object that contains the contiguous content identified with the offset, and the beginning of the left contains the bottom bounds.

    The result above contains the value L of s[1], and the maximum range taken does not include the upper boundary, or the value p of s[5].

    The plus sign (+) is a string join operator, and an asterisk (*) is a repeating operation. The following example:

    #!/usr/bin/python#-*-Coding:utf-8-*-Str=' Hello world! 'PrintStr # Output Full stringPrintStr[0]# The first character in the output stringPrintStr[2:5]# A string between the third and fifth in the output stringPrintStr[2:]# Output A string starting from the third characterPrintStr*2 # output String two timesPrintStr+"TEST" # Output a concatenated string

    The result of the above example output:

    HelloWorld!HllolloWorld!HelloWorld!HelloWorld!HelloWorld!TEST
    Python list

    The list is the most frequently used data type in Python.

    A list can accomplish the data structure implementation of most collection classes. It supports characters, numbers, and even strings that can contain lists (so-called nesting).

    The list is identified by []. Is the most common composite data type of Python. See this code to understand.

    The list of values can also be used to split the variable [head subscript: Tail subscript], you can intercept the corresponding list, from left to right index default 0, starting from right to left index default-1, subscript can be empty to take the head or tail.

    The plus sign (+) is the list join operator, and the asterisk (*) is a repeating operation. The following example:

    #!/usr/bin/python#-*-Coding:utf-8-*-List= [' ABCD ',786,2.23,' John ',70.2]tinylist = [123,' John ']Print List # output Full listPrint List[0]# The first element of the output listPrint List[1:3]# outputs the second to third elementPrint List[2:]# Outputs all elements from the third start to the end of the listPrintTinylist *2 # Output List two timesPrint List+ tinylist# Print a list of combinations

    The result of the above example output:

    [‘abcd‘7862.23‘john‘70.2]abcd[7862.23][2.23‘john‘70.2][123‘john‘123‘john‘][‘abcd‘7862.23‘john‘70.2123‘john‘]
    Python tuples

    A tuple is another data type, similar to a list.

    The tuple is identified with a "()". The inner elements are separated by commas. However, tuples cannot be assigned two times, which is equivalent to a read-only list.

    #!/usr/bin/python#-*-Coding:utf-8-*-Tuple = (' ABCD ',786,2.23,' John ',70.2) Tinytuple = (123,' John ')PrintTuple# output Full tuplePrinttuple[0]# The first element of an output tuplePrinttuple[1:3]# outputs the second to third elementPrinttuple[2:]# Outputs all elements from the third start to the end of the listPrintTinytuple *2 # Output tuple two timesPrintTuple + tinytuple# Print Group of tuples

    The result of the above example output:

    (‘abcd‘7862.23‘john‘70.2)abcd(7862.23)(2.23‘john‘70.2)(123‘john‘123‘john‘)(‘abcd‘7862.23‘john‘70.2123‘john‘)

    The following are tuples that are not valid because tuples are not allowed to be updated. And the list is allowed to be updated:

    #!/usr/bin/python# -*- coding: UTF-8 -*-‘abcd‘7862.23‘john‘70.2 )list‘abcd‘7862.23‘john‘70.2 ]tuple[21000# 元组中是非法应用list[21000# 列表中是合法应用
    Python Meta Dictionary

    The Dictionary (dictionary) is the most flexible built-in data structure type in Python, except for lists. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects.

    The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

    The dictionary is identified with "{}". A dictionary consists of an index (key) and a value corresponding to it.

    #!/usr/bin/python#-*-Coding:utf-8-*-Dict = {}dict[' One '] =" This is one"dict[2] ="This is the"Tinydict = {' name ':' John ',' Code ':6734,' Dept ':' Sales '}Printdict[' One ']# The value of the output key is ' one 'Printdict[2]# The value of the output key is 2PrintTinydict# Output a full dictionaryPrintTinydict.Keys()# output All keysPrintTinydict.Values()# Output All values

    The output is:

    isis two {‘dept‘‘sales‘‘code‘6734‘name‘‘john‘} [‘dept‘‘code‘‘name‘] [‘sales‘6734‘john‘]
    Python Data type conversions

    Sometimes, we need to convert the data-built type into the data type, and you just need to use the data type as the function name.

    The following several built-in functions can perform conversions between data types. These functions return a new object that represents the value of the transformation.

    Python--python basic Knowledge (1)

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.