Python Learning notes 1--python Basics

Source: Internet
Author: User

A. data types and variables

    1. Integers: hexadecimal is represented by 0x prefixes and 0-9,a-f
    2. Floating-point numbers: decimals, scientific notation: 10 is replaced by e; integers and floating-point numbers are stored inside the computer in different ways, integer operations are always accurate (including division), and floating-point operations may have rounding errors
    3. Strings and encodings

(1) Any text enclosed in single quotes ' or double quotation marks.

(2) You can use the escape character \ to identify ' and '. (\ n: NewLine (python allows the "..." format to represent multiple lines of content, eg.) ' ' a...b...c '), \ t: tab, \ \: denotes \,)

(3) R ' means the character inside of ' is not escaped by default

(4) Code:

ASCII encoding : 1 bytes (including uppercase and lowercase letters, numbers, and some symbols)

Unicode encoding : All languages are unified into a set of code, clear the Problem of garbled (2 bytes, ASCII-encoded characters in Unicode encoding, in front of 8 0)

UTF-8: Converts Unicode encoding to "variable length encoding" Because Unicode encoding requires more storage space than ASCII encoding, and is not saved if the text is all in English.

~~ASCII encoding can actually be seen as part of the UTF-8 code.

~ ~ in computer memory, Unicode encoding is used uniformly, when it needs to be saved to the hard disk or when it needs to be transferred, it is replaced with UTF-8 encoding.

(5) in the Python3 version, strings are encoded in Unicode, which supports multiple languages. The Ord () function gets an integer representation of the character, and the Chr () function converts the encoding to the corresponding character.

(6) If you want to transfer on the network, or save to disk, you need to change the string into bytes in bytes, with the b prefix of single or double quotation marks: x=b ' ABC '. Encode () changes the character to Bytes,decode () to convert bytes to characters.

(7) When manipulating strings, we often encounter the mutual conversion of STR and bytes. To avoid garbled problems, you should always use UTF-8 encoding to convert str and bytes.

  (8) Because the Python source code is also a text file, so when your source code contains Chinese, it is necessary to save the sources, you must be sure to save the UTF-8 encoding. When the Python interpreter reads the source code, in order for it to be read by UTF-8 encoding, we usually write these two lines at the beginning of the file:

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

The first line of comments is to tell the Linux/os x system that this is a python executable and the Windows system ignores this comment;

The second line of comments is to tell the Python interpreter to read the source code according to the UTF-8 encoding, otherwise the Chinese output you write in the source code may be garbled.

Affirming that UTF-8 encoding does not mean that your. py file is UTF-8 encoded, you must also make sure that the text editor is using UTF-8 without BOM encoding:

(9) Format:%

%d: integer

%f: Floating point

%s: string

%x: Hexadecimal integer

%%:%

4. Boolean values: True and False;and, or and not operations

In Python, when and and or perform boolean operations, they do not return Boolean values, but instead return one of the values they actually compare. The value of a left-to-right calculus expression in a Boolean context. For and, if all values in the Boolean context are true, and returns the last value, and if a value in the Boolean context is false, and returns the first false value. For or, if a value is true, the first truth is returned, and if all values are false, the last false value is returned.

5. Null value: None, not understood as 0.

6. Variable: The variable name must be a combination of uppercase and lowercase English, numeric, and _.

Dynamic Language:

Static language:

B:abc

7. Constants: Constants are typically represented in all uppercase variable names

8.1.1+1.1+1.1=3.3000000000003: Due to loss of precision

two. Conditional Judgment

three. Loops

(1) for X in..

(2) while

Four. List

(1) List is an ordered set of elements that can be added and removed at any time

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

(2) The Len () function can be used to obtain the number of list elements, with the index to access the elements of each position in the list, remember that the index is starting from 0 when the index is out of range, Python will report a indexerror error, so to ensure that the index does not cross the border, Remember that the index of the last element is Len (classmates)-1.

(3) If you want to take the last element, in addition to the index location, you can also use-1 to index, directly get the last element.

(4) The list element can also be another list

Five. Ganso Tuple

(1) Immutable list (point to Never change); In addition to changing the contents of the list, other methods apply to tuples; therefore: indexes, slices, Len, print are available; append, Extend, Del, etc. are not available

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

(2) The code is more secure because the tuple is immutable. If possible, you can use a tuple instead of a list as much as possible.

(3) Define an empty tuple:t = ()

(4) t= (1): The definition is not a tuple, but a 1 this number, only 1 elements of a tuple definition must be added a comma. t= (1,)

Six. Dictionary

(1) Python Built-in dictionary: dict support, Dict full name dictionary, also known as map in other languages, using key-value (Key-value) storage, with extremely fast search speed

my_dict={' John ': 1234, ' Mike ': 5678, ' Bob ': 8765}

my_dict[' Bob ']

(2) Given a name, for example ‘Michael‘ 95 , dict in the internal can directly calculate the Michael corresponding storage score "page", that is, the 95 number of memory address, directly removed, so the speed is very fast

(3) The order of Dict internal storage is not related to the order in which key is placed.

(4) Compared with the list, the search and insertion speed is very fast, does not increase with the increase of key, need to occupy a lot of memory, memory waste much.

(5) To ensure the correctness of the hash, as a key object can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be a key

(6) Dictionary budget compliance method

Len (my_dict)

Key in my_dict quickly determines if key is a key in the dictionary: O (1); ==my_dict.has_key (key)

Key in My_dict Enumeration dictionary: key is unordered

My_dict.items () all key-value pairs; The returned key-value pairs are in the form of a list

My_dict.keys () All keys

My_dict.values () All values

My_dict.clear () Empty dictionary

Seven. Collection

(1) Unordered non-repeating element (key) set; similar to dictionary, but without "value"

Created: X=set ()

X={key1,key2,...}

Add and remove X.add (' body ')

X.remove (' body ')

Operators for Collections:-& | ! =

(2) The set principle is the same as the dict, so it is also not possible to put mutable objects, because it is not possible to determine whether two mutable objects are equal, and there is no guarantee that the set will "have no duplicate elements"

(3) Chinese word segmentation ———— algorithm: Forward maximum match (word that takes as long as possible from left to right)

(1) Load dictionary: lexicon.txt

def load_dic (filename):        f= open (filename)        word_dic=set ()        max_length=1         for inch f:               word=unicode (Line.strip (),'utf-8')               Word_dict.add (word)                if len (word) >max_len:                      max_len=len (word)        return Max_len, Word_dict

(2) forward maximum matching participle

deffmm_word_seg (sent,max_len,word_dict): Begin=0 Words=[] Sent=unicode (Sent,'Utf-8')         whilebegin<Len (Sent): forEndinchRange (begin+max_len,begin,-1):                      ifSent[begin:end]inchword_dict:words.append (Sent[begin:end]) Breakbegin=EndreturnWords

(3) Application

Max_len,word_dict=load_dict ('lexcion.txt')   sent=raw_input (' Input a sententce: ' )     =fmm_word_seg (sent,max_len,word_dict) for in words:         Print Word

Python Learning notes 1--python Basics

Related Article

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.