Python Basic Syntax 1

Source: Internet
Author: User
Tags bitwise first string integer division natural string

Python basic Syntax (i)

Features of Python

1. Simple

Python is a language that represents simple thinking.

2. easy to learn

Python has a very simple syntax.

3. free, open source

Python is one of the floss (free/open source software).

4. high-level language

Using Python to write a program does not need to consider how to manage the underlying details of the memory used by the program.

5. Portability

Python has been ported to a number of platforms, including Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, as/400,

BeOS, os/390, z/OS, Palm OS, QNX, VMS, Psion, Acom RISC OS, VxWorks, PlayStation, Sharp Zaurus,

Windows CE even has pocketpc.

6. Explanatory

Can be run directly from the source code. Inside the computer, the Python interpreter translates the source code into an intermediate form of bytecode, which is then translated into the machine language used by the computer.

7. Object-oriented

Python supports both process-oriented programming and object-oriented programming.

8. Extensibility

Some programs can be written in a different language, such as A/C + +.

9. can be embedded type

Python can be embedded in a C + + program to provide scripting functionality.

the Rich library

The Python standard library is really huge. It can help you with all kinds of work, including regular expressions, document generation, unit tests, threads, databases, Web browsers, CGI, FTP,

e-mail, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interface), TK, and other system-related operations.

---------------Split Line------------------------The following is the basic syntax for Python---------------------------------------------------------

First, the basic concept

1. There are four types of Python: integers, long integers, floating-point numbers, and complex numbers.

    • integers, such as 1
    • Long integers are relatively large integers.
    • Floating-point numbers such as 1.23, 3E-2
    • Complex numbers such as 1 + 2j, 1.1 + 2.2j

2. String (sequence of characters)

    • The single and double quotation marks in Python are used exactly the same.
    • Use the quotation marks ("' or" ") to specify a multiline string.
    • Escape character ' \ '
    • Natural string, by adding R or R before the string. such as R "This was a line with \ n \" will be displayed, not newline.
    • Python allows processing of Unicode strings, prefixed with u or u, such as u "This is a Unicode string".
    • The string is immutable.
    • The literal cascading string, such as "This" and "is" and "string", is automatically converted to this is string.

  3. Naming of identifiers

    • The first character must be a letter in the alphabet or an underscore ' _ '.
    • The other parts of the identifier are composed of letters, numbers, and underscores.
    • Identifiers are case sensitive.

  4. Objects

Any "thing" in a python program becomes an "object".

  5. Logical lines and physical lines

The physical line is what we see when we write the program, and the logical line is what Python sees.

A semicolon in Python, which identifies the end of a logical line, but in practice typically writes only one logical line per physical line, avoiding the use of semicolons.

A logical line can be written in multiple physical rows, as follows:

s = "Peter is \"
Writing this article "

The use of the above \ is known as ' explicit line connection ', as well as:

Print \
"Peter"

6. Indent

White space in Python is very important, the beginning of the white space is the most important, also known as indentation. Whitespace (spaces and tabs) at the beginning of a line is used to determine the indentation level of logical lines, which determines the statement

Group. This means that statements at the same level must have the same indentation, and each set of such statements is called a block.

Note: Do not use a mix of spaces and tabs to indent because they do not work correctly across different platforms.

Second, operator and expression

1. Operators and their usage

operator name Description Example
+ Add Two objects added 3 + 5 get 8. ' A ' + ' B ' gets ' ab '.
- Reducing Get negative numbers or one number minus another number -5.2 Gets a negative number. 50-24 get 26.
* By Two number multiplied or returns a string that is repeated several times 2 * 3 gets 6. ' La ' * 3 get ' lalala '.
** Power

Returns the Y power of X

3 * * 4 gets 81 (i.e. 3 * 3 * 3 * 3)
/ Except x divided by Y 4/3 get 1 (integer division to get an integer result). 4.0/3 or 4/3.0 get 1.3333333333333333
// Take the Divide Returns the integer part of the quotient 4//3.0 Get 1.0
% Take the mold Returns the remainder of a division 8%3 gets 2. -25.5%2.25 gets 1.5
<< Move left Shifts a number of bits to the left by a certain number (each number in memory is represented as a bit or binary number, i.e. 0 and 1) 2 << 2 get 8. --2 is represented as 10 by bit
>> Move right To shift a number of bits to the right by a certain number >> 1 got 5. --11 is represented as 1011 by bits, and 1 bits to the right is 101, which is the decimal 5.
& Bitwise-AND Number of bitwise AND 5 & 3 Get 1.
| Bitwise OR The number of bitwise OR 5 | 3 Get 7.
^ Bitwise XOR OR The bitwise XOR of the number 5 ^ 3 Get 6
~ Rollover by bit The bitwise rollover of X is-(x+1) By 6.
< Less than Returns whether x is less than Y. All comparison operators return 1 for true, and return 0 for false. This distinction is equivalent to the special variable true and false. Note that these variable names are capitalized. 5 < 3 returns 0 (that is, false) and 3 < 5 returns 1 (that is, true). The comparison can be arbitrarily connected: 3 < 5 < 7 returns TRUE.
> Greater than Returns whether x is greater than Y 5 > 3 returns TRUE. If the two operands are numbers, they are first converted to a common type. Otherwise, it always returns false.
<= Less than or equal Returns whether x is less than or equal to Y x = 3; y = 6; X <= y returns True.
>= Greater than or equal Returns whether x is greater than or equal to Y x = 4; y = 3; X >= y returns True.
== Equals Compare objects for Equality x = 2; y = 2; x = = y returns True. x = ' str '; y = ' StR '; x = = y returns false. x = ' str '; y = ' str '; x = = y returns True.
!= Not equal to Compares two objects for inequality x = 2; y = 3; X! = y returns True.
Not Boolean "Non" If x is true, returns false. If x is False, it returns true. x = True; Not Y returns false.
and Boolean "and" If x is False,x and Y returns false, it returns the computed value of Y. x = False; y = True; X and Y, which returns false because X is false. In this case, Python does not calculate y because it knows that the value of this expression is definitely false (because X is false). This phenomenon is called short-circuit calculation.
Or Boolean "or" If x is true, it returns true, otherwise it returns the computed value of Y. x = True; y = False; X or Y returns true. Short-circuit calculations are also available here.

2. Operator precedence (low-to-high)

operator Description
Lambda Lambda expression
Or Boolean "or"
and Boolean "and"
Not X Boolean "Non"
In,not in Member Test
Is,is not Identity testing
<,<=,>,>=,!=,== Comparison
| Bitwise OR
^ Bitwise XOR OR
& Bitwise-AND
<<,>> Shift
+,- Addition and subtraction
*,/,% Multiplication, division and redundancy
+x,-x PLUS sign
~x Rollover by bit
** Index
X.attribute Property Reference
X[index] Subscript
X[index:index] Addressing segment
F (Arguments ...) Function call
(Experession,...) Binding or tuple display
[Expression,...] List display
{Key:datum,...} Dictionary display
' Expression,... ' String conversions

3. Python console output using print

Print "ABC"  #打印abc并换行
Print "abc%s"% "D" #打印abcd
Print "abc%sef%s"% ("D", "G") #打印abcdefg

Third, control flow

  1. If statement

i = 10
n = Int (raw_input ("Enter a number:"))

if n = = I:
print "Equal"
Elif N < i:
Print "Lower"
Else
Print "Higher"

2. While statement

While True:
Pass
Else
Pass
#else语句可选, the Else statement is executed when the while is false. Pass is an empty statement.

  3. For loop for: Inch

For I in range (0, 5):
Print I
Else
Pass
# Print 0 to 4

NOTE: The Else statement is executed when the For loop is finished;

Range (A, B) returns a sequence, starting from A to B, but excluding the b,range default step of 1, which specifies the step size, range (0,10,2);

  4. Break statement

Terminates the loop statement, and if terminated from for or while, any else that corresponds to the loop will not execute.

  5. Continue statements

The continue statement is used to adjust the remaining statements of the current loop, and then proceed to the next round of loops.

Iv. functions

The function is defined by def . The DEF keyword follows the identifier name of the function, followed by a pair of parentheses, which can contain variable names, which end with a colon, followed by a statement, the function body.

Def sumof (A, B):
Return a + b

  1. Function parameters

The parameter name in the function is ' formal parameter ', and the value passed when the function is called ' argument '

  2. Local Variables

A variable defined within a function has no relation to other variables that have the same name outside the function, that is, the variable name is local to the function. This is called the scope of the variable.

Global statement that uses the global statement to define variables that are outside the function.

def func ():
Global X
Print "x is", X
x = 1

x = 3
Func ()
Print X

#3

  3. Default parameters

Some parameters of the function can be ' optional ' by using the default parameters.

Def say (msg, times =  1):
Print msg * times

Say ("Peter")
Say ("Peter", 3)

Note: Only those parameters at the end of a formal parameter list can have default parameter values, that is, you cannot declare a formal parameter with a default value when declaring a function parameter, but only because the value assigned to the parameter is assigned according to the position.

  4. Key parameters

If a function has many parameters and now only wants to specify the part, then you can assign a value (called a ' key parameter ') by naming these parameters.

Pros: You don't have to worry about the order of the parameters, making the function easier; Assuming that other parameters have default values, you can assign values to only those parameters we want.

def func (A, b=2, c=3):
Print "A is%s, and B is%s, and C is%s"% (A, B, c)

Func (1) #a is 1, and B is 2, and C is 3
Func (1, 5) #a is 1, and B is 5, and C is 3
Func (1, C = ten) #a is 1, and B is 2, and C is 10
Func (c = d, a = 2) #a is a, and B is 20, and C is a-d.

  5. Return statement

The return statement is used to return from a function, that is, to jump out of a function. You can return a value from a function.

A return statement with no return value is equivalent to return none. None means that there is no special type for anything.

  6. Docstrings (document String)

def func ():
' This is self-defined function

Do nothing ""
Pass

Print func.__doc__

#This is self-defined function
#
#Do Nothing

Five, module

A module is a file that contains all of the functions and variables you define, and the module must have a. py extension. The module can ' enter ' (import) from other programs to take advantage of its functionality.

Import the other modules in the Python program using ' import ', the imported module must be in the directory listed in Sys.path, because the Sys.path first string is the empty string "is the current directory, so the program can import the current directory of the module.

1. Byte-compiled. pyc Files

The import module is time consuming, and Python is optimized so that the import module is faster. One way is to create a byte-compiled file with a. pyc extension.

PYC is a binary file, which is a byte code generated by the py file and is a cross-platform (platform-independent) bytecode that is executed by a Python virtual machine, similar to

The concept of a Java or. NET virtual machine. The content of the PYC is related to the Python version, and the PYC files are different when the versions are compiled.

  2. From: Import

If you want to use the variable or other of other modules directly, do not add ' module name +. ' Prefix, you can use the From: Import

For example, you would like to use the Argv,from sys import argv or from sys import of SYS directly *

  3. __name__ of the module

Each module has a name, the py file corresponding module name defaults to the Py file name, can also be assigned to the __name__ in the py files, if it is __name__, this module is the user

Run separately.

  4. Dir () function

DIR (SYS) returns a list of the names of the SYS modules, or DIR () if the parameter is not supplied, and the list of defined names in the current module is returned.

Del--Delete a variable/name, and after del, the variable can no longer be used.

Vi.. Data structure

Python has three types of built-in data structures: lists, tuples, and dictionaries.

  1. List

A list is a data structure that handles a set of ordered items, which are mutable data structures. The items of the list are contained in square brackets [], eg: [1, 2, 3], empty list []. Determines whether a list contains an item that can be used in, such as L = [1, 2, 3]; Print 1 in L; #True; supports indexing and slicing operations; If the index is out of range, indexerror; use the function Len () to see the length; Use Del to remove items from the list, Eg:del l[0] # If out of range, Indexerror

The list function is as follows:

    Append (value) ---Add an item to the end of the list value

L = [1, 2, 2]
L.append (3) #[1, 2, 2, 3]

    count (value) ---Returns the number of items in the list that have values of value

L = [1, 2, 2]
Print L.count (2) # 2

    Extend (LIST2) ---Add a list to the end of the list List2

L = [1, 2, 2]
L1 = [10, 20]
L.extend (L1)
Print L #[1, 2, 2, 10, 20]

    Index (value, [Start, [stop]]) ---Returns the index of the first occurrence in the list that is value, and if not, the exception valueerror

L = [1, 2, 2]
A = 4
Try
Print L.index (a)
Except ValueError, ve:
Print "There is no%d in list"% a

    Insert (i, value) ---Inserts an item vlaue to the list I position, and adds to the end of the list if I is not

L = [1, 2, 2]

L.insert (1, 100)
Print L #[1, 100, 2, 2]

L.insert (100, 1000)
Print L #[1, 100, 2, 2, 1000]

    pop ([i]) ---Returns the I-position item and removes it from the list, and if no argument is supplied, the last item is deleted; If provided, but I exceeds the index range, the exception indexerror

L = [0, 1, 2, 3, 4, 5]

Print L.pop () # 5
Print L #[0, 1, 2, 3, 4]

Print L.pop (1) #1
Print L #[0, 2, 3, 4]

Try
L.pop (100)
Except Indexerror, ie:
Print "Index out of range"

    Remove (value) ---Removes the first occurrence of value from the list, and if there is no vlaue in the list, the exception valueerror

L = [1, 2, 3, 1, 2, 3]

L.remove (2)
Print L #[1, 3, 1, 2, 3]

Try
L.remove (10)
Except ValueError, ve:
Print "There is no" list "

    reverse () ---list reversal

L = [1, 2, 3]
L.reverse ()
Print L #[3, 2, 1]

    Sort (Cmp=none, Key=none, reverse=false) ---list sorting

"Python Library Reference"
CMP:CMP Specifies a custom comparison function of the arguments (iterable elements) which should return a negative, zero O R positive number depending on whether the first argument are considered smaller than, equal to, or larger than the second Argument
"Cmp=lambda x,y:cmp (X.lower (), Y.lower ())"
Key:key specifies a function of one argument that's used to extract a comparison key from each list element: "Key=str.low Er
Reverse:reverse is a Boolean value. If set to True, then the list elements is sorted as if each comparison were reversed. In general, the key and reverse conversion processes is much faster than specifying an
Equivalent CMP function. This is because CMP are called multiple times for each list element while keys and reverse touch each element only once.

L5 = [10, 5, 20, 1, 30]
L5.sort ()
Print L5 #[1, 5, 10, 20, 30]

L6 = ["BCD", "abc", "CDE", "BBB"]
L6.sort (cmp = lambda S1, s2:cmp (s1[0],s2[1]))
Print L6 #[' abc ', ' BBB ', ' BCD ', ' CDE ']

L7 = ["BCD", "abc", "CDE", "BBB", "FAF"]
L7.sort (key = Lambda s:s[1])
Print L7 #[' FAF ', ' abc ', ' BBB ', ' BCD ', ' CDE ']

----------------------------------------------See continued Python basic Syntax (ii)----------------------------------------------

Python Basic Syntax 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.