Chapter 1 of python Learning (simple examples and common data types) and python Data Types
AIYQ195 learn python
Chapter 1 simple examples and common data types 1. hello programs required for getting started with programs
The program code of the IDE3.4 software is as follows:
Print ("hello aiyq195 ")
The execution result is as follows:
Python 3.4.4 (v3.4.4: 737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license ()" for more information.
Python 3.4.4 (v3.4.4: 737efcadf5a6, August 1, December 20, 2015, 20:20:57) (MSC v. In win32 1600 64-bit (AMD64)], enter "Copyright", "credit", or "License ()" for more information.
>>> Print ("hello aiyq195 ")
Hello aiyq195
The above is a simple sentence to show the content you want to print;
Unlike the C language, it does not need to define header files or primary functions. print ("echo data") is a simple sentence "); in addition, the sentence does not need to be separated by semicolons;
OK;
1.1 output function print ()
In python 3, you can leave () behind print (). Keep up with the content you want to output, but in python, you need to keep up with (). However, in python 2, your input () is correct, so, the best thing is to keep up with () directly ()
Example:
Python 3.4:
>>> Print ("hello aiyq195 ")
Hello aiyq195
>>> Print "hello aiyq195"
SyntaxError: Missing parentheses in call to 'print'
Python 2.7:
Aiyq195 @ aiyq195-virtual-machine :~ $ Python
Python 2.7.3 (default, Sep 26 2012, 21:53:58)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> Print "hello world"
Hello world
>>> Print ("hello world ")
Hello world
You can see from the above content that it is better to use print () directly to avoid version problems when using the print function;
1.2 input function input ()
The input () function allows you to input the data you want:
>>> Name = input ("what is your name? \ N ")
What is your name?
Aiyq195
>>> Name
'Aiyq195'
>>> Cr = input ("enter a number! \ N ")
Enter a number!
7
>>> Cr
'7'
There is also some content, that is, there is an input function raw_input () in the python 2 version. For the difference, see the following content:
Http://www.cnblogs.com/aiyq195/p/6511139.html
However, if you use the two functions above, you need to consider which version to execute!
2. Common Types
Python has many types, including:
A) character
B) String
C) Boolean Type
D) Integer
E) Number
F) floating point number
G) List
H) tuples
I) Dictionary
In python, this statement is not declared. It is directly defined and assigned to what type he is;
The following describes several types:
2.1 characters and strings
How to define strings in python
2.1.1 use single quotes (')
A single quotation mark can only represent some simple strings. If it contains some special symbols, an error occurs, such:
>>> Str = 'nihao aiyq195'
>>> Str
'Nihao aiyq195'
>>> Str = 'let's go'
SyntaxError: invalid syntax
2.1.2 use double quotation marks (")
>>> Str = "let's go"
>>> Str
"Let's go"
2.1.3 use multiple quotation marks (""")
Multiple quotation marks can be used to indicate strings of multiple rows. That is to say, if you want to display data of multiple rows at the same time, you need to mark the strings with multiple quotation marks, for example:
>>> Str = "" nihao aiyq195,
What is you ages! "
"""
>>> Str
'Nihao aiyq195, \ nwhat is you ages! "\ N'
Where \ n is the line break!
2.2 Boolean Type
Boolean: contains only two values: True and False;
Note that the above two words must be correctly spelled; otherwise, they are also wrong;
Example:
>>> Bool = 1
>>> Bool
1
Note: If you do not define a variable named bool, you are a Boolean value;
>>> Bool = false
Traceback (most recent call last ):
File "<pyshell #45>", line 1, in <module>
Bool = false
NameError: name 'false' is not defined
>>> Bool = False
>>> Bool
False
>>> Bool = true
Traceback (most recent call last ):
File "<pyshell #48>", line 1, in <module>
Bool = true
NameError: name 'true' is not defined
>>> Bool = True
>>> Bool
True
Note: This type of value can be used only when the correct spelling is False;
2.3 integer, floating point, number
Integer
>>> Int = 20
>>> Print (int)
20
Floating Point Number
>>> Float = 1.2
>>> Print (float)
1.2
Number:
It is actually the synthesis above, that is, integers and floating-point numbers.
The content involving numbers is a bit more:
2.3.1 digital type conversion
Int (x) converts x to an integer.
Float (x) converts x to a floating point number.
Complex (real [, imag]) creates a plural number
Str (x) converts object x to a string
Repr (x) converts object x to an expression string
Eval (str) is used to calculate a valid Python expression in a string and return an object.
Tuple (s) converts the sequence s into a tuples
List (s) converts sequence s into a list
Chr (x) converts an integer to a character
Unichr (x) converts an integer to a Unicode Character
Ord (x) converts a character into its integer
Hex (x) converts an integer into a hexadecimal string.
Oct (x) converts an integer into an octal string
2.3.2 numeric Functions
Abs (x) returns the absolute value of a number, for example, abs (-10) returns 10
Ceil (x) returns the upper integer of the number, for example, math. ceil (4.1) returns 5
Cmp (x, y) returns-1 if x <y, 0 if x = y, and 1 if x> y
Exp (x) returns the x power of e (ex). For example, math. exp (1) returns 2.718281828459045
Fabs (x) returns the absolute value of a number, for example, math. fabs (-10) returns 10.0
Floor (x) returns the rounded down integer. For example, math. floor (4.9) returns 4.
Log (x) such as math. log (math. e) returns 1.0, math. log (2.0) returns
Log10 (x) returns the logarithm of x based on 10. For example, math. log10 (100) returns 2.0.
Max (x1, x2,...) returns the maximum value of a given parameter, which can be a sequence.
Min (x1, x2,...) returns the minimum value of a given parameter, which can be a sequence.
Modf (x) returns the integer and decimal parts of x. The numerical symbols of the two parts are the same as those of x, and the integer part is expressed as a floating point.
The value after the pow (x, y) x ** y operation.
Round (x [, n]) returns the rounding value of floating point x. If n is given, it indicates the number of digits rounded to the decimal point.
Sqrt (x) returns the square root of the number x. The number can be a negative number and the return type is a real number. For example, math. sqrt (4) returns 2 + 0j
2.4 list
A list is the data that can be like a chain. It is a continuous data link;
2.4.1 initialization list
List = ['pyu', 'aiyq', 'wgj', 'yb ', 2342,3432]
Nums = [,]
2.4.2 Element
A list is generally a set that contains multiple data. Therefore, each data unit contained in a list is called an element.
Just as we put the names of a class in descending order into a roster;
The roster is a list, and each name in the class is the list element;
As follows:
>>> Classlist = ['hangsan', 'lisi', 'hangzhou', 'shanghai', 'qianqi']
In 'hangsan', 'hangsan' represents an element;
2.4.2 Index
Because the list is ordered, the index keyword is available;
An index is a point from 0;
We also take the class example. We sort it in the descending order;
In the first place, we calculated his code as 0, followed by 1 until n,
In this way, we know that the number of employees in the class is (n + 1 );
In this way, we can use this number to represent an element in our list;
Then, classlist [0] can represent an element, 'hangsan'
>>> Classlist = ['hangsan', 'lisi', 'hangzhou', 'shanghai', 'qianqi']
>>> Classlist [0]
'Hangsan'
2.4.3 update list elements
>>> Classlist [0] = 'aiyq195'
>>> Classlist [0]
'Aiyq195'
2.4.4 delete a list element
>>> Classlist
['Aiyq195 ', 'lisi', 'wangwu', 'zhaoliu', 'qianqi ']
>>> Del classlist [0]
>>> Classlist
['Lisi', 'wangw', 'zhaoliu', 'qianqi ']
The del command can delete the list elements. In this case, the elements in the original position of the list that you delete will place the index first, that is, at this time, the original n [1] is changed to n [0].
>>> Classlist [0]
'Lisi'
2.4.5 operations on the entire list
For list operations, we will briefly introduce the + and * operators;
The + operator Concatenates the data in the two lists;
Example:
>>> Nums = [1, 2, 3, 4, 5, 6, 7]
>>> Classlist
['Lisi', 'wangw', 'zhaoliu', 'qianqi ']
>>> Nums + classlist
[1, 2, 3, 4, 5, 6, 7, 'lisi', 'wangwu', 'zhaoliu ', 'qianqi']
>>> Classlist + nums
['Lisi', 'wangw', 'zhaoliu ', 'qianqi', 1, 2, 3, 4, 5, 6, 7]
>>> Nr = nums + classlist
>>> Nr
[1, 2, 3, 4, 5, 6, 7, 'lisi', 'wangwu', 'zhaoliu ', 'qianqi']
The above data shows that the + numbers can be directly used for the two lists to form a new list in order. In addition, the data in the list will not be re-ordered because of the creation;
The * operator is equivalent to a multiplication number. It doubles the number of elements in your list in the original order,
It will not be associated with any element, it will only change the number of your elements,
Just like nums in your list, it has seven elements. When we use the * operator, the number of its elements will become 21;
>>> Len (nums)
7
>>> Len (nums * 3)
21
>>> Nums * 3
[1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]
>>> Nr * 2
[1, 2, 3, 4, 5, 6, 7, 'lisi', 'wangwu', 'zhaoliu ', 'qianqi', 1, 2, 3, 4, 5, 6, 7, 'lisi', 'wangwu', 'zhaoliu', 'qianqi ']
>>> Nums * r
Traceback (most recent call last ):
File "<pyshell #78>", line 1, in <module>
Nums * r
NameError: name 'R' is not defined
Note that this * operator can only follow numbers, not characters;
2.4.6 check whether the data exists in the list
The In keyword allows us to determine whether an element In a list includes the data we want;
For example:
>>> Lisi in classlist
Traceback (most recent call last ):
File "<pyshell #82>", line 1, in <module>
Li in classlist
NameError: name 'lil' is not defined
>>> 'Lisi' in classlist
True
>>> Classlist
['Lisi', 'wangw', 'zhaoliu', 'qianqi ']
>>> 'Aiyq195 'in classlist
False
At this time, a Boolean value is returned. If yes, True is returned; otherwise, False is returned;
In addition, you can check whether the data you entered is the same as the list element to make the query successful;
2.4.7 list Truncation
Part of the data in the list is extracted;
>>> Nums
[1, 2, 3, 4, 5, 6, 7]
>>> Nums [2]
3
>>> Nums [2: 4]
[3, 4]
>>> Nums [2: 6]
[3, 4, 5, 6]
>>> Nums [-1]
7
>>> Nums [-1:-4]
[]
>>> Nums [-1: 4]
[]
>>> Nums [-2]
6
>>> Nums [-4:-1]
[4, 5, 6]
The content above illustrates some of the content, the screenshot of the list. What is needed is that you can intercept the content in the list according to the index;
That is, if you want to intercept these element ranges, you can connect the starting index value to the ending index value and use the ":" sign to get the expected range list element values.
2.4.8 list common functions and methods
List. append (obj) Add a new object at the end of the list
List. count (obj) counts the number of times an element appears in the list.
List. extend (seq) append multiple values in another sequence at a time at the end of the list (extend the original list with the new list)
List. index (obj): locate the index location of the first matching item of a value from the list. The index starts from 0.
List. insert (index, obj) inserts an object into the list.
>>> Nums. insert (0, 9)
>>> Nums
[9, 1, 2, 3, 4, 5, 6, 7]
>>> Nums. insert (0, 8)
>>> Nums
[8, 9, 1, 2, 3, 4, 5, 6, 7]
List. pop (obj = list [-1]) removes an element from the list (the last element by default) and returns the value of this element.
List. remove (obj) removes the first matching item of a value in the list.
List. reverse () reverse list element, reverse
List. sort ([func]) sorts the original list
2.5 tuple)
The Python tuples are similar to the list. The difference is that the elements of the tuples cannot be modified. The tuples use parentheses () and the list uses square brackets []. It is very easy to create tuples, you only need to add elements in parentheses and separate them with commas (,). For example:
Tup1 = ('physics ', 'chemistry', 1997,200 0)
Tup2 = (1, 2, 3, 4, 5)
Tup3 = "a", "B", "c", "d"
Create null tuples, for example, tup = ();
When there is only one element in the tuples, you need to add a comma after the element, for example, tup1 = (50 ,);
Tuples are similar to strings. subscript indexes start from 0 and can be truncated or combined.
2.5.1 Access tuples
Like the list, the ancestor is composed of various elements. You need to view the element. We also use the index of the tuples to view it;
View a single element
>>> Tup2 = (1, 2, 3, 4, 5)
>>> Tup2 [2]
3
View the elements of the tuples
>>> Tup2 [0: 4]
(1, 2, 3, 4)
2.5.2 modify tuples
Element values in tuples cannot be modified, but we can concatenate and combine them. For example:
>>> Tup1 = (12, 32, 43)
>>> Tup2 = ('abc', 'efg ')
> Tup1 [0] = 100
Traceback (mostrecent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> Tup3 = tup1 + tup2
>>> Tup3
(12, 32, 43, 'abc', 'efg ')
2.5.3 Delete tuples
The element values in the tuples cannot be deleted. You can use the del statement to delete the entire tuples. For example:
>>> Deltup3 [3]
Traceback (mostrecent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn' t support item deletion
>>> Deltup3
>>> Tup3
Traceback (mostrecent call last ):
File "<stdin>", line 1, in <module>
NameError: name 'tup3' is not defined
2.5.4 tuples Operator
Like the list operator, the tuples operator also has the plus sign (+) and the plus sign (*). It also has the keyword "in" to determine whether the element exists in the tuples;
>>> Tup1 = (1, 2, 3)
>>> Tup2 = (3, 4, 5)
>>> Tup1 + tup2
(1, 2, 3, 3, 4, 5)
>>> Tup1 * r
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
NameError: name 'R' is not defined
>>> Tup1 * 2
(1, 2, 3, 1, 2, 3)
>>> 2 in tup1
True
>>> 2 in tup2
False
2.5.5 tuples associated functions
Cmp (tuple1, tuple2) compares two tuples.
Len (tuple) calculates the number of tuples.
Max (tuple) returns the maximum value of elements in the tuples.
Min (tuple) returns the minimum element value in the tuples.
>>> Min (list)
1
Tuple (seq) converts the list into tuples.
>>> List = [1, 2, 3]
>>> Tuple (list)
(1, 2, 3)
2.6 introduction to the dictionary 2.6.1
A dictionary is the most flexible built-in data structure type in python except the list. A list is a combination of ordered objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, rather than by offset.
A dictionary consists of keys and values. A dictionary is also called an associated array or a hash table. The basic syntax is as follows:
Dict = {'Alice ': '000000', 'beth': '000000', 'cecil ': '000000 '};
You can also create a dictionary as follows:
Dict1 = {'abc': 456 };
Dict2 = {'abc': 123, 98.6: 37 };
Each key and value must be separated by a colon (:). Each pair is separated by a comma and placed in curly brackets ({}). The key must be unique, but the value does not have to; the value can take any data type, but must be immutable, such as a string, number, or tuples.
2.6.2 access dictionary
>>> Dict = {'aiyq195 ': 195, 'wangguojun', 176, 'ubin', 179}
File "<stdin>", line 1
Dict = {'aiyq195 ': 195, 'wangguojun', 176, 'ubin', 179}
^
SyntaxError: invalid syntax
>>> Dict = {'aiyq195 ': 195, 'wangguojun': 179, 'ubin': 180}
>>> Dict [0]
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> Dict
{'Aiyq195 ': 195, 'wangguojun': 179, 'ubin': 180}
>>> Dict ['aiyq195']
195
>>> Dict [195]
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
KeyError: 195.
As we can see from the above, there is no index in the dictionary viewing method, so you cannot view Elements Using indexes like lists and tuples,
In addition, he can only use keys to view the elements in the dictionary;
2.6.3 modify a dictionary
>>> Dict
{'Aiyq195 ': 195, 'wangguojun': 179, 'ubin': 180}
>>> Dict ['aiyq195 '] = 200
>>> Dict
{'Aiyq195 ': 200, 'wangguojun': 179, 'ubin': 180}
>>> Dict ['caidongxu'] = 180
>>> Dict
{'Aiyq195 ': 200, 'wangguojun': 179, 'ubin': 180, 'caidongxu': 180}
Through the example above, you can see how to modify the elements in the dictionary, or if the key you modified does not exist, it will directly add this element;
2.6.4 delete a dictionary
>>> Del dict ['caidongxu']
>>> Dict
{'Aiyq195 ': 200, 'wangguojun': 179, 'ubin': 180}
>>> Dict. clear
<Built-in method clear of dict object at 0xb691968c>
>>> Dict
{'Aiyq195 ': 200, 'wangguojun': 179, 'ubin': 180}
>>> Dict. clear ()
>>> Dict
{}
>>> Del dict
>>> Dict
<Type 'dict '>
You can see through the above:
Del dict ['name']; # delete an entry whose key is 'name'
Dict. clear (); # clear all dictionary entries
Del dict; # delete a dictionary
2.6.5 dictionary Functions
Cmp (dict1, dict2) compares two dictionary elements.
Len (dict) calculates the number of dictionary elements, that is, the total number of keys.
Str (dict) outputs the printable string representation of the dictionary.
>>> Str (dict)
"{'Aiyq195 ': 200, 'wangguojun': 179, 'ubin': 180 }"
Type (variable) returns the input variable type. If the variable is a dictionary, the dictionary type is returned.
>>> Type (dict)
<Type 'dict '>
Radiansdict. clear () deletes all elements in the dictionary.
Radiansdict. copy () returns the shortest copy of a dictionary.
Radiansdict. fromkeys () creates a new dictionary, which uses the elements in sequence seq as the dictionary key. val is the initial value corresponding to all the keys in the dictionary.
Radiansdict. get (key, default = None) returns the value of the specified key. If the value is not in the dictionary, the default value is returned.
Radiansdict. has_key (key) if the key returns true in the dictionary dict, otherwise false is returned.
Radiansdict. items () returns a list of (Key, value) tuples that can be traversed.
Radiansdict. keys () returns a list Of all keys in the dictionary.
Radiansdict. setdefault (key, default = None) is similar to get (). However, if the key does not exist in the dictionary, a key is added and the value is set to default.
Radiansdict. update (dict2) updates the key/value pairs of the dictionary dict2 to dict.
Radiansdict. values () returns all values in the dictionary in a list.
>>> Dict. items ()
[('Aiyq195', 200), ('wangguojun', 179), ('yubin', 180)]
>>> Dict. has_key ('aiyq195 ')
True
>>> Dict. keys ()
['Aiyq195', 'wangguojun', 'ubin']