Introduction to the basic syntax of of 1 for Python programming

  • 2020-04-02 13:46:57
  • OfStack

Python is a scripting language in today's increasingly popular, it is more simple than Java, are more powerful than PHP, desktop application development, and also applies to do in ubuntu, more is must be a scripting engine, so it is necessary to study the articles here only for a certain programming basis, preferably familiar with PHP or javascript user, if you don't have any basis for novice suggest looking for more detailed tutorial to learn.

Python's variables do not need to be defined, which is the same as PHP, it is looser than javascript, but it is indentation as a paragraph marker, as people used to the C language style syntax, may be very uncomfortable to use at first, but on closer thought, it is also very normal, very reasonable. Although Python is also very loose on the procedural/object-oriented side, in practice a typical program is a main entry point and then constantly calls other libraries or functions, so there's nothing wrong with indentation, which requires the user to write code in a formal way and omits the extra {} in reverse.
Compared with the C language style, the main syntactic features of Python are as follows:

1. Variables and strings
      In python, where all variables are objects, an array is actually a linked list and can be manipulated accordingly.
1.1 for common data types, the definition/assignment method is the same, which I won't cover here, but python's string aspect is a bit special, which I'll cover here.
Python has the same meaning of enclosing a string with [']["], and the same meaning of escaping special characters with [\]
However, it has a very special syntax: the [''] triple quotation mark, which is used to enclose a multi-line string. In fact, it can also be used as a multi-line annotation, such as:

# -*- coding: gb18030 -*-
'''
 If you use three quotes alone, the string is equivalent to an annotation because it is not used 
 Here is the assignment to a variable 
'''
str = '''  I'm a triple quote, 'oh!' I can break lines, 
           I broke the line, same thing OK '''
print str

That's an interesting syntax.
Need to pay special attention to, if the source code has Chinese, must be defined in the first line of the source code:
# -*- coding: gb18030 -*-

Of course, you can also use utf-8 depending on whether you're debugging on Linux or Windows.

1.2 in addition, in terms of variables, There are several built-in types that are important to understand: None, True, False (note: Python variables are strictly case-sensitive )

None is an undefined variable, as far as True/False is concerned, hehe.

Comments: in addition to using "" for multi-line comments, you can also use # as a single-line comment, which is common practice in scripting languages under Linux.

Line continuation: in python, a line that is too long can be terminated with a \, as is common with Linux shells.

1.3 array definition:
Arr = ['a', 'b', 'c']
Is equivalent to
Arr = []
Arr + = [' a ']
Arr + = [' b ']
Arr + = [' c ']
Traversal method:
For I in range(0, len(arr)):
      Print arr [I], "\ n"
Python's array is not really an array, but a list object, and if you want to refer to its usage, you can refer to the method of this object.
It's important to note that python's array is actually a linked list, so you can't just append elements to it as you would in a language like PHP. In the example above: if you use arr[2] = 'CCCCC' you can change the value of the third element, but if you use arr[3] = 'DDDD' adding an element is a mistake, you should add an element with arr.append(' DDDDD ') or arr.insert(' DDDD ')

For multidimensional arrays, the definition is: arr = [[]] * 3. It defines: [[], [], []], or arr = [[] for I in range(3)].

There is a chapter devoted to common operations such as arrays and strings, but no more.

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

Python blocks are in the same format

Block code:
      The code inside the block

How does it determine the end of a block? It is different from VB, Dephi and so on, the block is a sign of the end, it does not have, it is purely based on indentation recognition, so although a bit strange, but it is good to get used to it.

Block basic definition syntax:

2.1. If/elif/else

x=int(raw_input("Please enter an integer:")) # Get line input 
if x>0:
    print ' A positive number '
elif x==0:
    print ' zero '
else:
    print ' A negative number '

The three question operator is not used in Python, but it can be replaced with the value that satisfies the condition if satisfies the condition else
For example: STR = ('ok' if 1 > 2 the else 'not ok')
End result: STR == 'not ok'

One thing to note here is that there is none in python! , && and || operators, instead of not, and, or

2.2. In
In determines whether a number is in a set (tuple, list, etc.)
If 'yes' in   (' y ', 'ye', 'yes') :
      The print   'ok'
The counterpart of this is not in

2.3. The for... The in
Instead of a for loop like in C, python USES a for... In to operate on each element in the collection

a=['cat','door','example']
for x in a:
    print x

Is equal to:
for i in range( 0, len(a) ):
    print a[i]


If you want to modify the contents of a, please loop with a copy of a (otherwise not safe), such as:

a=["cat","tttyyyuuu"]
for x in a[:]:
    if len(x)>6: a.insert(0,x)
print a

The result is:
[' tttyyyuuu ', 'cat' and 'tttyyyuuu]

2.4. Break/continue

These two are used in the same way as other C syntax languages

for i in range(10):
    if 2==i: continue # End the current loop , Go to the next loop 
    if 6==i: break # Jump out of the loop 
    print i

The result is:
0
1
3
4
5

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

2.6. The is
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

a = [1,2]
b = [1,2]
>>> a is b
False
>>> a == b
True

2.7. Del

Used to delete elements

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
# An exception is thrown 
>>>NameError: name 'a' is not defined

2.8. Try... Except... Finally/raise

For exception handling

try:
    x=int(raw_input(" Please enter a number :"))
except ValueError: # Multiple exceptions can be caught at the same time , Writing such as except(RuntimeError,ValueError):
    print " You did not enter a number " # When a non-number is entered 
except: # Omit exception name , All exceptions can be matched , careful 
    pass
else: # When there are no exceptions 
    print 'result=', x
finally: # and Java In a similar. Commonly used to free up resources, such as files, network connections. 
   print 'finish'

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

The important thing to note here is that the try statement should not have syntax within it to complete an operation, but instead should be written in
Else: after that, this is very different from other languages, for example, if you put a print after try it doesn't show anything.

The convention is to end a class with an Error, and exceptions of the same kind are typically derived from the same base class (such as Exception)

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

try:
    raise Exception("spam","egg")
except Exception,inst: #inst Is an instance of the exception class , Is optional 
    print type(inst) # Type of exception 
    print inst

2.9 definition of function

Def function name (parameter list):
      Function code
      Return return value (optional)

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:
Def myfunc(a, b=0, c='aaa') : def myfunc(a, b=0, c='aaa')

Parameter keyword:
Another abnormal usage method of python's functions is that it can not be called in the order of parameters, but directly use key=value and other key-value pairs to represent parameters, such as:
Myfunc (c = 'GGGGG, a = 0)

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

def fprintf(file, format, *args):
    file.write(format % args)

The definition of classes and packages will be covered in chapter 3.

3. Footnote -- Python operators

The operator The name of the instructions example + add Add two objects 3 plus 5 is 8. 'a' plus 'b' is 'ab'. - Reduction of You get a negative number or one number minus another Minus 5.2 is a negative number. 50 minus 24 is 26. * take Multiply two Numbers or return a string that has been repeated several times 2 times 3 is 6. 'la' times 3 is 'lalala'. * * power

Returns x to the y

3 times 4 is 81. / In addition to X divided by y 4/3 gives you 1. 4.0/3 or 4/3.0 gets 1.333333333333333333 // Take the divisible Returns the integer part of the quotient 4 // 3.0 gets to 1.0 % modulus Returns the remainder of division 8 percent. 3 is 2. 2.25 1.5-25.5% < < Shift to the left To move a number of bits to the left (each number is represented in memory as a bit or binary number, i.e., 0 and 1). 2 < < 2 is 8. -- 2 is expressed in bits as 10 > > Moves to the right To move the number of bits of a number to the right by a certain number 11 > > 1 is 5. -- 11 is expressed as 1011 in bits. If you move one bit to the right, you get 101, which is the decimal 5. & Bitwise and Number by bit and 5 minus 3 is 1. | Bitwise or Number by bit or 5 |, 3 is 7. ^ The bitwise exclusive or Number by digit or 5 to the third is 6 ~ According to a flip The bitwise flip of x is minus x plus 1. Minus 5 is 6. < Less than Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. This is equivalent to the special variables True and False, respectively. Notice that these variable names are capitalized. 5 < 3 returns 0 (False) and 3 < 5 returns 1 (that is, True). Comparisons can be joined arbitrarily: 3 < 5 < 7 returns True. > Is greater than Returns whether x is greater than y 5 > 3 returns True. If both 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. = = Is equal to the 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. ! = Is not equal to Compare whether two objects are unequal X = 2; Y = 3; X!!! = y returns True. The not Boolean non If x is True, it returns False. If x is False, it returns True. X = True; Not y returns False. The and Boolean "and" If x is False, x and y return False, otherwise it returns the calculated value of y. X = False; Y = True; X and y, since x is False, returns False. In this case, Python won't evaluate y because it knows that the value of this expression must be False (because x is False). This phenomenon is called short circuit calculation. The or Boolean or If x is True, it returns True, otherwise it returns the evaluated value of y. X = True; Y = False; X or y returns True. Short-circuit calculations also apply here.

 


Related articles: