One Python dry goods a day: "Automation Basics": Conditional judgment statements

Conditional judgment

The reason why a computer can do many automated tasks is that it can make conditional judgments by itself. P

For example, enter the user’s age and print different content according to the age. In the Python program, use the if statement to achieve:

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

According to Python's indentation rules, if the if statement judges to be True, the two indented print statements are executed, otherwise, nothing is done.

You can also add an else statement to the if, which means that if the if judgment is False, do not execute the content of the if and execute the else:

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

Be careful not to omit the colon:.

Of course, the above judgment is very rough, you can use elif to make a more detailed judgment:

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

elif是else if的缩写,完全可以有多个elif,所以if语句的完整形式就是:

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

The execution of if statement has a characteristic, it is judged from top to bottom. If a certain judgment is True, after executing the statement corresponding to the judgment, the remaining elif and else are ignored, so please test and explain why The following program prints

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

The if 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, non-empty list, etc., it is judged as True, otherwise it is False.

input

Finally, look at a problematic conditional judgment. Many students will use input() to read the user's input, so that they can input by themselves, and the program will run more interestingly:

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

Enter 1982, the result is an error:

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

This is because the data type returned by input() is str. Str cannot be directly compared with an integer. You must first convert str into an integer. Python provides the int() function to accomplish this:

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

Run it again to get the correct result. But what if you type abc? You will get another error message:

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

It turns out that the int() function will report an error when it finds that a string is not a valid number, and the program will exit.

Recommendation: 020 is continuously updated, the small circle of boutiques has new content every day, and the concentration of dry goods is extremely high.
There are everything you want to make connections and discuss technology!
Be the first to join the group and outperform your peers! (There is no fee for joining the group)
Click here to communicate and learn with Python developers.
Group number: 745895701
application and delivery :
Python software installation package, Python actual combat tutorial,
free collection of materials, including Python basic learning, advanced learning, crawling, artificial intelligence, automated operation and maintenance, automated testing, etc.

cycle

To calculate 1+2+3, we can directly write the expression:

>>> 1 + 2 + 36

To calculate 1+2+3+…+10, I can barely write it out.

However, to calculate 1+2+3+…+10000, it is impossible to write the expression directly.

In order for the computer to calculate thousands of repeated operations, we need loop statements.

for...in loop

There are two types of Python loops. One is a for...in loop, which iterates over each element in a list or tuple in turn. See an example:

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

Executing this code will print each element of names in turn:

MichaelBobTracy

So the for x in… loop is to substitute each element into the variable x, and then execute the statement of the indented block for output each time. For example, if we want to calculate the sum of integers from 1 to 10, we can use a sum variable for accumulation:

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

If you want to calculate the sum of integers from 1 to 100, it is a bit difficult to write from 1 to 100.

Python provides a range() function, which can generate a sequence of integers, which can be converted to a list through the list() function. For example, the sequence generated by range(5) is an integer less than 5 starting from 0:

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

range(101) can generate a sequence of integers from 0-100, which is calculated as follows:

The first:

enter:

Output:

The second type: input:

output:

Pay attention to the indentation, it will output different results: enter:

Output:

while loop

The second type of loop is the while loop. As long as the condition is met, it will continue to loop. If the condition is not met, it will exit the loop and output the result of the last loop.

For example, if we want to calculate the sum of all odd numbers within 100, we can use a while loop:

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

In the loop, the variable n continues to decrement until it becomes -1, the while condition is no longer satisfied, and the loop exits.

enter:

Output:

break

In the loop, the break statement can exit the loop early and the program ends, but it must be used in conjunction with the if statement. For example, after printing out 1~10, immediately printing END, the program ends.

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

print(n) n = n + 1print('END')

continue

In the loop process, you can also use the continue statement to skip the current loop and start the next loop directly, but it must be used in conjunction with the if statement.

If we want to print only odd numbers between 1-10, we can skip some loops with the continue statement:

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

Executing the above code, you can see that the prints are no longer 1-10, but 1, 3, 5, 7, 9.

Pay special attention: Do not abuse break and continue statements.

dict,{}

Python has a built-in dictionary: dict is supported. The full name of dict is dictionary, which is also called map in other languages. It uses key-value storage and has extremely fast search speed.

For example, suppose you want to find the corresponding score according to the name of the classmate. If you use dict to achieve it, you only need a "name"-"score" comparison table, and you can find the score directly based on the name. No matter how big the table is, the search speed is not Will slow down. Write a dict in Python as follows:

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

In this key-value storage method, when you put it in, you must calculate the storage location of the value based on the key, so that you can get the value directly based on the key when you get it.

The method of putting data into the dict, in addition to the designation during initialization, can also be put into the key:

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

Since a key can only correspond to one value, if you put a key into value multiple times, the following value will erase the previous value:

>>> d['Jack'] = 90>>> d['Jack']90>>> d['Jack'] = 88
>>> d['Jack']88
>>> d
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85,'Adam':67,'Jack':88}

If the key does not exist, dict will report an error:

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

To avoid the error that the key does not exist, there are two ways. One is to judge whether the key exists by in:

>>> 'Thomas' in dFalse

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

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

Note: The interactive environment of Python does not display the result when None is returned.

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

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

It is important to note that the internal storage order of the dict has nothing to do with the order in which the keys are placed.

Compared with list, dict has the following characteristics:

The search and insertion speed is extremely fast, and will not slow down with the increase of the key; it takes up a lot of memory and wastes a lot of memory.

The opposite of list:

The time for searching and inserting increases with the increase of elements; it takes up little space and wastes little memory.

Therefore, dict is a way to exchange space for time.

dict can be used in many places where high-speed search is required. It is almost everywhere in Python code. The correct use of dict is very important. The first thing to keep in mind is that the key of dict must be an immutable object.

This is because dict calculates the storage location of value according to the key. If the result of calculating the same key each time is different, the dict is completely confused. This algorithm for calculating the location by key is called a hash algorithm (Hash).

To ensure the correctness of the hash, the key object cannot be changed.

In Python, strings, integers, etc. are immutable, so they can be safely used as keys. The list is variable and cannot be used as a key:

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

set

Set is similar to dict. It is also a set of keys, but does not store value. Since the key cannot be repeated, there is no duplicate key in the set.

To create a set, you need to provide a list as the input set:

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

Note that the incoming parameter [1, 2, 3] is a list, and the displayed {1, 2, 3} just tells you that there are three elements of 1, 2, and 3 inside the set, and the display order does not indicate The set is ordered.

Repeated elements are automatically filtered in the set:

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

You can add elements to the set through the add(key) method, and you can add them repeatedly, but it will not have any effect:

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

Elements can be deleted through the remove(key) method:

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

Set can be regarded as a set of disordered and non-repetitive elements in the mathematical sense. Therefore, two sets can perform operations such as intersection and union in the mathematical sense:

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

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, variable objects cannot be placed in the same way. Because it is impossible to judge whether two variable objects are equal, the set cannot be guaranteed. "There will be no duplicate elements" inside. Try to put the list in the set and see if it will report an error.

Talk about immutable objects again

As we mentioned above, str is an immutable object, and list is a mutable object.

For mutable objects, such as list, if you operate on the list, the contents of the list will change, such as:

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

And for immutable objects, such as str, do operations 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 a is still'abc' at the end, how should we understand it?

Let's first change the code to the following:

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

Always keep in mind that a is a variable and'abc' is a string object! Sometimes, we often say that the content of object a is'abc', but in fact it means that a itself is a variable, and the content of the object it points to is'abc':

┌───┐ ┌───────┐│ a │─────────────────>│ 'abc' │└───┘ └───────┘

When we call a.replace('a','A'), actually calling the method replace works on the string object'abc', and although this method is called replace, it does not change the string'abc' 'Content. On the contrary, the replace method creates a new string'Abc' and returns. If we use the variable b to point to the new string, it is easy to understand. The variable a still points to the original string'abc', but the variable b points to New string'Abc':

┌───┐ ┌───────┐│ a │─────────────────>│ 'abc' │└───┘ 
└───────┘┌───┐ ┌───────┐│ b │─────────────────>│ 'Abc' │└───┘ 
└───────┘

Therefore, for an immutable object, calling any method of the object itself will not change the content of the object itself. Instead, these methods create a new object and return it, thus ensuring that the immutable object itself is always immutable.

summary

A dict with a key-value storage structure is very useful in Python. It is important to choose an immutable object as the key. The most commonly used key is a string.

Although tuple is an invariant object, try to put (1, 2, 3) and (1, [2, 3]) into a dict or set, and explain the result.

Guess you like

Origin blog.csdn.net/Python_xiaobang/article/details/113109221