Liao Xuefeng Python (two) Python basic grammar

python basis

  • Python uses indentation to organize code blocks, be sure to follow the customary, stick with the four spaces of indentation.
  • In a text editor, you need to set the Tab automatically converted into four spaces, and spaces to ensure that no mix Tab.
  • Copy and paste function failure, after pasting attention indentation.
  • Finally, be sure to pay attention, Python programs are case-sensitive , if the wrong case, the program will complain.

Data types and variables

type of data

Integer
  • Of any size, positive and negative.
  • Use hex 0x prefix and 0-9, af representation.
  • Integer arithmetic is always accurate, including the division.
  • / As a result of a floating point division, the division result is a floor // is an integer, only taking the integer part, is not rounded.
  • % Of more than take.
Float
  • Decimal point position variable Science and Technology Act, represent different.
  • 1.23e9,12.3e8
  • Floating point operations will be rounding error.
String
  • Single or double quotes enclose text, '' or '' is not a part.
  • Need to use the symbol in quotes need to use an escape character representation.
  • ' "\ N \ t \ are'" wraps tab
  • r '' represents an internal character is not escaped.
  • With '' '' '' You can add multiple lines.
>>>print('''line1
 line2
line3''')

line1
line2
line3

Boolean value
  • True and False, case sensitive.
  • Can not or operation with and and.
Null
  • None attention to the case
  • And can not understand 0

variable

  • Not only is the number can be any type of data
  • Type variable itself is not fixed, arbitrary conversion.
  • Compared with the java language such as static, dynamic languages are more flexible and do not need to declare the type of declaration.
    = A 'ABC'
    B = A
    A = 'the XYZ'
    Print (B)
    at this time is B 'ABC'

constant

  • Meaning variables can not be changed, commonly used capital letters.
  • But essentially it remains a constant, there is no mechanism to protect it from being changed.

another

  • Variable assignment is to establish contact with its true object
  • Let x = y is to make objects x and y point to establish contact, then y changes independent of x.
  • It can be any data as an object, and the variable used to refer to these data objects in the program, is to assign to the variable data and associated variables.

Strings and coding

Character Encoding

  • The ASCII: American invention, comprising a case letters and numbers, a number of symbols, characters 127.
  • GB2312 Code: invented by the Chinese, the Chinese compiled.
  • Unicode: Modern computer systems and general-purpose operating system, does not produce garbled, but not worth on the transfer.
  • UTF-8: variable-length coding, coding can be Unicode characters into characters 1 to 6 depending on the size of the encoded digital. ASCII encoding and UTF-8 can be seen as a part of.
  • Computer memory using a Unicode encoding, notepad need to UTF-8 encoded file conversion, when the file is read into memory Unicode encoding, save time and then converted to UTF-8 saved in the file.
    #### Python string
  • Python3 use Unicode encoding, i.e. adaptation languages.
  • ord function gets an integer of characters () represents, chr function coded into a corresponding character ().
>>>ord('A')
65
>>>chr(66)
’B'
  • Since Python string type str, in memory represented in Unicode, characters corresponding to a plurality of bytes. If you want to transfer over the network or saved to disk, you need to become str to bytes bytes.

  • Python represents bytes of data types with single quotes b prefix or double quotes:

x = b'ABC'
  • To distinguish between 'ABC' and b'ABC ', the former is str, although the latter and the former contents have the same display, but each character bytes of only one byte.
  • In str Unicode represented by the encode () method may be coded as specified bytes.
>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
  • In bytes, the bytes can not be displayed as ASCII characters, use \ x ## display. Conversely, if we read the byte stream from the network or disk, then the data is read bytes. Should become bytes str, we need to use decode () method:
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'
  • If bytes is only a small fraction of invalid bytes can pass errors = 'ignore' Ignore the error bytes.
  • To calculate str contains how many characters you can use len () function. len () function calculates the number of characters of str, if changed bytes, len () function computes the number of bytes.
  • When a string operation, we often encounter str and bytes are interchangeable. In order to avoid the garbage problem, you should always stick with UTF-8 encoding for str and bytes for conversion.
  • If the .py file itself uses UTF-8 encoding, and also affirms # - - Coding: UTF-8 - -, open a command prompt test can show the normal Chinese.

format

  • In Python, using C language and formatting manner consistent, implemented%.
>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
Placeholder Replace content
%d Integer
%f Float
%s String
%x Hexadecimal integer
  • If you are not sure what to use,% s will always play a role, it will forward any data type into a string.

  • By %% to represent one percent

  • Method format () another format string is a string format () method, replacing it with the passed parameters were within the placeholder character string {0}, {1} ......

>>> 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'

Use the list and tuple

list

  • Python built-in data type is a list: list. list is an ordered set, which you can add and remove elements at any time.
>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']
  • Available classmates [0] to access Michael, attention is starting from zero. It will be out of range IndexError, available len (classmates) -1 accessing the last element.
  • len (classmates) output 3
  • classmates.append ( 'Adam') is added to the end elements.
  • classmates.insert (1, 'Jack') add elements to the specified position
  • pop () method removes the last element, pop (10) to delete the specified position of the element.
  • Modifying element may specify the location of direct assignment, classmates [1] = 'Sarach
  • list may be different types of elements may be additionally a list.
  • 0 empty list length.

tuple

  • The difference between tuple and tuple Once the initialization list is not changed.
  • No append, insert method.
  • Note that when defining elements must be determined.
  • The definition of a digital time
>>> t = (1,)
>>> t
(1,)

empty

>>> t = ()
>>> t
()
  • Note that when re tupol contained in the list, list is not changed, but the elements of the list variable.
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

Conditional

condition

  • Note that if a code block with indented
  • Note colon
  • Note that elseif is elif

Reconsideration input

  • input () Returns the type str
  • May be int () converts the type of data str is an integer type

cycle

cycle

for ... in loop
  • for x in ... cycles each element is assigned to the variable x, and then performs indented block.
    And calculate 1-10
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)

One by one print element

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)
  • (5) generating a sequence range is less than an integer of from 0 to 5
while loop
  • Implemented within the sum of all odd 100
sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

break

  • Leaves the loop early. Print 10 exit.
n = 1while n <= 100:
    if n > 10: # 当n = 11时,条件满足,执行break语句
        break # break语句会结束当前循环
    print(n)
    n = n + 1
 print('END')

continue

  • Out of the current cycle, the next cycle started directly.
n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0: # 如果n是偶数,执行continue语句
        continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
print(n)

Print out 1,3,5,7,9.

  • Do not abuse the break and continue statements!
    Most cycle does not need to use the break and continue statements!

Use dict and set

dict
  • dict full name dictionary, dictionaries, also known as the map, using the key-value store (key-value)
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
  • Compared to the list, you can quickly find out the elements.
  • The value should be based on key values ​​based on key release, can be used repeatedly.
>>> d['Jack'] = 90
>>> d['Jack']
90
>>> d['Jack'] = 88
>>> d['Jack']
88
  • By key in determining whether there is:
>>> 'Thomas' in d
False
  • By get () method determines whether the value is present.
  • POP value for key (key) corresponding method will be deleted
  • Note dict order as the key internal storage is not related.
  • Note that the dict key must be immutable objects, strings, integers, and so can, list no.

set

  • Collection is a set of key, but not the stored value.
  • No duplicate elements. Repeat elements are automatically filtered.
  • When you create a set, you need to provide a list as a set of inputs
  • add () to add, remove () to delete.
  • It can be regarded as a set of unordered and no duplicate elements in a mathematical sense
  • The same can not be put in variable object.

Immutable objects

  • Str immutable object has replace () method
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'

replace the value of a retrieves the abc, and Abc it becomes returned.
But had a change in value.
This method is equivalent to a new string value retrieved created and returned.

Released two original articles · won praise 0 · Views 35

Guess you like

Origin blog.csdn.net/jing123723/article/details/104749406