Python Learning log 2 syntax-20150716

Source: Internet
Author: User
Tags close close natural string set set

Pilot Log Chapter:

    • 1. Variable definition

Direct definition:

a=10

B=23

C=a+b

Print (c)


    • 2. Judgment statement:

#coding = Utf-8 Python is not able to recognize Utf-8, so comment

Score=90

If score >=70:

Print ("nice")

Elif score >=60:

Print ("Pass")

Elif Score >=30;

Print ("Failed")

Else

Print ("very poor")


    • 3. Looping statements:

For I in Range (0,100):

Print (i)

Print ("Item{0},{1}". Format{i, "Hello,python"})


    • 4. Defining functions

Def SayHello ():

Print ("Hello World")

Def Max (A, B)

If a>b:

Return a

Else

Return b


SayHello () #无缩进 If the indent description is the same as above

Print (max (2,3))


    • 5. Object-oriented

Class Hello: #类

#构造方法

Def_init_ (Self.name):

Self._name = Name


def SayHello (self): #定义方法

Print ("Hello {0}". Foemat (Self._name))

Class Hi (Hello): #继承

#执行初始化方法, constructing the initialization method

Def_init_ (Self,name):

Hello._init_ (self,name) #self传进, name outgoing

#定义方法, construct

def sayhi (self):

Print ("hi{0}". Format (Self._name))

#创建Hello实例

h = Hello ("Jikexueyuan") #传入参数

H.sayhello ()


H1 = Hi ("Zhangsan")

H1.sayhi ()


    • 6. Introduction of external files

mylib.py (external file):

Class Hello: #类定义

def SayHello (self): #方法定义

Print ("Hello Python")


loadlib.py (introduced):

Import mylib# Introducing external files, namespaces


H =mylib. Hello () #创建实例

H.sayhello () #访问


Or:

From mylib import hello# directly into Hello instance


h = Hello ()

H.sayhello ()


Syntax Basics:

    • 1.Python Constants and variables

The concept of constants:

The amount of python that will not be adapted in a program run, such as the number 7 and the character ABC, is always the number 7 and the string "ABC", which does not change to the other amount, i.e. once bound, cannot be changed


Application of constants:

PHP uses const to define constants

Python is defined by an object.


What is a variable:

In Python, you can change the amount of the program as it runs, even if you assign a value.


Assignment value:

Assigning a constant to a variable


Application of variables:

Variables change as the program runs and can accommodate more environments


    • 2.Python of numbers and strings

Learn the types of numbers:

Type: 5 kinds

signed integer int

Long integer type

Float type float

boolean bool (Ture or False)

Complex Type Complex


What is a string:

Quoted in single quotation marks, double quotes

Double quotes can be used in single quotes, cannot use single quotes, and can be output. Double quotation marks cannot be used, single quotes can be used, and results cannot be output

Three quotes: "", "" "can wrap, single quotes, double quotation marks can not wrap


Escape character:

"\" makes the following single quote meaningless: print ' it\ ' a dog '

print ' Hello boy \nhello boy '


Natural string:

Add an R before the usual string

Print "Hello Boy\nhello boy"

Print r "Hello Boy\nhello Boy" invalidates the escape character


Repetition of strings:

Print "hello\n" *20


Sub-string:

"Jike" is a substring of "Jikexueyuan"

#索引运算符从0开始索引

#切片运算符 [A:B] refers to the subscript from a to b-1, and the same first bit is 0

c1= "Jikexueyuan"

C2=C1[0]

C3=C1[7]

C4=c1[:2]

C5=c1[2:] From 21 until the end #kexueyuan

C6=c1[4:7] #xue


    • 3.Python Data types


Underlying data type:

Number and string


List:

Countless groups, similar to lists and tuples.

A list is a container for storing a series of elements, denoted by []

#列表

student=["Xiao Ming", "Xiao Hua", "Xiao Li", "Xiao Juan", "Xiao Yun"] #有序, comma-separated, starting from 0 marks

Print Student[3]

Results:

Xiao Juan


Meta-group:

Like lists, list values can be modified, tuples can only be read, tuples are represented by ()

#元组

student=["Xiao Ming", "Xiao Hua", "Xiao Li", "Xiao Juan", "Xiao Yun"

Print Student[3]

student[3]= "Xiao Yue"

Print Student[3]

Output:

Xiao Juan

Moon

Student= ("Xiao Ming", "Xiao Hua", "Xiao Li", "Xiao Juan", "Xiao Yun")

Print Student[3]

student[3]= "Xiao Yue"

Print Student[3]

Output:

Xiao June

Cannot be modified


Collection:

Two functions:

(1) Establishing a relationship

(2) Eliminate duplicate elements

Format: Set (Element) is an element in parentheses into a set

A=set ("Abcnmaaaggsng")

B=set ("CDFM")

#交集

X=a&b

Print X

#并集

Y=a|b

Print Y

#差集

Z=a-b

Print Z

#去除重复元素

New=set (a)

Print New

#输出

Set ("C", "M")

Set ("A", "B", "C", "N", "M", "G", "F")

Set ("A", "s", "B", "G", "n")

Set ("A", "C", "B", "G", "M", "s", "n")


Dictionary:

Also known as associative arrays, enclosed in {}.

Format: zidian={' name ': ' Weiwei ', ' home ': ' Guilin ', ' like ': ' Music '}

The dictionary contains a whole thing, including all aspects of the specific information, can only be two yuan

#字典

k={"name": "Weiwei", "Jiguan": "Guilin"}

Print k["Jiguan"]

#输出

Guilin

#添加字典里面的项目

k["Aihao"]= "Music"

Print k["name"]

Print k["Aihao"]

#输出

Weiwei

Music


    • 4.Python identifiers

What is an identifier:

Our name in Python programming is called identifiers, where variables and constants are one of the identifiers


Identifier naming rules:

Valid identifiers: The correct naming rules are named

The first character can be either a letter or an underscore, except for the first character, the other part can be a letter or an underscore. Identifiers are case-sensitive

Invalid identifier: An identifier that does not conform to the rule

#标识符命名规则

ssd_1=233

Print Ssd_1

Output: 233

1ssd=233

Print 1SSD

Output: Unable to output

_1ssd=233

Print _1SSD

Output: 233


Common python Keywords:

The Python keyword is also a python identifier, which refers to the identifier that comes with a specific meaning in the system, also known as a reserved word

The most common Python keywords are: and,elif,global,or,else,pass,break,continue,import,class,return,for,while total 28 kinds

#实例

Import Pickle

Print "777"


    • 5.Python objects


What is a Python object: Everything is an object

Python's built-in object types are numbers, string "", list [], tuple (), dictionary {}, set set, and so on.


Detailed pickle pickling:

In Python if there are some objects that require persistent storage and cannot lose the type and data of our object, we need to serialize these objects, after serialization, when we need to use the process of replying to the original data, serialization, we become pickle (pickled)


Recovery process becomes anti-pickle pickled


#pickle腌制

Import Pickle


Serializes an object #dumps (object)

lista=["Mingyue", "Jishi", "You"]

Listb=pickle.dumps (lista) #lista变量

Print Listb

#输出:

(lp0

S ' Mingyue '

P1

As ' Jishi '

P2

As ' you '

P3

A.


#loads (String) restores the object to its original form, and the object type is restored

Listc=pickle.loads (LISTB)

Print LISTC

#输出:

["Mingyue", "Jishi", "You"]


#dump (Object,file), storing objects inside a file serialization

group1= ("Bajiu", "Wen", "Qingtian")

F1=file (' 1.pkl ', ' WB ')

Pickle.dump (Group1,f1,true)

F1.close ()

#输出:


#load (Object,file), the data recovery of the file stored in the dump ()

F2=file (' 1.pkl ', ' RB ')

T=pickle.load (F2) #读取f2

Print T

F2.close

#输出:

("Bajiu", "Wen", "Qingtian")

Note: F2.close close file


    • 6.Python Lines and indents

Understanding logical lines and physical lines:

(1) Logical line: mainly refers to the number of lines in meaning of a piece of code

(2) Physical line: Refers to the number of rows we actually see

#逻辑行与物理行

#以下是3个物理行

Print "ABC"

Print "123"

Print "12q"


#以下是一个物理行, 3 logical lines

Print "ABC", print "123", print "12q"


#以下是一个逻辑行, 3 physical rows

print ' abc '

, "123"

, "12q" '

Summary: The actual number of rows is the physical row, the logical line is usually terminated with a semicolon


Rule in line semicolon usage:

A physical row can include more than one logical line, separated by semicolons, and the logical line of the last face can omit semicolons

#都没有分号

Print "ABC"

Print "123"

Print "12q"

#省略两个分号

print "ABC"; print "123"

Print "12q"


Line connection:

#行链接

Print "We are both \

Good boy. "

#输出

We're all good kids.

#上面如果没有使用 \, there will be an error, that is, the escape character is connected


What is indentation:

In Python, the blank of the beginning of the logical line is specified, and if the logical line header is blank, there will be a program execution error, which is Python-specific

#实例

A= "789"

Print a

#print前有个空白, execution will go wrong

So how to indent it:

(1) In general, there should be no blank in the beginning of logic.

(2) Indent method for if statement

(3) The Indent method in the while loop

#如何缩进

#一般情况下, the beginning of the line does not leave blank

Import Sys

#缩进方法有两种, you can press a space or tab

#if语句的缩进方法

A=7

If a>0:

print "Hello"

#while语句的缩进方法

A=0

While a<7:

Print a

A+=1

#输出

Hello


0

1

2

3

4

5

6


Comments:

Comments start with # until the end of the physical line is a comment

#实例

#如何注释 DDDFFF

The entire physical line is commented, and the other physical line is not commented after the line is wrapped

#如何注释

dddffff# Executable


This article is from the "8626774" blog, please be sure to keep this source http://8636774.blog.51cto.com/8626774/1675415

Python Learning log 2 syntax-20150716

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.