Python Variables in do not need to be declared . Each variable must be assigned a value before use , The variable will not be created until it is assigned a value .
stay Python in , Variable is variable , It has no type , What we say " type " Is the type of object in memory that the variable refers to .
Equal sign (=) Used to assign values to variables .
Equal sign (=) To the left of the operator is a variable name , Equal sign (=) To the right of the operator is the value stored in the variable .
Python There are six standard data types in :
data type | Definition | variability |
---|---|---|
Number( Numbers ) | int, bool, float, complex,long(python2) | Immutable data |
String( character string ) | Single quotation marks ' Or double quotes " Cover up , Use the backslash at the same time \ Escapes special characters | Immutable data |
List( list ) | In square brackets [] Between 、 Comma separated list of elements | Variable data type |
Tuple( Tuples ) | Write it in parentheses () in , The elements are separated by commas | Immutable data |
Set( aggregate ) | Use braces { } perhaps set() Function to create a collection | Variable data type |
Dictionary( Dictionaries ) | A dictionary is a mapping type , Dictionary use { } identification , It's a disorder key (key) : value (value) Set | Variable data type |
Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary ;
For dictionaries : key (key) Immutable type must be used . In the same dictionary , key (key) Must be unique .
Number( Numbers )
Python The number types of are int integer 、long Long integer (python2)、float Floating point numbers 、complex The plural 、 And Boolean (0 and 1).
You can use the built-in type() Function can be used to query the object type of variable , You can also use isinstance To judge the type :
var_int=123
print(type(var_int))
var_float=1.01
print(type(var_float))
var_bool=True
print(type(var_bool))
var_complex=1+2j
print(type(var_complex))
print(isinstance(var_int, int))
print(isinstance(var_float, float))
The output is as follows :
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
True
True
isinstance and type The difference is that :
type() A subclass is not considered a superclass type .
isinstance() Think of a subclass as a superclass type .
Be careful :
1、 stay Python2 There is no Boolean in , It uses numbers 0 Express False, use 1 Express True. To Python3 in , hold True and False Defined as a keyword , But their value is still 1 and 0, They can be added to numbers .
2、Python Multiple variables can be assigned at the same time , Such as a, b = 1, 2.
3、 A variable can be assigned to different types of objects .
4、 The division of a number consists of two operators :/ Returns a floating point number ,// Returns an integer .
5、 In mixed calculation ,Python Will convert integer to floating point .
String( character string )
Python Use single quotes for strings in ' Or double quotes " Cover up , Use the backslash at the same time \ Escapes special characters . You can also prefix a string with r, It means that string escape is forbidden .
Strings are immutable . All about characters we can start with Indexes 、 section 、 length 、 Traverse 、 Delete 、 Division 、 Clear the blanks 、 toggle case 、 Judge what to start with and so on .
Create string
# String form : Use ‘’ perhaps “” To create a string
var_str1='temp_string1'
print(var_str1)
var_str2="temp_string2"
print(var_str2)
1) Indexes / section
Strings can also be intercepted ( retrieval ). Be similar to C , The first character index of the string is 0 .Python No separate character type ; A character is a simple length of 1 String .
The index can also be negative , This will result in counting from the right . Except index , It also supports slicing . The index is used to get a single character , Slicing lets you get a substring .
as follows , The first line of numbers gives the index point in the string 0…6. The second line gives the corresponding negative index . Slicing is from i To j All characters between two numerical boundaries .
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
The index can also be negative , This will result in counting from the right .
>>> var_str='temp_string'
>>> var_str[1]
'e'
>>> var_str[-1]
'g'
>>> var_str[0:-2] # From the first to the last , It doesn't include the second from the bottom
'temp_stri'
Be careful , Contains the starting character , Does not contain the last character . This makes s[:i] + s[i:] Always equal to s.
Sliced indexes have very useful default values ; The first index omitted defaults to zero , The omitted second index defaults to the size of the sliced string .
>>> var_str='temp_string'
>>> var_str[2:]
'mp_string'
>>> var_str[:2]
'te'
>>>
2) length
Built in functions len() Return string length :
>>> s='thisisatestlongstring'
>>> len(s)
21
3) Delete
>>> s='python'
>>> del(s)
4) toggle case
>>> s='this is a string'
>>> print(s.capitalize())
This is a string
>>> print(s.title())
This Is A String
List( list )
The list is written in square brackets [] Between 、 Comma separated list of elements .
List can complete the data structure implementation of most collection classes . The types of elements in a list can vary , It supports Numbers , Strings can even contain lists ( The so-called nested ).
Just like a string , The list can also be indexed and intercepted , After the list is truncated, a new list containing the required elements is returned .
Each value in the list has a corresponding position value , Call it an index , The first index is 0, The second index is 1, And so on .-1 To start at the end .
>>> list=['abcd', 123, 4.56, "python", 789]
>>> print(list)
['abcd', 123, 4.56, 'python', 789]
>>> print(list[0])
abcd
>>> print(list[1:3])
[123, 4.56]
>>> print(list[2:])
[4.56, 'python', 789]
>>> print(list[:-1])
['abcd', 123, 4.56, 'python']
What's different from a string is , The elements in the list can be changed :
>>> list=['abcd', 123, 4.56, "python", 789]
>>> print(list[2])
4.56
>>> list[2]=100.1 # Update the third element in the list
>>> print(list)
['abcd', 123, 100.1, 'python', 789]
>>> del list[1] # Delete the second element in the list
>>> print(list)
['abcd', 100.1, 'python', 789]
Unlike string truncation , List interception can receive the third parameter , The parameter function is the step size of interception . If the third parameter is negative, it means reverse reading .
The following examples are in the index 1 To the index 8 And set the step size to 2( One place apart ) To intercept words
>>> list=[1,2,3,4,5,6,7,8,9,0]
>>> print(list[1:8:2])
[2, 4, 6, 8]
>>> print(list[-3:-10:-2]) # Reverse interception , From the third to the last element to the tenth from the bottom , The reverse intercept step is 2
[8, 6, 4, 2]
You can also use nested lists, which create other lists in the list :
>>> list=[1, ['a','b'], 2]
>>> print(list[1])
['a', 'b']
>>> print(list[1][1])
b
Tuple( Tuples )
Tuples (tuple) Like a list , The difference is that the elements of a tuple cannot be modified .
Tuples are written in parentheses () in , The elements are separated by commas . The element types in tuples can also be different .
Tuples are similar to strings , Can be indexed and subscript indexed from 0 Start ,-1 For the position starting from the end .
When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators :
>>> tup=(50)
>>> type(tup)
<class 'int'>
>>> tup1=(50,) # An element , Comma needs to be added after element
>>> type(tup1)
<class 'tuple'>
Set( aggregate )
aggregate (set) Is an unordered sequence of non-repeating elements .
You can use braces { } perhaps set() Function to create a collection .
Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary .
Create format :
>>> s={1, 2, 3}
>>> print(s)
{1, 2, 3}
>>> s=set((1, 2, 3))
>>> print(s)
{1, 2, 3}
Dictionary( Dictionaries )
Dictionary is another variable container model , And can store any type of object .
Each key value of the dictionary key=>value Yes, with a colon : Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :
d = {key1 : value1, key2 : value2, key3 : value3 }
A list is an ordered collection of objects , A dictionary is an unordered collection of objects . The difference between the two is : The elements in the dictionary are accessed by keys , Instead of accessing by offset .
key (key) Immutable type must be used .
In the same dictionary , key (key) Must be unique .
>>> dict1={}
>>> dict1['name']='Python'
>>> dict1['age']=18
>>> print(dict1)
{'name': 'Python', 'age': 18}
>>> dict2={'name':'python', 'age':18}
>>> print(dict2)
{'name': 'python', 'age': 18}
>>> print(dict2.keys())
dict_keys(['name', 'age'])
>>> print(dict2.values())
dict_values(['python', 18])
>>> dict3=dict([('name', 'python'), ('age', 1)]) #(key, value) Tuple sequences create dictionaries
>>> print(dict3)
{'name': 'python', 'age': 1}
>>> dict4=dict(name='python', age=18) # Keywords create dictionaries
>>> print(dict4)
{'name': 'python', 'age': 18}
Delete dictionary elements , Can delete a single element can also empty the dictionary :
>>> dict={'name': 'python', 'age': 18}
>>> del dict['age']
>>> print(dict)
{'name': 'python'}
>>> dict.clear()
>>> print(dict)
{}
>>> del dict
Dictionary values can be anything python object , It can be a standard object , It can also be user-defined , But the key doesn't work .
Two important points to remember :
1) The same key is not allowed to appear twice . When creating, if the same key is assigned twice , The latter value will be remembered , The following example :
>>> dict={'name': 'python', 'age': 18, 'name':'lily'}
>>> print(dict)
{'name': 'lily', 'age': 18}
2) The key must be immutable , So you can use numbers , A string or tuple acts as , Not with lists , The following example :
>>> dict={['name']: 'python', 'age': 18}
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
dict={['name']: 'python', 'age': 18}
TypeError: unhashable type: 'list'