Python Learning notes _python Basics

Source: Internet
Author: User

    • Python Basics
    • Statements and syntax
      • Comments
      • Go on
      • Code group
      • Indentation of code
      • Write multiple statements on one line
      • Module
    • Assigning values to variables
      • Assignment operator
      • Increment assignment
      • Multiple assignments
      • Multi-value Assignment
    • The basic style written by Python
      • Structure and layout of the module
    • Memory management
      • Variable definition
      • Reference count
        • Increase reference count
        • Reduce reference count
        • Del statement

Python base Statements and syntax annotations

#annotate with a number in Python

Go on

If a statement needs to cross a line, you need \ to connect two statements across the line

if‘qeesung‘and     23

In both cases, you do not need to use backslashes for cross-row connections:

    • A closed operation, with parentheses, brackets, and curly braces that can be written in multiple lines, for example, when defining 列表 one 元组 , 字典 you can cross-line
alist = [2,2,3,4,                                                         5,6,7,8                                                           ]                                                                                                    
    • Strings that are included under three quotation marks can be written across lines
‘‘‘HelloWorld This is Great World‘‘‘
Code group

The code that indents an identical statement is fast, and we call it, 代码组 for example, if that the while class statement is all over.

Indentation of code

Python distinguishes blocks of code by code. As the indentation depth increases, the level of the code is deepened, and the code without indentation is the highest level, called the part of the script 主体(main)

Write multiple statements on one line (;)

We've talked about \ writing a statement on multiple lines, and now we can use it to write multiple statements in one line.

import‘foo‘ ; sys.stdout.write(x+‘\n‘)
Module

Each Python script file can be treated as a module, and the module exists as a disk file.
The code in the module can be a script that executes directly , or it can be a bunch of code like a library function

Assigning values to variables

First, let's take 对象 a look at what is called, an object is a type of area in memory.

Assignment operator

Inside the Python statement, = is the primary assignment operator

12‘Hello World‘# ...

Attention:

    • The assignment in Python does not assign a value to a variable, and when assigned, whether the object is newly created or an existing one, it assigns the object's reference to the variable
    • The assignment statement in Python does not return a value, and the following statement is the wrong
1y = (x=x+1)# error , 赋值语句不返回值
Increment assignment

The so-called increment assignment is using the following operator: += , -= , **= et
Note:
Incremental assignments and general assignment operations are not just changes in the wording, but also deeper changes:

    • The general assignment operation is bound to change the value of the object to which the variable points
    • The increment assignment operation alters the object to which the variable points, for mutable objects, and does not change the object to which the variable is pointing.

Here's a chestnut:
General assignment operations

Print ' + '*6,' number ',' + '*6Number1 =1PrintID (number1) number1 =2PrintID (number2)Print Print ' + '*6,' list ',' + '*6List1 = [1,2,3]PrintID (list1) list1 = [4,5,6]PrintID (list1)

Operation Result:
++++++ number ++++++
157259952
157259940
++++++ List ++++++
3077201548
3074661452

It is visible that the general assignment operation is to change the object that the variable points to.

Incremental assignment operation

Print ' + '*6,' number ',' + '*6Number1 =1PrintID (number1) number1 + =2PrintID (number2)Print Print ' + '*6,' list ',' + '*6List1 = [1,2,3]PrintID (list1) list1 + = [4,5,6]PrintID (list1)

Operation Result:
++++++ number ++++++
159398064
159398040
++++++ List ++++++
3077873292
3077873292

So for non-mutable objects, the incremental assignment will change the object that the variable points to, and for a mutable object, the increment operation will not change the object that the variable points to.

Multiple assignments

Look at the chestnuts below:

1

Creates a new Shape object with a value, 1 and then passes its reference to,,, x y z three variables

Multi-value Assignment

Multivariate assignment is actually the assignment of tuples

x, y, z=12, `a string`

is actually the following tuple assignment

(x, y, z)=(12‘a string‘)
The structure and layout of basic style modules written by Python

When writing a Python script, you can write it in the following layout:

  1. Start line:#/usr/bin/env python
  2. Module Documentation:‘‘‘ this is a test modle ‘‘‘
  3. Module Import:import sys
  4. Variable definition:list1 ={} ;number1 = 0
  5. Class definition:class MyClass:
  6. function definition:def func():
  7. Main program:if __name__ == ‘__main__‘:

Since the main program code, whether the module is imported or run directly, we must know the direction of the program, in some cases, one application needs to import a module of another application, in order to reuse some code, at this time, we just want to access those bit domain other applications in the code, and do not want to run them , we can __name__ determine whether a program is being imported as a module or as a program to run:

    • If the module is imported, it __name__ is the name of the module;
    • If the module is being run directly, __name__ the value is__main__

So we can use the above mechanism to write the test code in the main program, when running the code independently, we run the test code, when as a module is imported, do nothing

Give me a chestnut:

#/usr/bin/env python"' there is math function ' def my_add(Number1, number2):    returnNumber1+number2 def my_sub(Number1, number2):    returnNumber1-number2if__name__ = =' __main__ ':if Ten= = My_add (4,6):Print ' Add test pass '    Else:Print ' Add test Failed '    if-2= = My_sub (4,6):Print ' Sub test pass '    Else:Print ' sub test failed '

If we run the script directly, we run the test code and if we import it as a module, we do nothing.

Memory management

The variables defined by Python have the following characteristics:

    • Variable unordered declaration
    • Variable unordered specified type
    • Program apes don't care about memory management
    • Variable names are "recycled"
    • Del statement can release resources directly
Variable definition

The variables in Python can only be used if they are created and assigned, because any variable without initialization has no meaning.

Reference count

When you create one, 对象 you create one 引用计数 , and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, it is garbage collected.

Increase reference count

When an object is created and its reference is assigned to a variable, the object's reference count is set to 1
Give me a chestnut:

3.14# 创建一个浮点型对象,并将引用赋值给x,引用计数为1# 为x指向的浮点型对象新建一个新的别名,引用计数增加为2

There are other ways to increase the object's reference count, such as passing the object as a parameter to a function, or adding an object to a container object.

#对象被创建3.14#另外的别名被创建y = x#作为参数传递给函数foobar(x)#成为容器对象的一个对象list1=[123‘xyz‘]
Reduce reference count

When a reference to an object is destroyed, the reference count is reduced, and the more common is when the variable leaves its scope. For example, when the function is finished, all local variables are automatically destroyed, and the reference count of the object is reduced.

In the following scenario, the reference count for an object is reduced:

    • A local object reference has left its scope
    • The alias of the object is destroyed
del
    • An alias of an object is assigned a reference to another object
123
    • Remove from a Window object
list1.remove(x)
    • The Window object itself is destroyed
del list1
Del statement

The DEL statement deletes a reference to the object that is reclaimed by the garbage collector when the reference count of the object deleted by Del is reduced to 0

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Python Learning notes _python Basics

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.