Getting Started with Python programming (1) Introduction to Basic grammar _python

Source: Internet
Author: User
Tags array definition arrays bitwise exception handling integer division in python

Python is an increasingly popular scripting language today, it is simpler than Java, more powerful than PHP, and also applicable to the development of desktop applications, in Ubuntu, is a necessary script engine, so it is necessary to learn, the article here only for a certain programming basis, It is better to be familiar with PHP or JavaScript users, if there is no basis for novice suggestions to find more detailed tutorials to learn.

Python variables don't need to be defined, this is the same as PHP, it is more relaxed than JavaScript, but it is indented as a paragraph logo, as the habit of C language style grammar, may be very not used to the beginning, but a thin think, in fact, is also very normal, very reasonable. While Python is very relaxed in process/object-oriented terms, but in fact, the general program is a main entrance, and then constantly call other class libraries or functions, so the indentation of the way is not improper, so on the one hand to require users to write code to standardize, on the other hand, the reverse omitted unnecessary {}.
Compared with the C language style, Python's main grammatical features are:

1, variable, string
In Python, all variables are objects, the array is actually a linked list, and can be linked to the corresponding list operation.
1.1 For ordinary data types, the definition/assignment method is the same, not to be introduced here, Python string aspects are somewhat special, here to introduce.
Python has the same meaning for strings with [']], and also for special characters using [\] for escaping
But it has a very special syntax: ['] triple quotes, which enclose a string of multiple lines, which is actually a multiline annotation, such as:

Copy Code code as follows:
#-*-coding:gb18030-*-
'''
Using three quotes alone, the string is equivalent to annotations because it is not used
Here's how to assign a value to a variable
'''
str = ' I'm a triple quote, \ ' oh!\ ' I can wrap,
To change the line, so OK ""
Print str

This kind of grammar is very interesting.
Need to pay special attention to IS, if the source code has Chinese, must be in the first line of the source code definition:
#-*-coding:gb18030-*-

Of course, you can also use the Utf-8 encoding, which depends on whether you are debugging in Linux or Windows.

1.2 In addition, there are several built-in types that are necessary to understand about variables: None, True, False (note:python variables are strictly case-sensitive)

None is a variable that does not define, as for true/false this everybody knows it, hehe.

Note: In addition to using the word "' as a multi-line annotation, you can use # as a single-line annotation, which is a common practice for scripting languages under Linux.

Continuation: Python for too long rows, you can use \ means not end, this and Linux shell common practice is consistent.

1.3 Array Definition:
arr = [' A ', ' B ', ' C ']
Equal to
arr = []
arr + = [' a ']
arr + = [' B ']
arr + = [' C ']
#遍历方法:
For I in range (0, Len (arr)):
Print arr[i], "\ n"
The Python array is not actually an array, but rather a list object, and you can refer to the object's method if you want to refer to its usage.
It should be noted that Python's array is actually a linked list, so the definition can not be like the language of PHP, directly appended to the following elements, but need to operate a list of methods to operate. In the example above: if you use arr[2] = ' CCCCC ' You can change the value of the third element, but if you add an element with arr[3] = ' dddd ' It will be wrong, should be used: arr.append (' ddddd ') or arr.insert (anywhere, ' dddd ') adding elements

For multidimensional arrays, the method is defined as: arr = [[]] * 3 It is defined as: [[], [], []], or you can use arr = [[] for I in range (3)]

For common operations such as arrays and strings, there is a chapter devoted to it, where more usage is not enumerated.

2, the definition of blocks (such as statements, functions, etc.)

Python blocks are formatted as

Block Code:
Code inside the Block

How does it judge the end of the block? It is different VB, Dephi, and so on, blocks are the end of the logo, it does not, it is purely based on the indentation to identify, so although a bit weird, but the habit will feel very good.

Block Basic definition syntax:

2.1. If/elif/else

Copy Code code as follows:
X=int (Raw_input ("Please enter an integer:") #获取行输入
If x>0:
print ' positive '
Elif x==0:
print ' 0 '
Else
print ' negative '

There is no three-operator in Python, but you can substitute a value that satisfies a condition if it satisfies a condition that it does not meet the condition.
such as: str = (' OK ' if 1>2 else ' not OK ')
The end result: str = ' Not OK '

One place to note here is that there is no python!, && and | | operator, instead of using not, and, or

2.2. In
In to determine whether a number is in a set (such as tuples, lists, etc.)
If ' Yes ' in (' Y ', ' ye ', ' yes '):
print ' OK '
The corresponding is also not in

2.3. For ... in
Python does not have a for loop like C, but instead uses for...in to manipulate each element in the collection

Copy Code code as follows:
A=[' cat ', ' door ', ' example '
For X in a:
Print X

Equivalent to:
Copy Code code as follows:
For I in range (0, Len (a)):
Print A[i]


If you want to modify the contents of a, please use a copy loop (otherwise unsafe), such as:

Copy Code code as follows:
A=["Cat", "tttyyyuuu"]
For x in a[:]:
If Len (x) >6:a.insert (0,x)
Print a

The results are:
[' tttyyyuuu ', ' cat ', ' tttyyyuuu ']

2.4. Break/continue

These two usages are the same as those of the other C-syntax classes

Copy Code code as follows:
For I in range (10):
If 2==i:continue #结束当前循环, go to Next loop
If 6==i:break #跳出循环
Print I

The results are:
0
1
3
4
5

2.5. While/pass
While True:
Pass #什么也不做

2.6. Is
Used to compare whether two variables point to the same memory address (that is, two variables are equivalent) and = = To compare two variables for logical equivalence

Copy Code code as follows:
A = [1,2]
b = [1,2]
>>> A is B
False
>>> A = = b
True

2.7 Del.

Used to delete an element

Copy Code code 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
A
#抛出异常
>>>nameerror:name ' A ' is not defined

2.8. Try ... except ... finally/raise

For exception handling

Copy Code code as follows:
Try
X=int (Raw_input ("Please enter a number:")
Except ValueError: #可以同时捕获多个异常, written as except (Runtimeerror,valueerror):
Print "You are not entering a number" #当输入非数字时
Except: #省略异常名, you can match all the exceptions, use caution
Pass
else: #当没有异常时
print ' result= ', X
Finally: #和Java中类似. Typically used to release resources, such as files, network connections.
print ' Finish '

Raise is used to throw exceptions, which can be a custom exception class

The special note here is that there should be no syntax within the TRY statement to complete an operation, but rather a
Else: Later, this is very different from other languages, such as writing a print after a try and it doesn't show anything.

Conventions are classes that end with an error, and similar exceptions are generally derived from the same base class (such as Exception)

Copy Code code as follows:
Class Myerror (Exception):
def __init__ (Self,value):
Self.value=value
def __str__ (self):
Return Reper (Self.value)

Base class exceptions can match derived class exceptions

Copy Code code as follows:
Try
Raise Exception ("spam", "egg")
Except Exception,inst: #inst为该异常类的实例, optional
Print type (inst) #异常的类型
Print Inst

2.9 Definition of function

def function name (argument list):
function code
return value (optional)

Copy Code code as follows:
def get_arr (arr):
Arr.insert (0, ' AAA ')
Return arr

arr = [' 1 ', ' 2 ', ' 3 ']
New_arr = Get_arr (arr)
Print New_arr

The result is: [' aaa ', ' 1 ', ' 2 ', ' 3 ']

Default parameters:
In which the following parameters allow initialization of a default value, such as: Def MyFunc (A, b=0, c= ' aaa '):

Parameter keywords:
Python's function also has a perverted use, that is, the invocation can be not in the order of parameters, but directly with key=value such key value pairs to represent parameters, such as:
MyFunc (c= ' ggggg ', a=0)

Variable parameters:
With *key, it must also be in the end of the parameter table
Such as:

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

The definition of classes and packages is specifically introduced in chapter III, which is not explained here first.

3. Operator of note--python

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

Returns the Y-power of X

3 * * 4 gets 81 (ie 3 * 3 * 3 * 3)
/ Except x divided by Y 4/3 gets 1 (the integer division gets the integer result). 4.0/3 or 4/3.0 get 1.3333333333333333
// Take the Divide The integer part of the return quotient 4//3.0 gets 1.0
% Take the mold Returns the remainder of a division 8%3 got 2. -25.5%2.25 got 1.5.
<< Move left Shifts a number of bits to the left 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 expressed as 10 by bit
>> Move right Move a number of bits to the right by a certain number One >> 1 get 5. --11 is expressed as 1011 by bit, 1 bits to the right and 101, or 5 in decimal.
& Bitwise AND The bitwise of number and 5 & 3 Get 1.
| by bit or Number of bitwise OR 5 | 3 Get 7.
^ Per-bitwise XOR OR The bitwise XOR of the number or 5 ^ 3 Get 6
~ Flip by bit The bit flip of X is-(x+1) ~5 got 6.
< Less than Returns whether x is less than Y. All comparison operators return 1 to represent true, and 0 to represent false. This is equivalent to the special variable true and false respectively. Note that these variable names are capitalized. 5 < 3 returns 0 (that is, false) and 3 < 5 returns 1 (that is, true). Comparisons can be any connection: 3 < 5 < 7 returns TRUE.
> Greater than Returns whether x is greater than Y 5 > 3 returns TRUE. If two operands are numbers, they are first converted to a common type. Otherwise, it always returns false.
<= Less than or equal to Returns whether x is less than or equal to Y x = 3; y = 6; X <= y returns True.
>= Greater than or equal to 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 Compare two objects for unequal x = 2; y = 3; X!= y returns True.
Not Boolean "Non" Returns False if X is true. 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 calculated value of Y. x = False; y = True; X and Y, which returns false because X is false. Here, Python does not compute y because it knows that the value of the expression must be 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 calculated value of Y. x = True; y = False; X or Y returns true. Short-circuit calculations are also applicable here.

Related Article

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.