Python BASICS (3) and python Basics
4. if statement
The If statement can check and determine the current condition and take corresponding measures.
1 if a in A: 2 if a condition: 3 Execute Command 14 else: 5 Execute Command 26 7 if judgment condition can also be abbreviated as 8 if x: 9 print ('true ')
If x is a non-zero value, a non-empty string, or a non-empty list, True is returned. Otherwise, False is returned.
4.1 conditional test (condition judgment)
1. The core of each if statement is to determine whether the condition is True or False. This expression is calledConditional Test.
2. python determines whether to execute the following code based on the value True or False in the condition test. if the if statement is True, the following code is executed. if it is False, the following code is ignored.
3. In python, everything that is not 0, Null, or empty objects is True.
4.2 check for Equality
1. Compare Python values to different valuesCase sensitivity.
2 .! = Not equal, exclamation pointNo,Can compare numbers and characters.
4.2.1 check multiple conditions
1. Use keywordsAndIf none of the connections are True, the values are False. To improve readability, you can write each test in.
2. Use keywordsOrIf one connection is satisfied, it is True. If none is satisfied, it is False.
4.2.2 check whether a specific value is included in the list
1. Use keywordsInTo determine the inclusion relationship.
2. Use keywordsNot inTo determine the non-inclusion relationship.
4.2.3 Boolean expression
1. the Boolean expression is the alias of the conditional test, and the results are both True or False. The Boolean value is exactly the same as that of the Boolean algebra. A boolean value can only be True or False, either True or False. in Python, you can use True or False to represent a Boolean value (Note the case sensitivity)
Boolean values can be calculated using and, or, and not. Boolean operator.
|
1. True and True
True
2. True or False
True
3. not True
False |
4.3if statement
1. Simple if statement, a test, an operation, note indentation, and colon.
2. if-else statement: one condition test and two operations.
3. if-elif-else structure multi-condition test. elif is short for else if and can have multiple elif.
|
If <condition judgment 1>:
<Execution 1>
Elif <condition Judgment 2>:
<Execution 2>
Elif <condition judgment 3>:
<Execution 3>
Else:
<Execution 4> |
4. if statement execution has the following characteristics: it determines from top down. if it is True in a certain judgment, the remaining elif and else will be ignored after the corresponding statement is executed.
5. else can be omitted and replaced with elif to avoid introducing more error messages.
6. Add a space on both sides of the comparison operator, such as syntax format =, >=and <=. For example, if age <4: Is Better Than if age <4.
5. Dictionary
Python has built-in dictionaries: dict support. dict stands for dictionary and is also called map in other languages. It is stored with key-value (key-value) and has extremely fast search speed.
Features:Unordered, the dictionary is dynamic data. The dictionary consists of {}, separated by semicolons. The dictionary contains keys and values, which correspond to each other. Values associated with keys can be numbers, strings, lists, and even dictionaries. Any Python object can be used as values in the dictionary. Correct use of dict is very important. The first thing to remember isDictKeyIt must be an unchangeable object.
Set:
1.1. Similar to dict, set is also a set of keys,But not storedValue.Because keys cannot be repeated, there are no duplicate keys in the set.
1.2. set can be regarded as a set of unordered and non-repeating elements in the mathematical sense. Therefore, two sets can be used for intersection and Union operations in the mathematical sense: & intersection; | Union set;
1.3. the only difference between set and dict is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, it cannot be placed into a variable object, because it is impossible to determine whether two mutable objects are equal, it is impossible to ensure that "there will be no repeated elements" in the set ". Put list in set to see if an error is reported.
1.4. The add (key) method can be used to add elements to the set. You can add them again, but it will not work.
1.5. You can use the remove (key) method to delete elements.
Comparison between list and dict
Compared with list, dict has the following features:
The search and insertion speed is extremely fast and will not slow down as the key increases;
A large amount of memory is required, resulting in a high waste of memory.
Contrary to list:
The time for searching and inserting increases with the increase of elements;
It occupies a small amount of space and wastes a small amount of memory.
Therefore, dictIt is a way to exchange space for time.
5.1 access dictionary value 1. Key-value access
Key Value access:
|
Alien_0 = {'color': 'green', 'points': 5} |
There are two methods to avoid the key nonexistent error: one is to use in to determine whether the key exists:
2. get Method
2. Provided through dictGetMethodIf the key does not exist, you can return None or the specified value:
|
D. get ('Thomas ')
D. get ('Thomas ',-1) # If 'Thomas' does not exist in d,-1 is returned.
-1
>>> PicnicItems = {'apples ': 5, 'cups': 2}
>>> 'I am bringing' + str (picnicItems. get ('cups ', 0) + 'cups .'
'I am bringing 2 cups .'
>>> 'I am bringing' + str (picnicItems. get ('eggs ', 0) + 'eggs .'
'I am bringing 0 eggs. |
Note: When None is returned, the interactive command line of Python does not display the result.
3. setdefault () method
The setdefault () method provides a way to complete this task in one row. The first parameter passed to this method is the key to be checked. The second parameter is the value to be set if the key does not exist. If the key exists, the method returns the value of the key.
|
>>> Spam = {'name': 'oka', 'age': 5}
>>> Spam. setdefault ('color', 'black') # The key does not exist. 'black' is returned'
'Black' |
4. pprint Module
Import the pprint module, you can use the pprint () and pformat () functions, they will be "beautiful print" a dictionary word.
|
Pprint. pprint (someDictionaryValue)
Print (pprint. pformat (someDictionaryValue )) |
5.2 add keys and values
A dictionary is a dynamic data. You can add keys and values to it at any time and add data through keys.
|
Alien_0 = {'color': 'green', 'points': 5}
Alien_0 ['x _ position'] = 0
Alien_0 ['y _ position'] = 25
Print (alien_0) |
5.3 Delete keys and values
1. to delete a key, use the pop (key) method and the corresponding value will also be deleted from dict:
2. Use del
Del alien_0 ['points']
5.4 traverse the dictionary item ()
The Python Dictionary (Dictionary) items () function returns an array of (Key, value) tuples that can be traversed in a list.
For key, value in user_0.items ():
Actual
For name, language in favorite_languages.items ():
Simple variable name:
For k, v in user_0.items ()
Note that the return order of key-value pairs is different from the storage order even when the dictionary is traversed. Python does not care about the storage sequence of key-value pairs, but only tracks the associations between keys and values.
Determine whether an object is an iteratable object by using the Iterable type of the collections module;
|
>>> From collections import Iterable
>>> Isinstance ('abc', Iterable) # Can str be iterated? |
Python's built-in enumerate function can convert a list into an index-element pair, so that the index and element itself can be iterated simultaneously in the for loop.
Use the built-in isinstance function to determine whether a variable is a string.
5.4.1 traverse all keys in the dictionary (for loop)
Python has two types of loops. One is for... in loop, which iterates each element in list or tuple in sequence. for example:
|
For name in favorite_policages.keys (): |
When the dictionary is traversed, all keys are traversed by default. Therefore, if you replace for name in favorite_languages.keys () in the above Code with for name in favorite_ages:, the output will remain unchanged. If you explicitly use method keys () to make the code easier to understand, you can choose to do so, but if you want to, you can also omit it.
5.4.2 traverse all keys in the dictionary in order
Sorted()
Use the sorted () function to obtain a copy of the key list in a specific order.
Sort by initials
One way is to sort the keys returned in the for loop. Therefore, you can use the sorted () function to obtain a copy of the key list in a specific order.
5.4.3 traverse all values in the dictionary
Values ()
UsageValues ()It returns a list of values without any keys.
For language in favorite_languages.values ():
To remove duplicate items, you can use a set combination.Set (). A set is similar to a list, but each element must be unique:
For language in set (favorite_languages.values ()):
5.5 nesting
You can also use a two-tier loop to generate a full arrangement.
5.5.1 dictionary list
Alien_0 = {'color': 'green', 'points': 5}
Alien_1 = {'color': 'yellow', 'points': 10}
Alien_2 = {'color': 'red', 'points': 15}
Aliens = [alien_0, alien_1, alien_2]
5.5.2 store the dictionary
Nested dictionary in the dictionary
5.6 exit loop (break)
In a loop, the break statement can exit the loop in advance. This statement must be used together with the if statement.
5.7 continue
In the loop process, you can also use the continue statement to skip the current loop and start the next loop directly. This statement must be used together with the if statement.