Python Basics-Data types

Source: Internet
Author: User
Tags iterable mathematical constants

When the statement ends with a colon:, the indented statement is treated as a block of code.
Indentation has pros and cons. The advantage is that you are forced to write the formatted code, but there is no rule that indents are a few spaces or tabs. In accordance with established management, you should always stick to the indentation of 4 spaces.
The Python program is case-sensitive, and if the case is written incorrectly, the program will error.
Data type

A computer is a machine that can do mathematical calculations as the name implies, so a computer program can handle a variety of values. However, the computer can handle far more than the numerical value, but also can deal with text, graphics, audio, video, web and other kinds of data, different data, need to define different data types. In Python, there are several types of data that can be processed directly:
Data type
Numbers (shaping, long-shaped, floating-point, plural)
String
List
Meta-group
Dictionary
Collection
Integer

Python can handle integers of any size, including, of course, negative integers, which are represented in the program in the same way as mathematically, for example: 1,100,-8080,0, etc.
Computer because of the use of binary, so, sometimes hexadecimal notation is more convenient, hexadecimal with 0x prefix and 0-9,a-f, such as: 0XFF00,0XA5B4C3D2, and so on.
Floating point number

Floating-point numbers, which are decimals, are called floating-point numbers because, when represented by scientific notation, the decimal position of a floating-point number is variable, for example, 1.23x109 and 12.3x108 are exactly equal. Floating-point numbers can be written in mathematical notation, such as 1.23,3.14,-9.01, and so on. But for very large or very small floating-point numbers, it must be expressed in scientific notation, the 10 is replaced with E, 1.23x109 is 1.23e9, or 12.3e8,0.000012 can be written 1.2e-5, and so on.
Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! ), and the floating-point operation may have rounding errors.
String

strings are arbitrary text enclosed in single quotes ' or double quotes, such as ' abc ', ' XYZ ', and so on. Note that the ' or ' itself is only a representation, not a part of the string, so the string ' abc ' only a,b,c these 3 characters. If ' itself is also a character, then you can use "", such as "I m OK" contains the characters are I, ', M, space, o,k these 6 characters.
What if the inside of a string contains both ' and contains '? You can use the escape character \ To identify, for example:
' I\ ' m \ ' ok\ '! '
The string content represented is:
I ' m "OK"!
Escape character \ Can escape many characters, such as \ n for newline, \ t for tab, character \ itself to escape, so \ means the character is \, you can print the string in Python's interactive command line () to see:
Print (' I\ ' m OK. ')
Effect:

Print (' I\ ' m learning\npython. ')

Print (' \\n\ ')

If there are many characters in the string that need to be escaped, you need to add a lot of \, in order to simplify, Python also allows to use R ' ' to indicate that the string inside of ' is not escaped by default
Print (' \\t\ ')

Print (R ' \\t\ ')

If there is a lot of line wrapping inside the string, it is not good to read it in a line, in order to simplify, Python allows the "..." format to represent multiple lines of content

Note When you enter multiple lines of content, the prompt changes from >>> to ..., prompting you to enter on the previous line, note ... is a prompt, not part of the code
After entering the Terminator ' and parentheses ', execute the statement and print the result.
If you write a program that coexists with a. py file, it is:
Print ("' Line1
Line2
Line3 ")

Boolean value

The Boolean value is exactly the same as the Boolean algebra, with a Boolean value of only true, false two, or true, or false, in Python, which can be used to indicate a Boolean value directly with True, false (note case), or by Boolean operations:

Boolean values can be operated with and, or, and not.
The and operation is associated with an operation, and only the result of all True,and operations is true:

An OR operation is an operation, as long as one of the true,or operation results is true:

The not operation is a non-operation, which is a single-mesh operator that turns true into False,false true:

Boolean values are often used in conditional judgments
Null value

The null value is a special value in Python, denoted by none. None cannot be understood as 0, because 0 is meaningful, and none is a special null value.

Variable

The concept of variables is basically the same as the equation variables in junior algebra, but in computer programs, variables can be not only numbers, but also arbitrary data types.
Variables are represented by a variable name in the program, and the variable name must be a combination of uppercase and lowercase English, numeric, and _, and cannot start with a number, such as:
A = 1
Variable A is an integer.
t_007 = ' T007 '
The variable t_007 is a string.
Answer = True
The variable answer is a Boolean value of true.
In Python, equals = is an assignment statement that can assign any data type to a variable, the same variable can be repeatedly assigned, and can be a variable of different types, for example:
A = 123 # A is an integer
Print (a)
A = ' ABC ' # A becomes a string
Print (a)
Double quotes with single quotes are all strings


Variables are stored in memory in the form of:

In Python, each variable is created in memory, and we can see the value in memory by a variable

Change the value of a variable in python with a pointer
x = 1 indicates that x points to the address stored in memory as 1, and the address is 1767137504.
Y = 2 indicates that Y points to the address stored in memory as 2, and the address is 1767137536.
That is, X, Y points to a different address, after you have 4,y = 5:

After executing x = y
X points to the memory that Y points to, and they all point to the same piece of memory, just like the pointer in C.

Linux under

(as if Linux (64bit Ubuntu) and Windows (64bit Windows10) occupy a different amount of memory)
In Python, the initial initialization of something stored in memory cannot be changed, and all we can change is its point.
For



You can see that the address of X and 1 is an address, and the address of Y and 2 is an address.
So
Executing x = 1, the interpreter creates an integer and a variable x, and points x to the memory address where 1 is located:
Executing x = y, the interpreter creates the variable y and points y to the memory address of x pointing to a
If the x is re-assigned ABC x= ' ABC ', then the interpreter creates the string ' abc ' and changes the direction of X to the memory address where ' ABC ' is located, but Y does not change

Assigning a variable x = y is the variable x pointing to the real object, which is what the variable y points to. The assignment of the variable y does not affect the direction of the variable x. They are independent according to different operations pointing to different addresses.
Python supports a variety of data types, within a computer, you can think of any data as an "object", and variables are used in the program to point to these data objects, the variable is assigned to the data and variables associated.
Constant

So-called constants are immutable variables, such as the usual mathematical constants π is a constant. In Python, constants are typically represented in all uppercase variable names:
PI = 3.14159265359
But in fact pi is still a variable, Python does not have any mechanism to guarantee that PI will not be changed, so it is only a customary usage to use all uppercase variable names to denote constants.
Finally, explain why the division of integers is also accurate. In Python, there are two types of division, one division is/:

>> 10/33.3333333333333335
/division evaluates to a floating-point number, even if two integers are evenly divisible, the result is a floating-point number:
>> 9/33.0
There is also a division is//, called the floor except, the division of two integers is still an integer:
>> 10//33
The floor of an integer is removed//is always an integer, even if it is not endless. To do the exact division, use/can.
Because//division takes only the integer part of the result, Python also provides a remainder operation that gives the remainder of dividing two integers:
>> 10% 31
The result is always an integer, regardless of whether the integer is a//division or the remainder, so the result of the integer operation is always accurate.
Note: There is no size limit for python integers, and integers for some languages are limited by size depending on their storage length, such as Java's range of 32-bit integers is limited to-2147483648-2147483647.
Python also has no size limit for floating-point numbers, but is represented as INF (infinity) beyond a certain range.

List

One of the data types built into Python is the list: lists. A list is an ordered set of elements that can be added and removed at any time.
For example:

M is a list
Use the Len () function to get the number of list elements:
Len (M)

Use an index to access the elements of each location in the list, remembering that the index starts at 0:
M[0]
M[1]

Python will report a indexerror error when the index is out of range, so make sure the index is not out of bounds, and remember that the index of the last element is Len (M)-1.

If you want to take the last element, in addition to calculating the index location, you can also use 1 to index, get the last element directly:
M[-1]

Get the bottom 2nd, the bottom 3rd one:
M[-2]
M[-3]


List is a mutable, ordered table that appends elements to the end of the list:
M.append (' d ')

You can also insert elements into the specified position, such as the index number 1:
M.insert (1, ' e ')

If there is data at that location, insert the current data into that location other data moves backwards

To delete the element at the specified position, use the pop (i) method, where I is the index position:
For example:
M.pop (1)

To replace an element with another element, you can assign a value directly to the corresponding index position:
m[1]= ' B '


The data types of the elements in the list can also be different, such as:
L = [' A ', 123, True]

The list element can also be another list, such as:
s = [' Python ', ' Java ', [' asp ', ' php ', ' go '], ' C + + ', ' C ']

You can also disassemble and write
m=[' asp ', ' php ', ' go '
s=[' python ', ' Java ', M, ' C + + ', ' C ']

Get Java
S[1]

Get PHP

S can be seen as a two-dimensional array
If a list does not have an element, it is an empty list with a length of 0:

Tuple

Another ordered list is called a tuple: a tuple. Tuple and list are very similar, but a tuple cannot be modified once initialized
A= (' A ', ' B ', ' C ')


Now, a This tuple cannot be changed, nor does it have a append (), insert () method. The method to get the element is the same as list, using a[0],a[-1], but cannot be assigned to another element.

When a is a tuple, appending the data using the Append method will give an error.

What is the meaning of immutable tuple? Because the tuple is immutable, the code is more secure. If possible, you can use a tuple instead of a list as much as possible.
When a tuple is defined, the elements of a tuple must be determined when defined, such as:

Define a tuple of only 1 elements, if so defined:

The definition is not a tuple, is 1 this number! This is because parentheses () can represent both tuples and parentheses in mathematical formulas, which creates ambiguity, so Python rules that, in this case, the parentheses are calculated and the result is naturally 1.
Therefore, only 1 elements of a tuple definition must be added with a comma, to eliminate ambiguity:

A tuple is immutable, but if the stored data has a list of lists that are mutable

In fact, a tuple does not change only the contents of the list

The data pointed to in a tuple is always immutable, the list address is constant, the contents of the list can change, and the list is an address, and the contents of the address can vary.
On the surface, the elements of a tuple do change, but in fact it is not a tuple element, but a list element. The list that the tuple initially points to is not changed to another list, so the so-called "invariant" of a tuple is that each element of a tuple is directed to never change. That point ' a ', it cannot be changed to point to ' B ', pointing to a list, cannot be changed to point to other objects, but the list itself is variable! The invariant of all tuples should be that each element of a tuple cannot change itself.
If a tuple saves a variable, the variable changes the element in the tuple as long as it is assigned to a tuple.


Dict

Python built-in dictionary: dict support, Dict full name dictionary, in other languages also known as map, using key-value (Key-value) storage, with a very fast search speed.
Dict data is obtained from key-value pairs, which are also stored as key-value pairs
Storage: D = {' xiaoming ': Xiaohong, ' Xiaowang ': 85}
Get: d[' xiaoming ']

Why does Dict look so fast? Because the implementation principle of dict and look dictionary is the same. Suppose the dictionary contains 10,000 characters, we need to look up a word, one way is to turn the dictionary back from the first page, until we find the word we want, this method is to find the element in the list method, the larger the list, the slower the lookup.
The second method is to search the dictionary's index table (such as the Radicals) for the corresponding page number, and then go directly to the page, find the word. Whichever word you look for, this is very fast and does not slow down as the dictionary size increases.
Dict is the second implementation, given a name, such as ' Michael ', Dict can directly calculate Michael's corresponding storage Score "page number", that is, 95 of the memory address of the number stored, directly out, so the speed is very fast. This Key-value storage method, when put in, must be based on the key to calculate the storage location of value, so that the time can be taken by the key to get the value directly.
Dictionaries are unordered, such as adding a data and then taking out.


Since a key can only correspond to one value, the value is placed multiple times for a key, and the following values will flush the previous value out:

Equivalent to re-assignment
If the key does not exist, it will error

There are two ways to avoid a key that does not exist:
One is to determine whether a key exists by in:

The second is the Get () method provided by Dict, if key does not exist, you can return none, or the value you specify:
Exist



does not exist

When none is returned, the interactive environment of Python does not display the results.
Using the custom return value

Delete a key
With the pop (key) method, the corresponding value is also removed from the dict:

Deleting a nonexistent value will cause an error

The order in which the dict is stored inside is not related to the order in which the key is placed.
Compared with list, Dict has the following features:
The speed of finding and inserting is very fast and will not slow with the increase of key;
It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
The time to find and insert increases as the element increases;
Small footprint and little wasted memory.
So, Dict is a way of exchanging space for time.
Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object.
This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).
To ensure the correctness of the hash, the object as a key 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:

#dict键值对互换

Mydict={"A": 1, "B": 2, "C": 3}

mydict_new={}

For Key,val in Mydict.items ():

mydict_new[val]=key

Print (mydict_new)

Mydict={"A": ' A ', "B": ' B ', "C": ' C '}

Mydict_new=dict ([Val,key] for Key,val in Mydict.items ())

Mydict={"A": ' A ', "B": ' B ', "C": ' C '}
Mydict_new=dict (Zip (mydict.values (), Mydict.keys ()))
Print (mydict_new)
Set

Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
To create a set, you need to provide a list as the input collection:

The parameter passed in [1, 2, 3] is a list, and the displayed {1, 2, 3} just tells you that this set has 3 elements in the inside of a single, and that the order shown does not indicate that the set is ordered.
Repeating elements are automatically filtered in set:


You can add elements to the set by using the Add (key) method, and you can add them repeatedly, but without effect:

You can delete an element by using the Remove (key) method:

Set can be regarded as a set of unordered and non-repeating elements in mathematical sense, so two sets can do the intersection and set of mathematical meanings, and so on:
Intersection

and set

The only difference between set and dict is that it does not store the corresponding value, but 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 the two Mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set.
Put list into set, will error.

Slice
Taking a list or tuple element is a very common operation.
Define a list
l=[1,2,3,4,5, ' A ', ' B ', ' C ', ' d ']
Take the top three
can use
The first way
l=[1,2,3,4,5, ' A ', ' B ', ' C ', ' d ']
Print (L[0])
Print (l[1])
Print (l[2])
A second approach
You can also use the loop
l=[1,2,3,4,5, ' A ', ' B ', ' C ', ' d ']
M=[]
N=6
For I in range (n):
M.append (L[i])
Print (m)
A third approach
Using the first method is inefficient, the second cycle is more cumbersome
Python provides slicing operations that can greatly simplify this tedious operation
l=[1,2,3,4,5, ' A ', ' B ', ' C ', ' d ']
D=l[0:6]
Print (d)
L[0:6] Indicates that the fetch starts at index 0 until index 6, but does not include index 6. That is, index 1, 2, 3, 4, 5, ' a ' is exactly 6 elements (A's index is 5 that is 6-1, the first parameter is the index from which to start, the second is the end of the index to N-1 or the second parameter is understood to take the number of the first parameter) slice can greatly simplify the tedious operation.
Slices can fetch data from the front, or they can fetch data from the back



Iteration (Iteration)

Iteration: Iteration
Iterative: iterable
Iterators: Iterator
Iterative comparison iterators are more abstract, which is like traversing a dictionary dict, using for...in ... Operation, which is called iteration, and the behavior that can traverse or can iterate is called iterative, whereas an iterator is an operator or a perpetrator of a specific iteration, and in Python a function specifically returns an Iterator object. This object can also traverse the dict through the properties of next, which we call the iterator
In Python a list or tuple, to access one of the elements, can be accessed by subscript, if you want to access all the elements, you can use a for loop to traverse the list or tuple, and this traversal is called iteration.
In Python, the iteration passes for: In.. To complete.
Python's for loop can be used not only on lists and tuples, but also on other objects that can be iterated
For example:
D = {' name ': ' Jack ', ' Age ': ' ' job ': ' Coder '}
Print (d) # First output dict
Print ("Iteration key")
For S in D:
Print (s)

Print ("Iteration value")
For value in D.values ():
Print (value)
Print (' iterative key and value ')
For K, V in D.items ():
Print (' key:%s,value:%s '% (k, v))

Output results


Strings can also iterate, iterating through each character:
For i in ' Hello World ':
Print (i,end= "")


Output results


Iterative (iterable)
If a list, a tuple, or a string can traverse, that is, an iterative behavior, called an iterative

Results

Numbers of type int are not iterative
strings, List,tuple,dict,set, etc. can iterate
Python's built-in enumerate function can turn a list into an index-element pair so that you can iterate over the index (subscript) and the element (key) itself in the For loop.

Output Result:

Print ("list becomes index-element pair")
For Index,value in enumerate ([' First ', ' second ', ' third ']):
Print (Index, ":", Value)
Print ("Dict becomes index-element pair")
For Index,key in enumerate ({' First ': 1, ' second ': 2, ' Third ': 3}):
Print (Index, ":", Key)

The object of the iteration is actually a list, each element of the list is a tuple, and each tuple object has n elements, so that it cannot be taken simply by means of the for-X in list: it should be possible to write for n1,n2,n3...in List: (to ensure that the number of tuples is equal)


Results

If not equal will error

Results



Iterators (Iterator)
An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.
There are several types of data that can be directly acting on a For loop:
A class is a collection of data types, such as list, tuple, dict, set, str, and so on;
A class is generator, including generators and generator function with yield.
These objects that can directly act on a for loop are called iterative objects: iterable

Generators are iterator objects, but list, dict, and Str are iterable, but not iterator.

You can use Isinstance () to determine whether an object is a iterator object
From collections Import Iterator
Isinstance ((x for X in range), Iterator)
Isinstance ([], Iterator)
Isinstance ({}, Iterator)
Isinstance (' abc ', Iterator)

Change the list, dict, str, etc. iterable to iterator can use the ITER () function
Defines a list and obtains an iterator object for the list via ITER
L = [' Python2 ', ' iter ', ' Python3 ']
it = iter (L) #获得list的迭代器对象
Print (IT)
While True:
x = Next (IT)
Print (x)

Output result Error

This is because next () does not know when to stop
To modify the code:

L = [' Python2 ', ' iter ', ' Python3 ']
it = iter (L) #获得list的迭代器对象

While True:
Try: #try捕获异常
X=next (IT)
Print (x)
Except stopiteration: #当捕获到迭代行为终止的时候, that is, when no element can next, terminate the loop
Break

Normal output result

Why is the list, dict, str and other data types not iterator?
Because the Python iterator object represents a data stream, the iterator object can be called by the next () function and continuously return to the next data until the Stopiteration error is thrown when there is no data. This data stream can be viewed as an ordered sequence, but we cannot know the length of the sequence in advance, but we will only continue to calculate the next data on demand through the next () function, so the calculation of iterator is inert and is only calculated when the next data needs to be returned.
Iterator can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.

Summary
All objects that can be used for a for loop are iterable types;
All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;
Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.
Python's for loop is essentially implemented by constantly invoking the next () function, for example:
# for x in [1, 2, 3, 4, 5]:
Print (x)
Equivalent to
# Get the Iterator object first:
it = iter ([1, 2, 3, 4, 5])
# loop: While True:
Try
# Get the next value:
x = Next (IT)
Except stopiteration:
# exit the loop when you encounter stopiteration
Break

Python Basics-Data types

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.