Chapter-python Foundation

Source: Internet
Author: User
Tags ord

1 data types and variables 1.1 integers

  16 binary number front plus 0x

1.2 Floating point

  1.23x109 is 1.23e9.

1.3 string

  Single or double quotation marks

To enter quotation marks can be escaped with \

Precede output with R to indicate that it is not escaped after

Example: Print (r "\\\\t\\")

Indicates that multiple lines of content "' contents are directly inside the " "content will be retained as a carriage return

1.4 Boolean value

Only True and False two kinds of values

Can perform an and or not operation

1.5 Null value

  None indicates

1.6 Variables

The variable name must be a combination of case English , numeric , and 下划线 number, and cannot start with a number

Python is a dynamic language , when assigning a value without a tube type, and when creating a new one without declaring a type

  Static languages such as Java, to declare types, and to assign values to types

1.7 Constants

  Constants are usually represented with all uppercase variable names

1.8 Division

/The result of the calculation is always floating-point

Called the floor except that the result is the largest integer less than the result of the division

2 string and encoded 2.1 character encodings

At first, the computer takes 1 bits as a byte, so the largest represented integer is 255.

The first encoding is only 127 characters, and a byte is used, which is the ASCII

Due to the large number of Chinese, the use of two bytes , forming a GB2312

Unicode is the language in which all languages are programmed, with two bytes and a few words with four bytes

As a result of this space, thus forming a variable length of the UTF-8, the commonly used English letters are encoded into 1 bytes, Chinese characters are usually 3 bytes, only very rare characters will be encoded into 4-6 bytes

2.2 Python string

Python 3 is a Unicode character set

Use Ord and CHR to match the actual encoding to the character

  Ord (' character ') gets the integer representation of the character

  chr (integer) to derive characters from integers

You can also typically use hexadecimal notation for characters

  

Normal string one character corresponds to a number of bytes

B ' String ' a character is represented by only one byte, used for network transmission or saved to disk

Convert to another encoding type

String. encode (' Target code ')

Usually have ASCII and utf-8

Calculates how many characters a string has

Len (String)

    

  

To avoid garbled problems, you should always use UTF-8 encoding to convert str and bytes

  

  In the Chinese source code, it is best to save the format as UTF-8

  

Usually the file header writes the following code

#!/usr/bin/env python3#-*-coding:utf-8-*-

The first sentence indicates a Linux system this is a Python program

The second sentence tells the Python interpreter to read the source code with UTF-8 encoding

Processing of strings

Replace method

String A. Replace ("To replace", "Replace with")

Note: The returned result is the replaced content, but the string a itself does not change

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

3 formatting

 ' String content placeholder '% (contents of placeholder)

>>> ' Hello,%s '% ' world ' Hello, world ' >>> ' Hi,%s, you have $%d. '% (' Michael ', 1000000) ' Hi, Michael, y The OU has $1000000. '

Common placeholders:

  

Complement 0

>>> '%2d-%02d '% (3, 1) ' 3-01 '

Limit the number of decimal places:

>>> '%.2f '% 3.1415926 ' 3.14 '

Want to output% expressed in percent

>>> ' growth rate:%d percent '% 7 ' growth rate:7% '

  

3 List and tuple3.1 list

Defined

classmates = [' Michael ', ' Bob ', ' Tracy ']

Gets the length of the list

  Len (list name)

Get Data

  Name [index]

Start from left to right 0

Start from right to left -1

List is a mutable, ordered table

Add data

Name. Append (What's added)

The added data is put to the last

Inserting data

Name. Insert (Location, data)

Data is placed in place, and subsequent data are deferred

Delete data

Name. Pop ()

Delete last Element

Name. Pop Location

Remove an element from a location

Replace element

Name [location]= newly-changed data

The data type of the elements inside the list can also be different

The list element can also be another list

At this point the data can form a multilevel [] form

Sort of List

List name. Sort ()

Sort by alphabetical dictionary, size of numbers

3.2 Tuple

 Tuple is also called tuple

  Once initialized, it cannot be modified.

Defined

Classmates = (' Michael ', ' Bob ', ' Tracy ')

Definition of empty tuple

t = ()

Definition of a single element tuple

t = (1,)

  Note : When a tuple element has an element that is similar to a list that can be changed, the tuple becomes "mutable".

Therefore, it is best to ensure that the element is immutable when initializing a tuple

4 condition judgment and circulation 4.1 pieces judgment

 Structure of the IF statement

If < condition judgment 1>:    < execution 1>elif < conditional judgment 2>:    < execution 2>elif < conditional judgment 3>:    < execution 3>else:    < Executive 4>

Feature: only one of the function bodies will be executed

4.2 Input

  Get user input

variable = input ("input hint")

Birth = input (' Birth: ')

The data type returned by input () is a string type

String type to int type

    int String

Similarly, converting to float is

    float String

4.3 Loop 4.3.1 for: In loop

  You can iterate over the elements of a list or a tuple

names = [' Michael ', ' Bob ', ' Tracy ']for name in Names:    print (name)
sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]:    sum = sum + xprint (sum)

Generating integer sequence methods

    Range (Integer a)

Generates a sequence of integers starting from 0 to less than integer a

sum = 0for x in range (101):    sum = sum + xprint (sum)
4.3.2 While loop

  Meet the conditions on the loop, not satisfied on the exit

sum = 0n = 99while n > 0:    sum = sum + N    n = n-2print (sum)
5 Dict and set5.1 dict

 Dict is the dictionary type, full dictionary, in other languages called Map, is based on key-value pairs

Features: find speed blocks the actual order of storage is inconsistent with the order in which key is placed

Reason for querying blocks

Because the storage key value pair of time to do the processing, for the key value can calculate the corresponding storage location , with the dictionary pinyin query a reason

It is for this reason that the order of the actual storage is inconsistent with the order of key

Defined

D = {' Michael ': Up, ' Bob ': +, ' Tracy ': 85}

Get value

1 Dictionary name [key value]

d[' Michael ']

2 dictionary names. Get (key)

D.get (' Thomas ')

When the key value entered is not in the dictionary, it will output a value of None

At this point, you can also set the name of the dictionary when the value of the output itself is encountered. Get (default value when key is None)

D.get (' Thomas ',-1)

Determine if key is in the dictionary

Key in dictionary name

' Thomas ' in D

Setting the value

Dictionary name [key value]= value

d[' Adam '] = 67

Repeatedly assigns a value to the same key, and the last value stored is the last assigned value

Delete value

Dictionary name. Pop (key)

D.pop (' Bob ')

Note: The dictionary type key is best set to an immutable object

Because if the key value changes, the stored content address will change accordingly.

5.2 Set

  Characteristics:

Store only a set of keys

Stored keys are not duplicated , and repeated additions have no effect

denoted by curly braces

An operation commonly used to make a set

Defined

Set name = Set ([Key, Key, key])

>>> s = Set ([1, 2, 3]) >>> S{1, 2, 3}

adding elements

Set name. Add (Key)

>>> S.add (4) >>> s{1, 2, 3, 4}

Delete Element

Set name. Remove (key)

>>> S.remove (3) >>> s{1, 2}

Application, two set can do the set and intersection

>>> S1 = set ([1, 2, 3]) >>> s2 = Set ([2, 3, 4]) >>> S1 & s2{2, 3}>>> s1 | S2{1, 2, 3, 4}

Chapter-python Foundation

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.