8.23
In Python, constants are typically represented in all uppercase variable names.
List:
classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]
can also be used
-1Make an index and get the last element directly:
You can also insert elements into the specified position, such as the index number 1 :
To delete the element at the end of the list, use the pop() method:
To delete an element at a specified location, using the pop(i) method, where the i index is located:
Tuple:
classmates = (‘Michael‘, ‘Bob‘, ‘Tracy‘)
Classmates this tuple cannot be changed, nor does it have a append (), insert () method. Other methods to get elements are the same as list.
A tuple of only 1 elements must be defined with a comma , to disambiguate
Conditional judgment
if age >= 18: print ‘your age is‘, age print ‘adult‘elif age >= 6: print ‘teenager‘
else: print ' Your Age was ', age print ' teenager '
Cycle
Range (5) generates a sequence that is less than 5 of the integer starting from 0:
Dictionary
To avoid a key that does not exist, there are two ways to in determine whether a key exists:
The second is the Get method provided by Dict, if key does not exist, you can return none, or the value you specified:
Note: When none is returned, the interactive command line of Python does not display the results.
To delete a key, the pop(key) corresponding value is also removed from the dict using the method:
Set 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:
>>> s = set([1, 2, 3])>>> sset([1, 2, 3])
Pass
add(key)The method can add elements to the set and can be added repeatedly, but without effect:
remove(key)You can delete an element by means of:
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:
Re-discussion of immutable objects I've made mistakes myself.
For mutable objects, such as list, to manipulate the list, the contents of the list will change, such as:
>>> a = [‘c‘, ‘b‘, ‘a‘]>>> a.sort()>>> a[‘a‘, ‘b‘, ‘c‘]
For non-mutable objects, such as STR, we operate on STR:
>>> a = ‘abc‘>>> a.replace(‘a‘, ‘A‘)‘Abc‘>>> a‘abc‘
Although the string has a replace() method, it does change ‘Abc‘ , but the variable is a still at the end ‘abc‘ , how should it be understood?
Let's start by changing the code to the following:
>>> a = ‘abc‘>>> b = a.replace(‘a‘, ‘A‘)>>> b‘Abc‘>>> a‘abc‘
Always keep in mind that a it is a variable, but a ‘abc‘ string Object! Sometimes, we often say that the object's a content is ‘abc‘ , but actually refers to, a itself is a variable, it points to the content of the object is ‘abc‘ :
See the function section tomorrow.
Python Learning Notes _ an hour a day