Task02: Conditions and circulation

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/NumberOneStudent/article/details/102664128

We are ready to use 17 days time, the Python-based deliberate practice divided into the following tasks:

Task01: variables, operators and the data type (1day)
Task02: cyclic conditions (1day)
Task03: a list of tuples (2Day)
Task04: string sequence (1day)
Task05: Function and Lambda (2Day)
Task06: dictionaries and collections (1day)
Task07: file with the file system (2Day)
Task08: Exception handling (1day)
Task09: the else and with the statement (1day)
Task10: classes and objects (2Day)
Task11: magic method (2Day)
Task12: module ( 1day)

Conditions circulation

Conditional

The reason why a computer can do a lot of automated tasks, because it can make their own judgment conditions.
For example, enter the user's age, print different content based on age, in a Python program, implemented in an if statement:

age = 20
if age >= 18:
    print('your age is', age)
    print('adult')

According to the Python indentation rules, determine if the if statement is True, put the two lines indented print statement is executed, otherwise, do nothing.

You can also add an else statement to if, meaning that if if judgment is False, if the contents do not perform, and go else performed:

age = 3
if age >= 18:
    print('your age is', age)
    print('adult')
else:
    print('your age is', age)
    print('teenager')

Be careful not to write less a colon:.
Of course, the above determination is very rough, you can use to make a more detailed determination elif:

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

elif is an abbreviation else if, and can have multiple elif, so if the full form of the statement is:


if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

if there is a characteristic statement is executed, it is down from the judge, if the judge is on a True, the corresponding statement after the judgment executed, ignore the rest of the elif and else, so please test and explain why the following program is printed teenager:

age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

if the judgment condition can also be abbreviated, such as writing:

if x:
    print('True')

As long as x is a non-zero value, non-empty string, other non-empty list, it is determined True, otherwise to False.
Finally, look at a problem evaluated. Many students will () read with input user input, so you can enter your own program to run more interesting:

Reconsideration input

birth = input('birth: ')
if birth < 2000:
    print('00前')
else:
    print('00后')

Enter 1982, the result of an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

This is because the input () returns the data type str, str direct comparison can not be an integer, it must be converted into integer str. Python provides int () function to do this thing:

s = input('birth: ')
birth = int(s)
if birth < 2000:
    print('00前')
else:
    print('00后')

Run again, you can get correct results. However, if you enter abc it? You will get an error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

When the original error will be int () function finds a string of numbers is not legitimate, the program exits.

How to check and capture the program run of mistakes? Back errors and debugging will be mentioned.
Summary
conditional can let the computer make their own choice, Python's if ... elif ... else very flexible.

Matching condition is determined from the top down, the corresponding block statement is executed when the condition is satisfied, and the subsequent elif else are no longer performed.

cycle

In order for a computer to calculate the repetitive operations thousands of times, we need to loop.

Python loop, there are two, one is for ... in loop, followed by the list or tuple each element iterative out, look at an example:

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

The implementation of this code, in turn print out every element of names:

Michael
Bob
Tracy

So for x in ... cycle each element is assigned to the variable x, and then execute the statement indented block.

Another example we want to calculate the sum of integers from 1 to 10, you can use a variable to do cumulative sum:

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)

To calculate the sum of integers from 1 to 100, from 100 1 writes a bit difficult, but fortunately Python provides a range () function, can generate a sequence of integers, and then through the list () function can be converted into a list. Such as (5) generating a sequence range is from zero integer less than 5 :

>>> list(range(5))
[0, 1, 2, 3, 4]

The second loop is the while loop, as long as the conditions are met, continuous cycle, the loop exits when the condition is not satisfied. For example, we want to calculate the sum of all odd-numbered less than 100, can be achieved using a while loop:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

The cycle continuously variable n is decremented until it becomes -1, is no longer satisfied while condition, loop exits.

break

In a loop, break statement to exit the loop early. For example, the digital print cycle would be 1 to 100:

n = 1
while n <= 100:
    print(n)
    n = n + 1
print('END')

The above codes can be printed out from 1 to 100.

If you want to advance the end of the cycle, you can use the break statement:

n = 1
while n <= 100:
    if n > 10: # 当n = 11时,条件满足,执行break语句
        break # break语句会结束当前循环
    print(n)
    n = n + 1
print('END')

Performing the above code can be seen, the 1 to 10 after printing, followed by printing the END, the program ends.

Visible role is to break ahead of the end of the cycle.

continue

In cycling, you can also continue statement skips the current cycle, the next cycle started directly.

n = 0
while n < 10:
    n = n + 1
    print(n)

The above program can be printed out from 1 to 10. However, if we want to print only odd, you can skip some of the circulating continue statement:

n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0: # 如果n是偶数,执行continue语句
        continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)

Can be seen that the above code is executed, printing is no longer from 1 to 10, but 1,3,5,7,9.

Visible role is to continue ahead of the end of the current round of cycle, and directly start the next cycle.
Summary
cycle is to let the computer do repetitive tasks and effective method.

break statement to exit the loop cycle, and continue statements can be ended early round cycle, and directly start the next cycle. Both statements usually have to cooperate if statements.

Pay special attention to, do not abuse the break and continue statements. break and continue cause code execution logic bifurcation too much, prone to error. Most cycle does not need to use break and continue statements, the above two examples, can be modified by rewriting the cycle conditions or circular logic, remove break and continue statements.

Sometimes, if the code is written there is a problem, let the program into a "death cycle", that is, loop forever. Then you can use Ctrl + C to exit the program, or to force the end of the Python process.

dict

Python built-in dictionary: dict support, dict full name of the dictionary, in other languages ​​also called map, using a key - value (key-value) memory, has a fast search speed.

For example, suppose you want to find the corresponding results of the students by name, if implemented list, requires two list:

names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]

Given a name, to find the corresponding results, you must first find the location corresponding to the names, and then remove the corresponding results from the scores, the longer the list, the longer the time-consuming.

If dict implementation, only a "name" - "accomplishments" of the table, find the results directly from the name, no matter how big the table, the search speed will not slow down. Write a dict in Python as follows:

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

Why dict find so fast? Because of the principle and dict dictionary is the same. Suppose dictionary contains 10,000 Chinese characters, we want a beautiful woman a word, the dictionary is a way to turn back from the first page until you find the word we want, which is to find methods of elements in the list, the larger the list, look slower.

The second method is to look up the word in the dictionary corresponding page number of the index table (such as Radicals), and then directly turn the page to find the word. No matter which word to find, look for this speed is very fast, it will not increase the size of the dictionary and slow.

dict is the second implementation, given a name, such as 'Michael', dict inside can be directly calculated Michael corresponding stored results "page" that is stored in memory 95 the digital address, directly taken out, so very fast.

You can guess, this key-value storage in a bag, it must be calculated according to the key value of the storage location, so take the time to get a value based on the direct key.

The method of data into the dict, in addition to specifying the initialization, but may also be placed through the key:

>>> d['Adam'] = 67
>>> d['Adam']
67

Since only a key corresponding to a value, therefore, for a plurality of times into the value key, the preceding value will later washed away:

>>> d['Jack'] = 90
>>> d['Jack']
90
>>> d['Jack'] = 88
>>> d['Jack']
88

If the key does not exist, dict will error:

>>> d['Thomas']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Thomas'

To avoid key errors that do not exist, there are two ways, one is by key in determining whether there is:

>>> 'Thomas' in d
False

The second is provided by dict get () method, if the key does not exist, you can return None, or specify their own value:

>>> d.get('Thomas')
>>> d.get('Thomas', -1)
-1

Note: None is returned when the Python interactive environment does not display the results.

To delete a key, a pop (key) method, the corresponding value will be deleted from the dict:

>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}

Be sure to note the order of internal storage dict order and put the key is not related.

Compare and list, dict has the following characteristics:

Find and insert the fast, the key will not increase slowed;
take up a lot of memory, memory and more waste.
The opposite list:

Find and insert a time increases the element increases;
small footprint, waste very little memory.
So, dict is a way to use space in exchange for time.

dict can be used in many places to look for high-speed, almost everywhere in Python code, the proper use of dict is very important to keep in mind is the first key dict must be immutable objects.
This is because dict to calculate the value based on key storage location, if different each time the same key computing the results, that the internal dict completely confused. The position calculated by the algorithm is called hash algorithm key (Hash).

To ensure the correctness of the hash as a key target can not be changed. In Python, string, integer, etc. are immutable, and therefore, can be safely used as key. The list is variable, it can not serve as key:

>>> key = [1, 2, 3]
>>> d[key] = 'a list'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

set

Similar dict and set, a set key is set, but not stored value. Since the key can not be repeated, so that, in the set, no duplicate key.

To create a set, you need to provide a list as a set of inputs:

>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}

Note that the incoming parameters [1, 2, 3] is a list, and the display of {1, 2, 3} just tell you that set inside the three elements 1,2,3, the order does not mean that the display set is ordered. .

Repeating elements in the set are automatically filtered:

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

May be added by add (key) set to the element method may be repeated to add, but has no effect:

>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

You can delete elements by remove (key) method:

>>> s.remove(4)
>>> s
{1, 2, 3}

set can be seen as a set of unordered and no duplicate elements in a mathematical sense, therefore, the intersection of two set can be done in a mathematical sense, the union and other operations:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

The only difference is that only dict and set no store corresponding value, however, and the principles set dict the same, so the same can not be put into variable objects, because they can not determine whether the two variable objects are equal, it can not guarantee set internal "no repeat elements." Try the list into the set, and see whether the error.

Again on immutable objects

We talked about above, str is the same object, and the object is a variable list.

For variable objects, such as list, the list with the operation, the contents of the interior of the list will change, for example:

>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']

For immutable objects, such as str, str operate on it:

>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'

Although there is a string replace () method, and indeed become a 'Abc', but a last variable is still the 'abc', how should understand?

We put the code into the following:

>>> a = 'abc'
>>> b = a.replace('a', 'A')
>>> b
'Abc'
>>> a
'abc'

Always keep in mind is, a variable, while the 'abc' is the string object! Sometimes, we often say, a target content is 'abc', but actually refers to, is itself a variable, the content it points to an object is 'abc':
┌───┐ ┌───── ──┐
│ A │─────────────────> │ 'abc' │
└───┘ └───────┘
when we call a.replace ( 'a', when the 'a'), in fact, replace the calling method is applied to the string object 'abc', and this method, although name replace, but did not change the contents of the string 'abc' of. Instead, replace method creates a new string 'Abc' and return, if we use the new string variable to point b, it is easy to understand, still pointing to the original variable a string 'abc', but they point to the variable b new string 'Abc' a:

┌───────┐ ┌───┐
│ A │─────────────────> │ 'ABC' │
└───┘ └──── ───┘
┌───┐ ┌───────┐
│ │───────────────── B> │ 'Abc' │
└───┘ └ ───────┘
so, for the same objects, the object itself call any method does not change the contents of the object itself. Instead, these methods will create a new object and returns, so that guarantees that immutable object itself will always be immutable.

summary

Using the key-value store configuration dict useful Python, immutable objects selected as the key is very important, is the most commonly used key string.
Although tuple is immutable objects, but try to put (1, 2, 3) and (1, [2, 3]) was placed in a dict or set, and interpret the results.
set ([1, 2, 3 ]) of the
set (1, [2, 3 ]) Error
explain why the first may be the second not:

You can be s = set ([1, 2, 3]) of [2,3] be understood as requiring its set of this type of data included in a formal, as set here is not a list key, but the elements of the list as a key set of.

In other words, whether you are ready to put anything into the set, it will be a first list (or tuple) in the form , and even the empty set, they have to be [].

A second look, s = set ((1, [2,3])) , the first assignment
list1 = [2,3]
is, at this time is converted into the s

s = set((1, list1))

See here you get it? This is a wish to tuple = (1, list1) s was charged to this set. The tuple has two elements, a is 1, is a list1, because list1 variable (not the hash), this set can not be stored in the s, the error will be.

The third right:
S1 = { 'S': [. 1, [2,. 3]]}

Guess you like

Origin blog.csdn.net/NumberOneStudent/article/details/102664128