"Machine learning" Python Quick Start notes

Source: Internet
Author: User
Tags function definition pear shallow copy

Python Quick Start notes

Xu an 2018-3-7

1. Python Print

#在Python3. x uses print () to output, and 2.x uses () the error print ("Hello World") print (' I\ ' m apple ') #如果全部使用单引号, you need to precede the escape character \+ quote print (' Apple ' + ' pear ') print (' Apple ' +str (4)) #将数字转换为字符串并打印print (int ("1") +2) #将字符串转换为整数类型

2, Pyhton numerical operation

Print (2**2) #幂运算为 **print (10%3) #取余数为%print (9//4) #取整数为//

3. Self-variable definition

a,b,c=1,2,3 #一次定义多个变量print (A,B,C)

4. While loop

Condition=1while Condition<10:print (condition) condition+=1

5. For loop (equivalent to an iterator)

X=1y=2z=3if X<y<z:print ("x is less than Y")

6. If-else statement

If X<y:print ("X<y") else:print ("X>y")

7, If-elif-else

If X<y:print ("X<y") elif X==y:print ("") Else:print ("X>y")

8. Function definition

def add (A, B): #在python中定义函数需要使用def () c=a+b print ("This is the result of the addtion:", c) Add (1,3)

9. Default function parameters

def car (price,color= ' red ', second_hand=true): #在函数参数后面加 = "Default" to complete the assignment of the default value #bool the parameters in the type need to be uppercase True, flase# need to put the default arguments behind the variable Print (' Price ', price, ' color ', color, ' Second_hand ', Second_hand,) car (1000)

10. Variable Type

'''

(1) Global variables

Variables within the module, outside of all functions, class, can be shared globally or shared by external files

When global variables are used, they need to be explicitly declared using global

If you do not update the global variables, you generally do not need to add the global declaration

If there is a re-assignment and the global Declaration is not used inside the function, it is equivalent to creating a local variable with the same name internally

Local variable with the same name takes precedence over a global variable that is not explicitly declared

'''

apple=10 #全局变量需要在函数外部定义def test10_01 (): Global Apple #在函数内部定义全局变量 apple=20 #在函数内声明的局部变量的优先级高于全局变量 print (apple ) test10_01 ()

'''

(2) Local variables

Inside the function, within the class method (without self-decoration)

Life cycle when a function executes, local variables die out when the function is completed

'''

Def test10_02 (): city= ' Shijiazhuang ' Print (city)

'''

(3) Static variables (class variables)

Directly accessible through the class name, or directly through the instance name, the variables are shared globally between the class and the instance

'''

# class foo:# all=0# def add (self): # foo.q+=1# Ins_1=foo () #实例化对象1 # Ins_2=foo () #实例化对象2 # print (Ins_1.all) #0 # Print (ins_2.all) #0 # Print (foo.all) #0 # ins_1.add () #静态全局变量加1

'''

(4) Instance variables

For a module, it has its own global variables, which can be used by its own internal classes and functions.

For a class or method, it has its own local variables for internal use.

For classes, there are static variables that can be used by both internal and inherited parent-child

The local variables between instances need to be implemented by dynamic binding polymorphism

'''

Class Foo_1:all=0 def __init__ (self,name): Self.name=name def Add (self): foo.q+=1

'''

(5) Summary

Private variables: Variables that are unique to themselves, such as local variables of functions and methods, instance variables

Public variables: Need to be shared within a certain range to achieve synchronization purposes, such as global variables for code sharing within modules, static variables shared between classes and subclasses

'''

11. File Write

Text= "This was my first text.\nthis is next line\n" #使用 \ n means newline, the main line-break instruction is consistent with C + + print (text) my_file=open (' 1.txt ', ' W ') # Open can be opened with a file, open (' File path ', ' form '), Form W for writable form, R for read-only form my_file.write (text) #在文件中写入相应的语句my_file. Close () # Remember to use the Close method to close the file print after the file is written (' Flie writing completed. ')

12. Append text content

My_file=open (' 1.txt ', ' a ') #方式a是append的缩写, indicating the file's append mode append_text= "This is appened text" My_file.write (append_text) my_ File.close ()


# 13. Read the file

My_file=open (' 1.txt ', ' R ') #r为读模式content =my_file.read () #读取文件内容需要使用read () method Second_read=my_file.readline () Third_ Read=my_file.readline () #readline为逐行输出文字all_read =my_file.readlines () #逐行读取后会将读取的元素按行放置在一个列表中print (content, ' Second_read ', Second_read, ' Third_read ', Third_read, ' All_read ', all_read)

14. Classes (Class)

class calculator:  #类一般为大写     def __init__ (self,name,price):   # constructor, which must be assigned when the object is instantiated, preceded by a self        self.name=name         self.price=price    name= "Calculator"      price=10    def add (self,x,y):         Print (self.name)    #如果要在类内调用本身的方法, need to add self. property name or self. Method name          result=x+y        print (Result)     def  Minus (Self,x,y):        result=x-y         print (Result)     def times (self,x,y):         result=x*y        print (Result)     def  devide (self,x,y): &Nbsp;       result=x/y        print (result) newcalulator=calculator (' name ', ten) print (Newcalulator.name)

15. Input

A_input=input (' Please give me a number: ') #input的功能为输入, followed by the parentheses for the prompt information, the return value of input is the content entered (is the STR type), and assigned to the corresponding parameter Int_input=int (a _input) #对字符串需要转换为int类型后进行判断if int_input==1:print (' Your input is 1 ') elif int_input==2:print (' Your input is 2 ') El Se:print (' Your input number is other ')

16. Tuples use parentheses or do not use parentheses

A_tuple= (1,2,3,43) #元组可以用小括号的形式 or without parentheses another_tuple=1,12,43,23 for x in A_tuple:print (x)

17. Use brackets in the list

A_list=[12,34,23,43]for x in A_list: #将list的值使用for循环放到x中, then prints out print (x) for index in range (len (a_list)): #range () will be born into an iterator with index print ("index=", Index, ' number in list= ', A_list[index]) a=[1,2,3,4,5]a.append (0) #在列表后面追加一个元素print (a) A.insert (1,0) #insert (add position, Value) A.remove (2) #remove (first occurrence) print (A[3:5]) A.index (1) #列表中第一次出现该数值的索引a. Sort (reverse= True) #默认为从小到大进行排序, join reverse to sort from large to small print (a)

18. Multidimensional List

A=[1,2,3,4,5]multi_dim_a=[[1,2,3],[123,312,4],[12,43,1]]print (multi_dim_a[1][1]) #使用 [] [] Index

19. Dictionary using curly Braces

d={' Apple ': 1, ' pear ': 2, ' Orange ': 3} #冒号前面的为key, followed by the content, the dictionary key is unique, if not only remember the following element, it cannot be a list to ensure its uniqueness requires print (d[' Apple ') # The value of the print dictionary del d[' pear ' #从字典中删除元素d [' B ']=20 #加入元素到字典print (d) #因为字典采用hash存储, so the dictionary is an unordered container

20. Import Module

#方法一: # import Time #直接使用模块名进行后续操作 # print (Time.localtime ()) # Method Two: # import time as T #如果模块名太长可以使用简称 # Method Three: # From time import L Ocaltime only introduces a function of module # print (LocalTime ()) #如果使用本方法, can write localtime () #方法四 without writing Time.localtime: From time to import * #加 * Can End print (localtime ())

21, the introduction of their own modules

# Make sure your module (same as. py file) and this file are in the same directory, # import M1 #自己的模块名, where function # m1.function () is defined to call its function directly, in Macox, its package directory is in Site-package, If you put the self-built module in it, you can call directly

22, Break&continue

A=truewhile a:b=input (' Please enter something: ') if b!= ": Print (' Enter is not blank ') break

23. Error Handling

Try:file=open (' + ', ' R ') except Exception as E:print (' There is no File named ') response=input (' does you want to creat a new file? (y/n) ' If response = = ' Y ' or ' y ': #逻辑运算符 or OR and not print (' The file is created ') Else:pass #跳过

24. zip (merge two lists into one list item) lambda map

A=[1,2,3]b=[4,5,6]list (A, b) #zip返回为一个对象, if you want to visualize it, you need to convert it to a list to merge for i,j in Zip (A, B): print (I/2,J/2) #生成一个迭代器进行输 Out Fun1=lambda x,y:print (x+y) fun1 (2,3) def fun1 (x, y): Return (x+y) #实现参数绑定print (fun1,[1,3],[2,8])

25. Shallow Copy &deep copy

Import Copya=[1,2,3]b=aprint (ID (a)) #输出变量的唯一id, is assignment, b simply copies the address of a, without making a copy of the actual variable value print (ID (b)) c=copy.copy (a) print (' ID of a: ', ID (a)) print (' ID of c: ', ID (c)) #浅拷贝, the ID is different, the first-level space address is different, but the second-tier space (the second-enclosing array) begins with the same address d=copy.deepcopy (a) print (' ID of a: ', ID (a)) Print (' ID of c: ', ID (d)) #深拷贝, the ID is different, the address from the first level of space is completely different


# 26, Threading Threads

# 27, multiprocessing Multi-core

# 28, Tkinter GUI interface


29. Pickle Save Code

Import pickle# a_dic={' fruit ': [' apple ', ' pear '], ' vegetable ': [' tomato ', ' cumcuber ']}# file =open (' Pickle_exm.pickle ', ' WB ') # Pickle.dump (a_dic,file) # file.close () # file=open (' Pickle_exm.pickle ', ' RB ') # a_dic=pickle.load (file) # Open the previously saved code # File.close ()


#或者自动关闭方案

With open (' Pickle_exm.pickle ', ' RB ') as File:a_dic=pickle.load (file)


30. Use set to find different

Char_list=[' A ', ' B ', ' C ', ' C ']print (set (char_list)) #使用set进行不同查找, output is a non-repeating sequence, sorted by hash sentence= ' Welcome to Shijiazhuang ' Print (set (sentence)) #可以分辨句子中的不同字母 and presented in a single form

# 31, regular expressions (to be added)

import Re #引入正则表达式pattern1 = "Cat" pattern2= ' dog ' string= "dog runs to Cat" print (pattern1 in string) #使用in来判断单词是否在目标语句中 # Look for print (Re.search (pattern1,string)) #使用正则表达式进行查找, the found content will be returned as an object # match a variety of possible--using []print (Re.search (r "R[a-z0-9]n", ' Dog runs to the Cat '))


"Machine learning" Python Quick Start notes

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.