Python step 1

The art of deceiving Hu 2020-11-13 03:23:23
python step


1.Python It's an explanatory language , No compilation .

  • py and pyc  So there is no compilation ?

2. image Perl Follow the same GPL(GNU General Public License) agreement .

3. scripting : Can be embedded into C/C++ Program .

4. Scalable : You need a piece of code that runs very fast , Or code that doesn't want to be public , have access to C or C++ Complete that part of the program , Reuse Python call .

notes : About Python Something more detailed , Deepen... On the basis of continuous understanding .


【 standard 】

Python identifier

  • Single underscore start _foo Represents class properties that cannot be accessed directly , It needs to be accessed through the interface provided by the class , Out-of-service from xxx import * And import ;
  • Start with a double underline __foo Represents a private member of a class ;
  • Beginning and ending with double underscores __foo__ representative Python A special way of marking , Such as __init__() Constructor representing class .

Python Blank line

  • Functions or methods of classes are separated by empty lines , Represents the beginning of a new piece of code . Classes and function entries are also separated by a blank line , To highlight the beginning of the function entry .
  • Air travel is not Python Part of grammar .

【 Variable type 】

  • Python The variable assignment in does not require a type declaration
  • Each variable is created in memory , All include the identification of variables , Name and data these information .
  • Each variable must be assigned a value before use , The variable will not be created until it is assigned a value .
  • Python Allows you to assign values to multiple variables at the same time (a=b=c=1;a,b,c=1,2,'s')

Standard data type

  • Numbers( Numbers )
  • String( character string )
  • List( list )
  • Tuple( Tuples )
  • Dictionary( Dictionaries )

Python Numbers

  • Immutable data types , This means that changing the digital data type assigns a new object .
  • int
  • long( Can also be 8 Into the system and 16 Base number )( Add at the end L perhaps l),- An integer of infinite size
  • float
  • complex( use a + bj, perhaps complex(a,b) Express , The real part of a complex number a Deficiency part of harmony b It's all floating point .)

Python character string

  • String or string (String) It's numbers 、 Letter 、 A string of characters made up of underscores .
  • 2 The order of values is :( Left to right index default 0 At the beginning , The maximum range is less string length 1; Right to left index default -1 At the beginning , The maximum range is at the beginning of the string )
  • Gets a substring : [ Header subscript : Tail subscript ]
  • plus (+) Is a string concatenation operator , asterisk (*) Is a repeat operation .(r/R) Original string
  • Python Single character type... Is not supported , The single character is in Python Is also used as a string .
  • Python2.6 Start , Added a function to format strings str.format(), It enhances string formatting .

Python list

  • [,,,,]
  • The cutting of the values in the list can also use variables [ Header subscript : Tail subscript ]
  • A string is a list of characters
  • The data items of a list do not need to have the same type
    • have access to del Statement to delete the elements of the list ( del list1[2] )
    • Use append() Method to add a list item (list.append('ss'));
    • list.pop([index=-1])
      Removes an element from the list ( Default last element ), And returns the value of that element
    • list.remove(obj)
      Removes the first match of a value in the list
  • The list is right + and * The operator of and Strings are similar .
  • a[:]  Is to create  a  A copy of , So we're in the code for  a[:]  After the operation , It won't change  a  The value of the . And if it's directly to  a  To operate , that  a  The value of will be affected by some operations

Python Tuples

  • Tuple use "()" identification . The inner elements are separated by commas .
  • Tuples cannot be assigned twice , Equivalent to read-only list .
  • tuple(seq)  Convert list to tuple .
  • The first level element of a tuple cannot be modified, added or deleted, but the second level element can be modified .
For example, modify the list in Yuanzu , Dictionary and so on :
  • When a tuple contains only one element , You need to add a comma after the element :
tup1 = (50,)
Python Dictionaries
  • A list is an ordered collection of objects , A dictionary is an unordered collection of objects .
  • The dictionary is Variable containers Model , And it can store Any type of object .
  • The elements in the dictionary are accessed by keys , Instead of accessing by offset .
  • use "{ }" identification . The dictionary is indexed by (key) The value corresponding to it value form .
d = {key1 : value1, key2 : value2 }
  • Keys are usually the only , If repeat The last key value pair will replace the previous one , Value doesn't need to be unique .
  • The value can take any data type , But the bond has to be immutable , Such as a string , A number or tuple .
  • Delete related

del dict['Name']; # Delete key is 'Name' The entry of

dict.clear();     # Empty all entries in the dictionary

del dict ;        # Delete Dictionary


Python Data type conversion

  • Conversion of data types , You just need to use the data type as the function name .

【Python Operator 】

  • Python There is no ++ or -- Self operator

Python Arithmetic operator

  • **  power
  • // Divide and conquer , Returns the integer part of the quotient (  9//2 Output results 4 , 9.0//2.0 Output results 4.0  )
  • Be careful :Python2.x in , Integer divide by integer , Only integers can be obtained . If you want to get the decimal part , Change one of them to a floating-point number .

Python Logical operators ( Not 0 It's true )

  • x and y: Boolean " And " - If x by False,x and y return False, Otherwise it returns y Calculated value .
  • x or y: Boolean " or " - If x Right and wrong 0, It returns x Value , Otherwise it returns y Calculated value .
  • not x:  Boolean " Not " - If x by True, return False . If x by False, It returns True.

Python member operator

  • in: Returns if a value is found in the specified sequence True, Otherwise return to False.
  • not in If no value is found in the specified sequence, return True, Otherwise return to False.

Python Identity operator

  • is : Is to determine whether two identifiers are referenced from an object 【x is y, similar id(x) == id(y)】( notes : id() Function to get the memory address of an object .)
  • is not : Is to determine whether two identifiers are referenced from different objects
  • notes :is Used to determine whether two variable reference objects are the same , == Used to determine whether the values of reference variables are equal .
  • 【 notes 】 In order to improve memory utilization efficiency for some simple objects , For example, some of the smaller int object ,python Take the method of reusing object memory

【Python Basic branch structure 】

Python Conditional statements
  • Python The programming language specifies any non 0 And non empty (null) The value is true,0 perhaps null by false.
  •  python Does not support switch sentence , So multiple conditional judgments , Only use elif To achieve .

Recycling else sentence

  • stay python in ,while … else The cycle condition is false When the else Sentence block ( Not through break Jump out and interrupt )
  • similar if Sentence syntax , If your while There is only one statement in the body of the loop , You can match the statement with while In the same line
  • ——(while (flag): print 'Given flag is really true!')
  • for … else That means ,for There is no difference between the sentences in and the ordinary ones ,else The statement in will be executed normally in the loop ( namely for Not through break Jump out and interrupt ) In case of execution ,while … else Is the same .

【 function 】

  • stay python in , Type belongs to object , Variables have no type :

a=[1,2,3]

a="Runoob"

In the above code ,[1,2,3] yes List type ,"Runoob" yes String type , Variables a There is no type , She's just a reference to an object ( A pointer ), It can be List Type object , You can also point to String Type object .

  • Parameter passing : Pass immutable object and pass mutable object .

Pass immutable object : Such as Integers 、 character string 、 Tuples . Such as fun(a), It's just a Value , No impact a Object itself . For example fun(a) Internal modification a Value , Just modify another copied object , Does not affect the a In itself .

Pass variable object : Such as list , Dictionaries . Such as fun(la), Will be la Really pass it on , After modification fun External la It will also be affected

  • Parameters

Required parameters : You have to pass in functions in the correct order . The number of calls must be the same as when they were declared .

printme(" Call the same function again ");

Key parameters : The order of the parameters when the function is allowed to be called is not the same as when it is declared , because Python The interpreter can match parameter values with parameter names .

printinfo( age=50, name="miki" );

Default parameters : If the value of the default parameter is not passed in , Is considered the default value

def printinfo( name, age = 35 ):
" Print any incoming strings "
print "Name: ", name;
print "Age ", age;
return;

Indefinite length parameter : You may need a function to handle more arguments than you originally declared . These parameters are called indefinite length parameters . With an asterisk (*) The variable name of will hold all unnamed variable parameters .

def printinfo( arg1, *vartuple ):
" Print any incoming parameters "
print " Output : "
print arg1
for var in vartuple:
print var
return;

Python file I/O

  • Keyboard entry

raw_input([prompt]) Function to read a line from standard input , And return a string ( Remove line breaks at the end ):

 input Can receive a Python Expression as input , And return the result to .

str = input(" Please enter :")
print " What you input is : ", str
 Please enter :[x*5 for x in range(2,10,2)]
What you input is : [10, 20, 30, 40]
  • Open and close files

Must use first Python Built in open() function Open a file , Create a file object , Related methods can be called to read and write .

File Object's  close() Method Refresh the buffer of any information that has not been written , And close the file , After that, no more writes can be made .

write() Method Any string can be written to an open file . It's important to pay attention to ,Python Strings can be binary data , Not just words .

tell() Method Tell you the current location in the file

seek(offset [,from]) Method to change the location of the current file .

Python exception handling

  • Two very important functions to deal with python Exceptions and errors in the operation of the program .

exception handling ;

Assertion (Assertions);

  • exception handling

try It works by , When you start a try After the statement ,python Mark in the context of the current program , So you can go back here when the exception occurs ,try Clauses are executed first , What happens next depends on whether an exception occurs during execution .

try:
fh = open("testfile", "w")
fh.write(" This is a test file , For testing exceptions !!")
except IOError:
print "Error: File not found or failed to read "
else:
print " Content written to file successfully "
fh.close()
  • An exception

have access to raise The statement itself triggers an exception

# Defined function
def mye( level ):
if level < 1:
raise Exception,"Invalid level!"
# After triggering an exception , Later code will not be executed
try:
mye(0) # An exception
except Exception,err:
print 1,err
else:
print 2
  • User defined exception

By creating a new exception class , Programs can name their own exceptions .

版权声明
本文为[The art of deceiving Hu]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database