coding

By default, Python 3 source files are encoded in UTF-8 and all strings are Unicode strings. Of course, you can also specify a different encoding for the source file:

– coding: cp-1252 –

The above definition allows the use of character encodings from the Windows-1252 character set in source files. The appropriate languages are Bulgarian, Beloese, Macedonian, Russian, and Serbian.

identifier

The first character must be an alphabetic letter or underscore _.

The rest of the identifier consists of letters, numbers, and underscores.

Identifiers are case-sensitive.

In Python 3, Chinese variable names are allowed, and non-ASCII identifiers are allowed.

Python reserved words

Reserved words are keywords, and we cannot use them as any identifier names. Python’s standard library provides a keyword module that prints all the keywords in the current version:

import keyword>>> keyword.kwlist[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

annotation

In Python, single-line comments start with #, as shown in the following example:

Instance (Python 3.0 +)

#! /usr/bin/python3 # print (“Hello, Python! # second comment

Execute the above code and the output is:

Hello, Python!

Multi-line comments can use multiple # signs, as well as ” and “” :

Instance (Python 3.0 +)

#! /usr/bin/python3 # first comment # second comment “” third comment

Fourth note “”” “fifth note

Print (“Hello, Python!” )

Execute the above code and the output is:

Hello, Python!

Line and indented

Python’s most distinctive feature is the use of indentation to represent blocks of code without the use of curly braces {}.

The number of indent Spaces is variable, but statements in the same code block must contain the same number of indent Spaces. Examples are as follows:

Instance (Python 3.0 +)

if True:

print ("True")else:

print ("False")
Copy the code

The last line of the following code does not indent the same number of Spaces, resulting in a runtime error:

The instance

if True:

print (“Answer”)

print (“True”)

else:

print (“Answer”)

Print (“False”) # print (“False”

The following error may occur after execution:

File “test.py”, line 6 print (“False”) unindent does not match any outer indentation level

Multi-line statement

Python usually writes a single statement on one line, but if the statement is long, we can use a backslash () to implement multi-line statements, for example:

total = item_one + \

    item_two + \

    item_three
Copy the code

Multi-line statements in [], {}, or () do not require a backslash (), for example:

total = [‘item_one’, ‘item_two’, ‘item_three’, ‘item_four’, ‘item_five’]

Number type

There are four types of numbers in Python: integers, Booleans, floats, and complex numbers.

Int (integer), such as 1, has only one integer type int, which is represented as a Long integer. There is no Long in Python2.

Bool (Boolean), as True.

Float (float), e.g. 1.23, 3e-2

Complex, e.g.1 + 2j, 1.1 + 2.2j

String (String)

Single and double quotation marks are used exactly the same in Python.

Use triple quotes (“” or “””) to specify a multi-line string.

Escape character ‘

Backslashes can be used to escape, and r prevents backslashes from escaping. If r”this is a line with \n”, \n will display, not a newline.

Cascading strings such as “this “, “is “, and “string” are automatically converted to “this is string”.

Strings can be concatenated with the + operator and repeated with the * operator.

Strings in Python are indexed in two ways, starting with 0 from left to right and -1 from right to left.

Strings in Python cannot be changed.

Python has no separate character types; a character is a string of length 1.

The syntax for intercepting a string is as follows: variable [header subscript: tail subscript: step]

This is a sentence. Paragraph = “”” This is a paragraph,

Can be multiple lines “””

Instance (Python 3.0 +)

#! /usr/bin/python3 STR =’Runoob’ print(STR [0:-1]) print(STR [0]) # print(STR [0]) # print(STR [0]) # print(STR [0]) # Print (STR [2:5]) # print(STR [1:5:2]) # print(STR [1:5:2]) # print(STR [1:5:2] The output from the second to fifth and every two characters print (STR * 2) # output string two print (STR + ‘hello’) # connection string print (‘ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – ‘) Print (‘hello\nrunoob’) # Print (r’hello\nrunoob’) # Print (r’hello\nrunoob’) # Print (r’hello\nrunoob’) #

The r here refers to raw, i.e. raw string, which automatically escapes the backslash, for example:

Print (‘\n’) # print(‘\n’) # print(‘\n’) # print(‘\n’) # print(‘\n’) # print(‘\n’) #

The output of the above example is as follows:

RunoobRunooR

noo

noob

UoRunoobRunoobRunoob hello — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — hello

runoob

hello\nrunoob

A blank line

A blank line separating functions or methods of a class indicates the beginning of a new code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.

Unlike code indentation, blank lines are not part of Python syntax. Write without inserting blank lines, and the Python interpreter runs without error. However, blank lines are used to separate two pieces of code with different functions or meanings for future maintenance or refactoring.

Remember: blank lines are part of the program code.

Waiting for user input

Execute the following program to wait for user input after pressing enter:

Instance (Python 3.0 +)

#! /usr/bin/python3 INPUT (“\n\n Press Enter and exit.” )

In the above code, “\n\n” prints two new blank lines before output. Once the user presses enter, the program exits.

Multiple statements are displayed on the same line

Python can use multiple statements on the same line, with semicolons (;) between them. Here is a simple example of splitting:

Instance (Python 3.0 +)

#! /usr/bin/python3 import sys; x = ‘runoob’; sys.stdout.write(x + ‘\n’)

Execute the above code with the script, and the output is:

runoob

Using the interactive command line, the output is:

import sys; x = ‘runoob’; sys.stdout.write(x + ‘\n’)runoob7

7 represents the number of characters.

Multiple statements constitute code groups

The indenting of the same set of statements forms a code block, called a code group.

Compound statements such as if, while, def, and class begin with a keyword and end with a colon (:), followed by one or more lines of code that form a code group.

We call the first line and the following group of code a clause.

Examples are as follows:

if expression :

suiteelif expression :

suite else :

suite

The print output

Print defaults to newline output. If you want to implement non-newline output, end=”” :

Instance (Python 3.0 +)

#! / usr/bin/python3 x = “a” y = “b” # output print a newline (x) print (y) print (” — — — — — — — — – ‘) # not print a newline output (x, end = “”) print (y, end=” ” )print()

The execution results of the above examples are as follows:

a

b———a b

The import with the from… import

Use import or from in Python. Import to import the corresponding module.

Import the entire module (somemodule) in the format: import somemodule

Import a function from a module in the format: from somemodule import someFunction

Import multiple functions from a module in the format: From somemodule import FirstFunc, secondFunc, thirdFunc

Import all functions in a module in the format from somemodule import *

Importing the SYS Module

Import sysprint (‘ = = = = = = = = = = = = = = = = Python import mode = = = = = = = = = = = = = = = = = = = = = = = = = = ‘) print (‘ command line parameters: ‘) for the I in sys. Argv:

Print (I)print ('\n python path ',sys.path)Copy the code

Import sys module argv,path member

From sys import argv,path # import specific member print(‘================python from Import = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = ‘) print (# ‘path: the path) as members of the import path already, so I don’t need to quote with sys. Path

Command line arguments

Many programs can perform operations to view basic information. Python can use the -h argument to view help information about each argument:

$ python -h

usage: python [option] … [-c cmd | -m mod | file | -] [arg] … Options and arguments (and corresponding environment variables):-c cmd : program passed in as string (terminates option list)-d : debug output from parser (also PYTHONDEBUG=x)-E : ignore environment variables (such as PYTHONPATH)-h : print this help message and exit[ etc. ]

Refer to the website: www.runoob.com/python/pyth…