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

Python notes (I)

編輯:Python

Python Basics

data structure

  1. Integers

For large numbers , for example 10000000000, It's hard to count 0 The number of .Python Allow... In the middle of numbers _ Separate , therefore , It's written in 10_000_000_000 and 10000000000 It's exactly the same . You can also write numbers in hexadecimal 0xa1b2_c3d4.

Be careful :Python There is no size limit to the integer of , In some languages, integers are limited by their storage length

  1. Floating point numbers

For large or small floating-point numbers , It must be expressed by scientific counting , hold 10 use e replace ,1.23x109 Namely 1.23e9, perhaps 12.3e8,0.000012 It can be written. 1.2e-5, wait .

  1. character string
    • Strings are in single quotes ' Or double quotes " Any text enclosed , such as 'abc',"xyz" wait .
    • Escape character ` Can escape many characters , such as n Means line break ,t Represents a tab , character ` We need to escape ourselves , therefore \ The character is ``.
    • In order to simplify the ,Python It is also allowed to use r'' Express '' The internal string does not escape by default .
    • If there are a lot of newlines inside the string , use n It's not easy to read in one line , In order to simplify the ,Python Allowed '''...''' The format of represents multiline content :
 print('''line1
line2
line3''')
  • For the encoding of a single character ,Python Provides ord() Function to get the integer representation of a character ,chr() Function to convert the encoding to the corresponding character :
 >>> ord('A')
65
>>> chr(25991)
' writing '
  • To calculate str How many characters are included , It can be used len() function , If replaced bytes,len() The function counts the number of bytes :
 >>> len('ABC')
3
>>> len(' chinese ')
2
>>> len(b'ABC')
3
>>> len(b'xe4xb8xadxe6x96x87')
6
>>> len(' chinese '.encode('utf-8'))
6
  • In computer memory , Unified use Unicode code , When you need to save to a hard disk or need to transfer , Just switch to UTF-8 code . because Python The string type of is str, In memory with Unicode Express , A character corresponds to several bytes . If you want to transmit over the network , Or save to disk , We need to str Becomes in bytes bytes.Python Yes bytes Type of data with b A single or double quotation mark for a prefix indicates , Pay attention to the distinction 'ABC' and b'ABC', The former is str, Although the content of the latter is the same as that of the former , but bytes Each character of takes up only one byte .
 # With Unicode It means str adopt encode() Methods can be encoded as specified bytes
>>> 'ABC'.encode('ascii')  # Pure English str It can be used ASCII Encoded as bytes, The content is the same .
b'ABC'
>>> ' chinese '.encode('utf-8') # In Chinese str It can be used UTF-8 Encoded as bytes. stay bytes in , Cannot display as ASCII Byte of character , use x## Show .
b'xe4xb8xadxe6x96x87'
>>> ' chinese '.encode('ascii') # In Chinese str No use ASCII code , Because the scope of Chinese coding exceeds ASCII The range of coding ,Python Will report a mistake .
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
# If we read a byte stream from a network or disk , So the data you read is bytes. To put bytes Turn into str, It needs to be used. decode() Method :
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'xe4xb8xadxe6x96x87'.decode('utf-8')
' chinese '
  • because Python The source code is also a text file , therefore , When your source code contains Chinese , When saving the source code , You need to be sure to specify save as UTF-8 code . When Python When the interpreter reads the source code , To make it press UTF-8 Code read , We usually write these two lines at the beginning of the document :
 #!/usr/bin/env python3
# -*- coding: utf-8 -*-

 The first line of comment is to tell Linux/OS X System , This is a Python Executable program ,Windows The system ignores this comment ;
 The second comment is to tell Python Interpreter , according to UTF-8 Code read source code , otherwise , The Chinese output you write in the source code may be garbled .
4. Null value 

Null value is Python A special value in , use None Express .None It can't be understood as 0, because 0 It makes sense , and None Is a special null value .

  1. Variable

stay Python in , Equal sign = It's an assignment statement , You can assign any data type to a variable , The same variable can be assigned repeatedly , And it can be different types of variables . The language with variable type is called dynamic language , It corresponds to static language .

 a = 123 # a Is an integer
print(a)
a = 'ABC' # a Change to string
print(a)
# The language with variable type is called dynamic language , It corresponds to static language .

list and tuple

  1. list
    • list It's an orderly collection , You can add and remove elements at any time .
    • use len() Function to get list Number of elements .
    • Visit with an index list Elements in every position in , Remember the index is from 0 At the beginning .
    • If you want to take the last element , Besides calculating the index position , You can also use -1 Do the index , Get the last element directly , And so on , It can be used -2-3 Index to get the penultimate 2 individual 、 Last but not least 3 individual .
    • list It's a Variable ordered table , You can go list Middle append (append()) Element to end , You can also insert elements (insert()) To the designated location , For example, the index number is 1 The location of :
 classmates.append('Adam')
classmates.insert(1, 'Jack')
classmates.pop()  # Delete list The element at the end
classmates.pop(1) # Deletes the element at the specified location 
  • To replace one element with another , It can be directly assigned to the corresponding index position .
  • list The data types of the elements inside can be different , The element can also be another list.
    1. tuple
  • tuple and list Very similar , however tuple Once initialized, it cannot be modified , No, append()insert() This way .
  • Immutable tuple What's the point ?
 because tuple immutable , So the code is more secure . If possible , It works tuple Instead of list Try your best tuple.
* tuple The trap of : When you define a tuple when , At the time of definition ,tuple The elements of must be determined . however , To define one, only 1 An element of tuple, A comma must be added `,`, To disambiguate :
 t = (1) # The definition is not tuple, yes 1 The number of
t = (1,) # Define a that contains only one element tuple The correct way to write 
  • tuple So-called “ unchanged ” Is said ,tuple Each element of , Direction never changes . If tuple The data type of elements in is list, Then the element points to this list, It cannot be changed to point to other objects , But the point is list It's variable in itself !

Mutable and immutable objects

str Is immutable , and list It's a mutable object .

For mutable objects , such as list, Yes list To operate ,list The internal content will change , such as :

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

And for immutable objects , such as str, Yes str To operate :

>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'

Although the string has a replace() Method , And it did change 'Abc', But variables a In the end, it's still 'abc', How to understand ?

For immutable objects , Call any method of the object itself , It doesn't change the content of the object itself . contrary , These methods create new objects and return , such , It ensures that the immutable object itself is immutable .

conditional

  1. if Complete form of statement
 if < conditional 1>:
< perform 1>
elif < conditional 2>:
< perform 2>
elif < conditional 3>:
< perform 3>
else:
< perform 4>
# Be careful not to write less colons :
  1. input() Judgment problems caused

input() The data type returned is str, If you want to use input() Input data to make judgment conditions , You need to convert first ,Python Provides int() Function will str Convert to integer , When int() Function to find that a string is not a legal number, it will report an error .

loop

  1. for x in ... loop , In turn list or tuple Each element in is substituted into a variable x, Then execute the indented block statement .
  2. while loop , As long as the conditions are met , It's going to keep cycling , Exit the loop if the condition is not met .

dict and set

  1. dict
    • Use the key - value (key-value) Storage , With extremely fast search speed .
    • One key There's only one value, If key non-existent , stay dict Error will be reported when searching in .
 avoid key Non existent error , There are two ways :
 > * adopt in Judge key Whether there is :
>
> ```python
> >>> 'Thomas' in d
> False
> ```
> * adopt dict Provided `get()` Method , If key non-existent , Can return `None`, Or as you specify value:
>
> ```python
> >>> d.get('Thomas')
> >>> d.get('Thomas', -1)
> -1
> ```
* Delete one key, use `pop(key)` Method , Corresponding value Also from the dict Delete in .
* dict It can be used in many places that need high-speed search , stay Python Almost everywhere in the code , Use... Correctly dict It's very important , The first thing to remember is dict Of key Must be immutable . stay Python in , character string 、 Integers are immutable , therefore , You can do it safely key. and list Is variable , Can't do it key.
2. set
* set and dict similar , It's also a group. key Set , The only difference is set No corresponding... Is stored value.
* set It can be seen as a set of disordered and unrepeatable elements in the sense of Mathematics , therefore , Two set Can do intersection in mathematical sense 、 Operations such as Union .
* To create a set, Need to provide a list As input set :
 >>> s = set([1, 2, 3])
>>> s
{1, 2, 3}
  • adopt add(key) Method to add elements to set in , adopt remove(key) Method to delete an element .

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