Introduction to basic types in Python

Source: Internet
Author: User
Tags arithmetic integer division

1. Variables
    • Variables can be not only numbers, but also arbitrary data types
    • Naming conventions: variables are represented by a variable name, and the variable name must be a combination of uppercase and lowercase English, numeric, and underscore _, and cannot begin with a number
    • Python equals "=" is an assignment statement, you can assign any data type to a variable, the same variable can be repeatedly assigned, and can be different types of variables, the variable itself is not fixed type of language called Dynamic language
    • print ' A ', ' B ' #, is a space;

For example:

A= ' ABC '

The meaning is: (1) A string that creates an ' ABC ' in memory

(2) Create a variable named a in memory and point it to ' ABC '

2. String
    • To surround with "or".
    • The string itself contains '

Surround it with "".

Eg: "I ' m OK"

    • The string itself contains "

In the "enclosed"

Eg: ' Learn ' Python ' in Imooc '

    • The string itself contains both ' and '

Escaped with \, escape character \ Not counted into string contents

Eg: ' Bob said \ ' I \ ' m ok\ '. '

    • The common escape characters are:

\ n-Line

\ t---> a tab

\ \--->\ character itself

    • String ' xxx ' and unicode string u ' xxx '
    • Functions in the string:

(1) Upper () turn characters into uppercase letters

(2) isintance (X,STR) can determine if x is a string

(3) Str.capitalize (s) s string first letter uppercase

(4) Str.strip (RM): Removes the character from the RM sequence at the beginning and end of the STR string, and when RM is empty, the default is to remove the whitespace (including ' \ n ', ' \ R ', ' \ t ', ').

    • Raw strings and multiple lines of string

Precede the string with a prefix R, indicating that this is a raw string, the characters inside do not need to be escaped for example: R ' \ ^_^/'

If you are representing multiple lines of string, you can use the expression ".....", or you can use R "...".

    • The Unicode string is represented by U ' ... '.

Unicode string In addition to a more than a u, and ordinary characters no difference, escape character and multiline notation is still valid

3, integers and floating-point numbers
    • The result of integer operation is still an integer, and the result of floating-point arithmetic is still floating-point number, and the result of integer and floating-point arithmetic becomes floating-point number.
    • Integer division, even if not endless, the result is still an integer
    • % for redundancy
    • If you think of the exact result, turn one of the integers into a floating-point number
4. Boolean type
    • True False with (and) or (or) non (not)
    • 0, empty string ' and none ' are considered false in Python, and other numeric and non-empty strings are true
5. List
    • Creating a list list is an ordered collection of elements that can be added and removed at any time
    • Use [] to denote
    • Python is a dynamic language, so the elements contained in the list are not required to be of the same data type.
    • Index starting from 0 take care not to cross the border
    • 1 This index indicates that the last element is not out of bounds
    • Functions in the list:

(1) Add new element to tail---Append ()

(2) Add a new element---> Insert () Two parameters, one is the index number, the second is the new element added

(3) Delete element---->pop () Delete the last element and return this element if you want to delete the element that specifies the subscript as a pop (subscript value)

(4) Replacement element---->l[2]= ' Mise '

(5) the zip () function can turn two lists into a list

6. Tuple Ganso
    • A tuple tuple cannot be modified after it has been created
    • Use () to indicate
    • Create a single-element tuple---> t= (1,) without commas would be considered to assign 1 to T
    • You can create a "mutable" tuple with a list but become just a list t= (' A ', ' B ', [' A ', ' B '])
    • The invariant in a tuple refers to the element in a tuple, which points to never change
7. If statement

NOTE: If statement indents to four spaces

The if followed by the expression is then used: Represents the code block start,

8. Dict Dictionary
    • The dictionary dict Key-value is denoted with {}
    • Dict is looking for value through key.
    • You can use Len () to calculate the length of a key-value count one.
    • Features of Dict:

(1) Fast search speed

(2) Regardless of the number, the speed is the same but the list will gradually decrease as the element increases.

However, Dict occupies a large amount of memory, which wastes a lot of content, and the list consumes less memory.

(3) Since Dict is located by key, the key cannot be duplicated in the same dict

(4) stored key-value sequence pairs are not sequential

(5) Elements that are key must be immutable

9. Set

Usage scenarios:

Sometimes, we only want to dict key, do not care about the value of the key corresponding to the purpose is to ensure that the elements of this set is not duplicated, then, with the set

Characteristics:

Elements are not duplicates, and they are unordered.

Set will automatically remove duplicate elements

Much like Dict, but does not store value

Similar to key in Dict, must be an immutable object

10. Functions
    • Functions are the most basic form of code abstraction.
    • Call Function:

Need to know the name and parameters of the function

    • To write a function:

To use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, returning the function value with the return statement.

    • NOTE: When a statement is executed in the body of a function, once it executes to return, the function executes and returns the result.
    • If there is no return statement, the result is returned after the function is executed, except that the result is none.
    • Return none can be shortened to return.

    • Defining Default Parameters

For example, the Int () function

    Int (' 123 ')

    Int (' 123 ', 8) # The second argument is a conversion, not a pass, the default is decimal, if passed, use the parameters passed in

    • The function's default parameter is to simplify the call.
    • Because the parameters of the function match from left to right, the default parameters can only be defined after the required parameters.
11. Iteration

In Python, given a list or tuple, we can traverse the list or tuple through a for loop, which is the iteration

The For loop can be used on other iterative objects

A collection refers to a data structure that contains a set of elements.
1. Ordered set: List,tuple,str and Unicode
2. Unordered collection: Set
3, unordered set and have Key-value pair: dict

The biggest difference between iterating and accessing an array by subscript is that the latter is a concrete iterative implementation that only cares about the iterative results and does not care how the iterations are implemented internally.

The index iteration----The enumerate () function automatically turns each element into a tuple (index,element), and then iterates over it, acquiring both the index and the element itself.

Value in Iteration Dict

The Dict object has a values () method that returns a list containing all value

The Dict object also has a itervalues () method

The two methods differ:

The values () method actually converts a dict to a list containing value

However, the Itervalues () method does not convert, and it takes value from dict sequentially during the iteration, so the Itervalues () method saves the memory required to generate the list than the values () method

Print itervalues () found that it returned a <dictionary-valueiterator> object, which shows that in Python, a for loop can have an iterative object that is far more than List,tuple,str,unicode. Dict, any iteration object can be used for a for loop

If an object says that it can iterate, we use the For loop to iterate over it, and the iteration is an abstract data operation that does not require any data inside the iteration object.

Value and key in iteration dict:----with the items () or Iteritems () method

Build list:

[X*x for X in range (1,11)]

Conditional filtering:

[X*x for X in range (1,11) if x%2==0]

Multilayer expressions: For loop nesting for loops

[M+n for M in ' ABC ' for n in ' 123 ']

Equivalent:

L=[]for m in ' ABC ': for    N in ' 123 ':        l.append (M+n)

Introduction to basic types in Python

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.