程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Basics

編輯:Python

List of articles

    • 1、python characteristic
      • 1.1、 advantage
      • 1.2、 shortcoming
      • 1.3、 Application field
    • 2、python Basic grammar
      • 2.1、 code
      • 2.2、 identifier
      • 2.3、 Reserved words
      • 2.4、 notes
      • 2.5、 Indent
      • 2.6、 That's ok
      • 2.7、 Input and output
      • 2.8、 Variable
    • 3、 Basic data type
      • 3.1、 establish
      • 3.2、 Operation characteristics
      • 3.3、Number( Numbers )
      • 3.4、String( character string )
      • 3.5、type() and isinstance()
    • 4、 Process control
    • 5、 modular
      • 5.1、 function
      • 5.2、 Modules and packages
      • 5.3、 Scope
    • 6、 class
      • 6.1、 The definition of a class
      • 6.2、 Instantiate the class
      • 6.3、 Inheritance and rewriting
    • 7、 abnormal
    • 8、 other

1、python characteristic

1.1、 advantage

Simple , Open source , Portability , Explanatory 1, object-oriented , Extensibility , Rich library .

1.2、 shortcoming

Slow running speed .

1.3、 Application field

Cloud computing , Scientific computing and artificial intelligence ,web Development , Finance .

youtube、 douban 、 Know almost all python Development .

2、python Basic grammar

2.1、 code

By default ,Python 3 Source file to UTF-8 code , All strings are unicode character string .


Encoding mode

ASCII code : The earliest code , common 128 character , English letters only , Numbers and symbols .
Unicode code : Unify the coding of all languages ,2 byte .
UTF-8 code : To solve the problem Unicode The waste of memory and storage space Unicode Encoding into variable length encoding UTF-8 code .UTF-8 To encode common English letters into 1 Bytes , Chinese characters are usually 3 Bytes ; For example, the transmitted text contains a large amount of English , use UTF-8 Coding saves space .

The common character coding mode of computer system

Unified use in computer memory Unicode code , When it is saved to the hard disk or needs to be transferred, it is converted to UTF-8 code .

When editing with Notepad , Read from file UTF-8 The characters are converted to Unicode Into memory , Save it before Unicode Convert to UTF-8; While browsing the web , The server dynamically generates Unicode Content to UTF-8 Then transfer to browser , If the web source code is similar <meta charset="UTF-8" /> The information of indicates that the web page is marked with UTF-8 code .


2.2、 identifier

from Letter 、 Numbers and underscores form , The first character must be a letter or underscore in the alphabet ; stay Python 3 in , It can be used Chinese as variable name , Not ASCII Identifiers also allow .

2.3、 Reserved words

import keyword
keyword.kwlist # Output all keywords of the current version 

2.4、 notes

Single line comment with # start , Multi line comments can use multiple # Number or ''' and "".

2.5、 Indent

Use indents to represent code blocks , Statements in the same code block must contain the same number of indented spaces , You don't need braces {}.

2.6、 That's ok

  1. Multiple lines in one statement
    Use the backslash \\ To implement multiline statements ; stay [], {}, or () Multiple lines in , No need to use backslash \\
  2. Multiple statements on one line
    Use the following words between sentences ; Division
  3. 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 . Blank lines are not the same as code indentation , Air travel is not python Part of grammar .
    There is no error in writing without inserting a blank line interpreter , The function of blank lines is to separate two pieces of code with different functions or meanings for maintenance or reconstruction .

2.7、 Input and output

  1. Input
input("")
# default input() by str Format , If you use mathematics , You need to convert the format , Such as :
int(input())
  1. Output
print()
# default print() It's a new line , You need to add... At the end of the variable without newline end="":
print( x, end=" " )

2.8、 Variable

Python The variables in the No declaration required ; Each variable must be before use Assignment must be made. ( Can be null ), The variable will not be created until it is assigned a value .

stay Python in , Variable has no type , What we say " type " Is the type of object in variable memory . A variable can be assigned to different types of objects .

3、 Basic data type

Six standard data types

Immutable data (3 individual ) Variable data (3 individual )Number( Numbers )List( list )String( character string )Dictionary( Dictionaries )Tuple( Tuples )Set( aggregate )

3.1、 establish

str = 'python 3.8'
tuple = ('python', 3.8)
list = ['python', 3.8]
dict = {
1: 'python', 'key2': 3.8}
set = {
'python', 3.8}

3.2、 Operation characteristics

character string Tuples list Dictionaries aggregate Indexes YYY key N section YYYNN Splicing operators + and *YYYNN Element deletion NNYYYlen() Return length YYYYYin Judge that the element contains YYYYY
  • Basic operations for lists
# Index slice :
list=[1.2,'1',['a',1],(1,2),{
'name':'zhangsan'}
print(test[2]) # Indexes 
print(test[0:3]) # section , Left closed right away 
['a',1]
[1.2,'1',['a',1]]
list=[1.2,'1',['a',1],(1,2),{
'name':'zhangsan'}
# increase :
list.append('list') # Add at the end 
list.extend(['list',10,'hello']) # Add more , Use list []
list.insert(0,'list') # Index insertion 
# modify 
list[1]='list'
# Delete 
list.remove(1.2) # Output according to the element 
list.pop() # The index defaults to , Delete the last element by default 
del list[0] # Delete... According to index 
list.clear() # Remove all elements 
  • To access a dictionary, use a key instead of an index , Such as :dict['key1']; The keys of the dictionary must be immutable , You can use numbers 、 String or tuple , It can't be a list .
  • A collection is an unordered sequence of non repeating elements

3.3、Number( Numbers )

int、float、bool、complex( The plural )

  • stay Python 3 in , There is only one integer type int, Expressed as a long integer , No, python2 Medium Long.
  • stay Python2 There is no Boolean in , Use numbers 0 Express False, use 1 Express True; Python3 in , hold True and False Define as keyword , But their value is still 1 and 0, And can be added to numbers .

3.4、String( character string )

Shield escape : With r or R Before string quotation marks ;
Three quotes allow a string to span multiple lines .

  1. String formatting

% The operator :

print(' pi is approximately %5.3f' % math.pi)

>>>pi is approximately 3.142

  1. f-string (python3.6 Above support )
    f-string Format method with f start , Followed by a string , The expression in the string is in curly braces {} wrap up , It will replace the calculated value of the variable or expression , comparison % Methods no longer need to be judged %s still %d.
print(f' pi is approximately {
math.pi:.3f}')

>>>pi is approximately 3.142

  1. A string of format() Method
print(' the {} who say "{}!"'.format('knights', 'Ni'))

>>>the knights who say "Ni!"

3.5、type() and isinstance()

Built in type() Function can be used to query the object type of variable :

print(type(a))

<class 'int'>
Or use isinstance To judge :

>>>isinstance(a, int)

>>>True
isinstance and type The difference is that :type() A subclass is not considered a superclass type , and isinstance() Meeting .

4、 Process control

1.if sentence

if...elif...elif... Instead of switch...case... sentence .

2.while sentence

3.for sentence
for...in... Iterate over any sequence , When traversing a sequence of numbers, use range() sentence :

for i in range(0, 10, 1) # Stepping 

4.break and continue sentence

break Used to jump out of the nearest for or while loop ,continue Indicates to continue the next iteration in the loop .

5.else Clause

stay if,while and for Can be used in ;

Cyclic quilt break and continue Do not run on abort else Clause .

6.pass sentence
placeholder .

5、 modular

5.1、 function

  • Parameter passing
    When passing immutable data , The operation within a function does not affect the variable itself ( Similar value transfer ), For variable transfer, the modified external variables are also affected ( Similar to reference passing ).
    Similarly , Variables defined inside a function have a local scope , Define a global scope outside the function . When the internal scope wants to modify the variables of the external scope , Want to use global and nonlocal keyword .
  • Function definition and call form
  1. Default parameters
    When you call a function , If no parameters are passed , Then the default parameters .
  2. Key parameters
    Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared .
  3. Indefinite length parameter
    With an asterisk * Will be imported as tuples , Store all unnamed variable parameters , Add two asterisks ** The parameters of are imported as dictionaries .
  4. Anonymous functions
    Use lambda To create anonymous functions , That is, no longer use def Statement to define functions .

5.2、 Modules and packages

The use of modules allows authors of different modules not to worry about having the same global variable names as each other ; A package is a way of using “ Module name with dot ” To construct the Python Method of module namespace , The use of dotted module names allows authors of multi module software packages not to worry about the same module names as each other .

  • __name__ attribute
    When a module is first introduced by another program , Its main program will run . If you want to make a program block in the module not execute when the module is introduced , You can use __name__ attribute : Each module has one __name__ attribute , When the value is __name__ when , Indicates that the module itself is running , Otherwise it's introduced . usage :
if __name__ == '__main__':
  • When using a variant from fibo import fib, fib2 when ,fibo Undefined .

5.3、 Scope

  • Global and local variables : Variables defined within a function have a local scope , Define a global scope outside the function . Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope .
  • global Change the variable to a global variable .

6、 class

6.1、 The definition of a class

The definition of a class contains the definition of properties and methods , The methods defined by a class generally contain constructor __init__(); Variables defined in methods , Class that only works on the current instance .

  1. Private properties of class
    __private_attrs: Start with two underscores , Declare the property private , Can't be used outside of the class or accessed directly . When used in methods within a class :self.__private_attrs.
  2. Class method
    Inside the class , Use def Keyword to define a method , Different from general function definition , Class method must contain parameters self, And it's the first parameter ,self Represents an instance of a class .
    self The name of is not meant to be dead , You can also use this, But it's better to use it as agreed self.
  3. Private method of class
    __private_method: Start with two underscores , Declare the method private , Can only be called inside a class , Cannot call... Outside of a class :self.__private_methods.

6.2、 Instantiate the class

Class instantiation will automatically call the constructor __init__(), After class instantiation, you can reference properties and methods .

6.3、 Inheritance and rewriting

Subclass ( Derived class DerivedClassName) Will inherit the parent class ( Base class BaseClassName) Properties and methods of .

class people:
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s say : I %d year ." %(self.name,self.age))
# Single inheritance example 
class student(people):
grade = ''
def __init__(self, n, a, w, g):
# Call the constructor of the parent class 
people.__init__(self, n, a, w)
self.grade = g
# Overrides the method of the parent class 
def speak(self):
print("%s say : I %d Year old , reading %d grade " % (self.name, self.age, self.grade))
  • Multiple inheritance
class sample(speaker,student):
  • super() function
    super(Class, self).xxx You can call the parent class ( Superclass ) Methods ,super() Used to solve multiple inheritance problems , It's OK to call the parent class method directly with the class name when using single inheritance , But if you use multiple inheritance , There's a search order involved 、 Repeated calls, etc .

Python 3 It can be used super().xxx In the form of .

  • __call__() Method
    This method enables the class instance object to be called like a normal function , With Object name () In the form of .

7、 abnormal

1. The catching

try...except...else...finally

Abnormal execution occurs except: After the code , No exception execution occurred else: After ,finally It will execute whether there is an exception or not .

2. Throw an exception ( Take the initiative )

raise sentence .

3. User defined exception

Have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly .

8、 other

  1. with as sentence
    Use with as Statement operation context manager (context manager), It can automatically allocate and release resources , Such as :
with open("/tmp/foo.txt") as file:
data = file.read()

  1. Explanatory :Python A program written in C language does not need to be compiled into binary , You can run the program directly from the source code . Inside the computer ,python The interpreter converts the source code into an intermediate form called bytecode , Then translate it into machine language and run . ︎


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved