Introduction to Python programming (1) basic syntax

Source: Internet
Author: User
Tags array definition integer division

Python is an increasingly popular scripting language. It is simpler than Java and more powerful than php. It is also suitable for developing desktop applications. In ubuntu, it is also a necessary script engine, so it is necessary to learn about it. The article here is only intended for users who have certain programming basics, preferably those who are familiar with php or javascript, if you do not have any basic beginner, you are advised to find more detailed tutorials.

Python variables do not need to be defined. This is the same as php. It is loose than javascript, but it uses indentation as the paragraph identifier and is used by people who are used to the C language style syntax, it may be difficult to use it at first, but it is quite normal and reasonable to think about it. Although Python is also loose in process-oriented/object-oriented aspects, in fact, the general program is a main portal, and then constantly calls other class libraries or functions, so there is nothing wrong with indentation, on the one hand, users are required to standardize code writing, and on the other hand, redundant {} is saved in reverse order {}.
Compared with the C language style, Python has the following main syntax features:

1. Variables and strings
In python, all variables are objects. arrays are actually a linked list and can be linked.
1.1 for common data types, the definition and value assignment methods are the same. I will not introduce them here, but I will introduce some special python strings.
Python uses ['] ["] To enclose strings with the same meaning. It also uses [\] to escape special characters.
However, it has a special Syntax: ['''], which is used to enclose strings that are divided into multiple rows. Actually, this can also be used as its multi-line annotation, for example:

Copy codeThe Code is as follows: #-*-coding: gb18030 -*-
'''
Use three quotation marks separately. Because the character string is not used, it is equivalent to an annotation.
Assign a value to a variable.
'''
Str = ''' I'm a pair of three quotation marks, \ 'oh! \ 'I can wrap,
Line feed, so OK '''
Print str

This syntax is very interesting.
Note that if the source code contains Chinese characters, it must be defined in the first line of the source code:
#-*-Coding: gb18030 -*-

Of course, you can also use UTF-8 encoding, which means you are debugging in linux or windows.

1.2 In terms of variables,It is necessary to know several built-in types, including None, True, and False.(Note:Python variables are case sensitive.)

None indicates an unspecified variable. As for True/False, everyone knows it.

Note: In addition to using ''' for multiline annotation, you can also use # as a single line annotation. This is a common practice of the script language in linux.

Continue row: For a long row in python, \ can be used to indicate that the row is not over. This is consistent with the common practice of linux shell.

1.3 array definition:
Arr = ['A', 'B', 'C']
Equivalent
Arr = []
Arr + = ['a']
Arr + = ['B']
Arr + = ['C']
# Traversal method:
For I in range (0, len (arr )):
Print arr [I], "\ n"
The python array is actually not an array, but a list object. If you want to refer to its usage, you can refer to the method of this object.
It should be noted that the python array is actually a linked list. Therefore, after definition, you cannot directly append elements to the backend like php. Instead, you need to use the linked list operation method. In the preceding example, if arr [2] = 'ccccccc' is used, the value of the third element can be changed, however, if you use arr [3] = 'ddddd' to add an element, the following error occurs: arr. append ('ddddd ') or arr. insert (any location, 'dddd') to add elements

For multi-dimensional arrays, the definition is as follows: arr = [[] * 3. It defines: [[], [], [], you can also use arr = [[] for I in range (3)]

For common operations such as arrays and strings, we will introduce them in the following chapter. Here we will not list more usage methods.

2. Block definition (such as statements and functions)

The format of the Python block is

Block Code:
Code inside the block

How does it determine the block end? It is different from VB, Dephi, and so on. blocks all have an ending sign. It does not exist. It is identified purely based on indentation. Although this is a bit weird, it is quite nice to get used to it.

Basic Block definition Syntax:

2.1. if/elif/else

Copy codeThe Code is as follows: x = int (raw_input ("Please enter an integer:") # Get row Input
If x> 0:
Print 'positive number'
Elif x = 0:
Print '0'
Else:
Print 'negative number'

In Python, the three-question operator is not used, but it can be replaced by a value that meets the condition (if the condition else does not meet the condition ).
For example, str = ('OK' if 1> 2 else 'not OK ')
The final result is: str = 'not OK'

Note that python does not exist! , & And | Operator, but not, and, or

2.2. in
In determines whether a number is in a set (such as tuples and lists ).
If 'yes' in ('y', 'Ye ', 'yes '):
Print 'OK'
Corresponding to this is not in.

2.3. for... in
Python does not have a for loop similar to C, but uses for... in to operate every element in the set.
Copy codeThe Code is as follows: a = ['cat', 'door', 'example ']
For x in:
Print x
Equivalent:
Copy codeThe Code is as follows: for I in range (0, len ()):
Print a [I]

If you want to modify the content of a, use the copy loop of a (otherwise it is not safe), such:

Copy codeThe Code is as follows: a = ["cat", "tttyyyuuu"]
For x in a [:]:
If len (x)> 6: a. insert (0, x)
Print

Result:
['Tttyyyuuu ', 'cat', 'tttyyyuuu']

2.4. break/continue

These two statements are used in the same way as other C syntax languages.
Copy codeThe Code is as follows: for I in range (10 ):
If 2 = I: continue # ends the current loop and enters the next loop
If 6 = I: break # Jump out of the loop
Print I
Result:
0
1
3
4
5

2.5. while/pass
While True:
Pass # do nothing

2.6. is
Used to compare whether two variables point to the same memory address (that is, whether two variables are equivalent) and = is used to compare whether two variables are logically equal.
Copy codeThe Code is as follows: a = [1, 2]
B = [1, 2]
>>> A is B
False
>>> A = B
True

2.7. del

Used to delete Elements
Copy codeThe Code is as follows: a = [1, 2, 3, 4, 5, 6]
Del a [0]
A
>>> [2, 3, 4, 5, 6]

Del a [2: 4]
A
>>> [2, 3, 6]
Del a [:]
A
>>> []

Del
A
# Throw an exception
>>> NameError: name 'A' is not defined

2.8. try... try t... finally/raise

Used for Exception Handling
Copy codeThe Code is as follows: try:
X = int (raw_input ("enter a number :"))
Failed t ValueError: # multiple exceptions can be captured simultaneously, such as running T (RuntimeError, ValueError ):
Print "your input is not a number" # When you enter a non-Number
Failed T: # The Exception name is omitted. All exceptions can be matched. Use it with caution.
Pass
Else: # When no exception occurs
Print 'result = ', x
Finally: # is similar to Java. It is generally used to release resources, such as files and network connections.
Print 'finish'

Raise is used to throw an exception and can be a custom exception class.

Note that the try statement should not have the syntax for completing an operation, but should be written in
Else: later. This is very different from other languages. For example, writing a print after a try will not show anything.

The Convention is a class ending with an Error. exceptions of the same type are generally derived from the same base class (such as Exception)

Copy codeThe Code is as follows: class MyError (Exception ):
Def _ init _ (self, value ):
Self. value = value
Def _ str _ (self ):
Return reper (self. value)

A base class exception can match a derived class exception.
Copy codeThe Code is as follows: try:
Raise Exception ("spam", "egg ")
Failed t Exception, inst: # inst is the instance of this Exception class, which is optional
Print type (inst) # exception type
Print inst

2.9 Function Definition

Def function name (parameter list ):
Function Code
Return Value (optional)

Copy codeThe Code is as follows: def get_arr (arr ):
Arr. insert (0, 'aaa ')
Return arr

Arr = ['1', '2', '3']
New_arr = get_arr (arr)
Print new_arr

Result: ['aaa', '1', '2', '3']

Default parameters:
The following parameter allows initialization of a default value, such as def myfunc (a, B = 0, c = 'aaa '):

Keyword:
Another abnormal way to use python functions is to directly use key-value pairs such as key = value to represent parameters without the order of parameters. For example:
Myfunc (c = 'gggggggg', a = 0)

Variable parameters:
It is represented by * key, which must be before the end of the parameter table
For example:

Copy codeThe Code is as follows: def fprintf (file, format, * args ):
File. write (format % args)

The definition of classes and packages is described in Chapter 3.

3. Notes-Python Operators

Operator Name Description Example
+ Add Add two objects 3 + 5 get 8. 'A' + 'B' get 'AB '.
- Subtraction Returns a negative number or a number minus another number. -5.2 returns a negative number. 50-24 get 26.
* Multiplication Returns a string that is repeated several times. 2*3 get 6. 'La '* 3 to get 'lala '.
** Power

Returns the Power y of x.

3 ** 4 get 81 (3*3*3*3)
/ Division X divided by y 4/3 to get 1 (Division of Integers to get the result of integers ). 4.0/3 or 4/3. 0 get 1.3333333333333333
// Integer Division Returns the integer part of the operator. 4 // 3.0 get 1.0
% Modulo Returns the remainder of the Division. 8% 3 get 2. -25.5% 2.25 get 1.5
< Move left Shifts a certain number of BITs to the left (each number is expressed as a bit or binary number in the memory, that is, 0 and 1) 2 <2 get 8. -- 2 expressed in BITs as 10
> Right Shift Shifts a certain number of BITs to the right. 11> 1 to get 5. -- 11 is expressed as 1011 in bits. After moving 1 bit to the right, 101 is obtained, that is, 5 in decimal format.
& Bitwise AND Bitwise AND 5 & 3 get 1.
| By bit or Number by bit or 5 | 3 get 7.
^ Bitwise OR Bitwise OR 5 ^ 3 get 6
~ Flip by bit The bitwise flip of x is-(x + 1) ~ 5 to 6.
< Less Returns whether x is less than y. Returns 1 for all comparison operators to indicate true, and 0 for false. This is equivalent to the special variables True and False. Note: These variable names are capitalized. 5 <3 returns 0 (False) and 3 <5 returns 1 (True ). Comparison can be connected at any time: 3 <5 <7 returns True.
> Greater Returns whether x is greater than y. 5> 3 return True. If both 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.
= Equal Equal comparison object X = 2; y = 2; x = y returns True. X = 'str'; y = 'str'; x = y, False is returned. X = 'str'; y = 'str'; x = y returns True.
! = Not equal Compare whether two objects are not equal X = 2; y = 3; x! = Y returns True.
Not Boolean "Non" If x is True, False is returned. Returns True if x is False. X = True; not y returns False.
And Boolean "and" If x is False, x and y returns False. Otherwise, it returns the calculated value of y. X = False; y = True; x and y, returns False because x is False. Python does not calculate y here, because it knows that the value of this expression must be False (because x is False ). This phenomenon is called short circuit computation.
Or Boolean "or" If x is True, it returns True; otherwise, it returns the calculated value of y. X = True; y = False; x or y returns True. Short circuit calculation is also applicable here.

 

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.