Python from rookie to Master (9): Conditional and conditional statements

Source: Internet
Author: User

Tags: publishing translation attention length Dev branch from rookie to master assignment

1. Boolean (Boolean) values and Boolean variables

?? Before you speak a conditional statement, you should first look at the Boolean type. A conditional statement (if) needs to specify a Boolean or Boolean variable to determine whether the statement in the code block is to be specified according to the criteria. A Boolean value has only two values: True and false, which can be translated into true and false.

?? Now that we've learned what Boolean values are for, but what values does the Python language think of As Boolean values? In fact, in the Python language, each type of value can be interpreted as a Boolean-type value. For example, the following values are interpreted as false in a Boolean value.

None  0  ""  ()  []  {}

?? There are some types of data involved in these values that we have not talked about (for example, [] to represent a 0-length list), but the reader does not have to worry about these data types in the following chapters.

?? If the above values are used in a conditional statement, the conditions in the conditional statement are interpreted as false, that is, the statements in the conditional code block are not executed.

?? At the bottom of the Python language, the Boolean value of TRUE is treated as 1, and the Boolean value false as 0, although on the surface, true and 1, false, and 0 are completely different two values, but in fact, they are the same. We can verify this in the Python console.

>>> True == 1True>>> False == 0True>>> True + False + 2021

?? It is clear that we can directly treat true as 1,false as 0, or we can directly use True and false as 1 and 0, so true + False + 20 evaluates to 21.

?? In addition, we can use the BOOL function to convert values of other types to Boolean types.

>>> bool("")False>>> bool("Hello")True>>> bool([])False>>> bool([1,2,3])True>>> bool(20)True>>> bool(‘‘)False

?? We can see that some of the values given earlier by the system are considered false, and the conversion of the BOOL function becomes the true Boolean value. However, these values cannot be compared directly to a Boolean value, for example, "[] = = False" is not directly used, so it is correct to convert it to a Boolean value using the BOOL function before comparing
BOOL ([]) = = False

?? In the preceding code, the "= =" operator, which is a logical operator, is a two-tuple operator, needs to specify that the left and right two operands are used to determine whether two values are equal, and if two operands are equal, the result of the operation is true, otherwise false. This operator is often used in subsequent chapters, and there are, of course, many similar operators that are introduced together when explaining conditional statements.

2. Conditional statements (if, else, and Elif)

?? For computer programs, the first skill to learn is "turn", that is, according to different conditions, the implementation of different branches of the program, such a program is meaningful.

?? The function of the IF statement is to give the program a "turn" skill. Use the IF statement to use the code block described in Section 3.3. The Python language requires that the code block to be executed when the condition of the IF statement is met must be indented (typically, 4 spaces are indented). The syntax format for the IF statement is as follows:

if logic expression:        #  if代码块开始    statement1    statement2    … …    statementnotherstatement              #  if代码块结束

?? Where logic expression is the expression representing the logical expressions, which is the return of the Boolean type value (True or false). Because the various data types of a Python statement can be used as Boolean types, logic expression can be seen as a normal expression. According to the rules of the code block, a colon (:) is used at the end of the beginning line of each code block, and if the block ends, it will fall back to the indentation of the start line of the code block.

?? The following is the basic use of the IF statement.

n = 3if n == 3:    print("n == 3")print("if代码块结束")

?? In the above code, "n = = 3" is a logical expression, and the value in this example is true. The "print (" n = = 3 ")" is the statement in the if code block, and because the value of "n = = 3" is True, "print (" n = = 3 ")" is executed. The last statement does not belong to the if code block, so this line of code will be executed regardless of whether the condition of the IF statement is true.

?? For conditional statements, there are often more than one branch. For example, the above code if the value of the variable n is 4, then the condition of the IF statement is false, and if you want to perform a branch with false conditions, you can use the ELSE clause.

n = 4if n == 3:    print("n == 3")else:    print("n等于其他值")    print("if代码块结束")

?? In the above code, n equals 4, so the condition of the IF statement is false, so the statement in the Else code block is executed. If and else are blocks of code, so the IF statement and the Else statement are followed by a colon (:).

?? In a multi-branch conditional statement, you need to set more conditions using the ELIF clause. Elif is followed by a logical expression, and Elif is also a block of code, so you'll end with a colon (:). Also, in an if statement, the IF and else sections can have only one, and the elif part may have any number.

n = 4if n == 3:    print("n == 3")elif n == 4:    print("n == 4")elif n == 5:    print("n == 5")else:    print("n等于其他值")    print("if代码块结束")

?? This example uses the Raw_input function to enter a name from the console and then uses the conditional statement to determine what letter the name begins with.

from click._compat import raw_inputname = raw_input("请输入您的名字:")        #  从控制台输入名字if name.startswith("B"):                #  if代码块    print("名字以B开头")elif name.startswith("F"):              #  elif代码块    print("名字以F开头")elif name.startswith("T"):              #  elif代码块    print("名字以T开头")else:                                   #  else代码块    print("名字以其他字母开头")

?? The program runs as shown in the results.

3. Nested code blocks

?? Conditional statements can be nested, that is, in a conditional code block, you can have another conditional code block. code block A that contains nested code block B can be called a parent code block of B. Nested code blocks still need to increase the amount of indentation on the basis of the parent code block to place their own blocks of code. The following example shows how to use nested blocks of code to make logical judgments.

?? This example requires entering a name in the Python console and then outputting the result based on the judging result by judging the name entered in the nested code block.

name = input("你叫什么名字?")         #  从Python控制台输入一个字符串(姓名)if  name.startswith("Bill"):            #  以Bill开头的姓名    if name.endswith("Gates"):          #  以Gates结尾的姓名(嵌套代码块)        print("欢迎Bill Gates先生")    elif name.endswith("Clinton"):      #  以Clinton结尾的姓名        print("欢迎克林顿先生")    else:                               #  其他姓名        print("未知姓名")elif name.startswith("李"):              #  以“李”开头的姓名    if name.endswith("宁"):              #  以“宁”结尾的姓名        print("欢迎李宁老师")    else:                               #  其他姓名        print("未知姓名")else:                                   #  其他姓名    print("未知姓名")

The program runs as shown in the results.

"Python from rookie to master" began to reprint, please pay attention to

4. Comparison operators

?? Although the knowledge of the IF statement itself has so far been finished, our study is far from being introduced. The conditions for the IF statement given above are very simple, but in practice the conditions of the IF statement can be very complex, which requires using the comparison operator described in this sectionto.
Now let's take a look at the comparison operators in the Python language listed in the following table.

?? The comparison operators described in the superscript refer to the concept of objects and containers, which we have not yet talked about, and in this section the reader only needs to understand that the Python language can manipulate objects and containers by comparison operators, and later on the chapters of objects and containers, detailing how to manipulate objects and containers with correlation comparison operators.

?? In comparison operators, the most common is to determine whether two values are equal, for example, a greater than b,a equals B. These operators include "= =", "<", ">", ">=", "<=", and "X! = y".
?? If you compare two values for equality, you need to use the "= =" operator, which is the two equals sign.

>>> "hello" == "hello"True>>> "Hello" == "hello"False>>> 30 == 10False

?? Note that if you compare two strings for equality, each of the corresponding letters in the two string is compared, so "hello" and "hello" are not equal, that is, the comparison operator is case-sensitive.

?? When using the "= =" operator, be careful not to write an equal sign (=), otherwise it will be an assignment operator, and for an assignment operator, the left side of the equal sign (=) must be a variable, otherwise an exception will be thrown.

>>> "hello" = "hello"               # 使用赋值运算符,会抛出异常  File "<stdin>", line 1SyntaxError: can‘t assign to literal>>> s = "hello">>> s‘hello‘

?? For values of type string, numeric, and so on, you can also compare their sizes with operators greater than (>), less than (<).

>>> "hello" > "Hello"  True>>> 20 > 30False>>> s = 40>>> s <= 30False>>> "hello" != "Hello"True

?? When comparing strings, the Python language is compared in alphabetical ASCII order, for example, comparing the sizes of "Hello" and "Hello". The first is to compare the size of ' h ' and ' H ', obviously the ASCII of ' H ' is greater than ' h ', so there is no need to compare it later, so the result of "Hello" > "Hello" is true.

?? If a string is the prefix of another string, then comparing the two strings, the Python language will assume that the long string is larger.

>>> "hello" < "hello world"True

?? In addition to the few operators that compare size, it is useful to determine whether two objects are equal, and operators that determine whether a value belongs to a container, although there are no objects and containers yet, but here's an experiment to see how these operators are used so that later learning objects and containers are, These operators are more easily mastered.

?? The operators used to determine the equality of two objects are is and is not, and the two operators look similar to the equals operator (= =), but they are very tricky to use.

>>> x = y = [1,2,3]>>> z = [1,2,3]>>> x == yTrue>>> x == zTrue>>> x is yTrue>>> x is zFalse>>> x is not zTrue

?? In the above code, the result is exactly the same when you compare X and y with "= =" and "is", but when you compare X and Z, the differences are shown. The result of x = = Z is true, and X is Z results in false. This result occurs because the "= =" operator compares the value of the object, both the X and Z values are a list (you can also think of the list as an object), and the number of elements in the list is exactly the same as the value, so the result of x = = Z is true. But the "is" operator is used to determine the identity of an object, that is, not only the value of the object is exactly the same, but also the object itself is the same object, it is clear that X and Y are the same object, because when assigning a value, a list is assigned to Y, and then the value of y is assigned to x, so X and Z also assigns a list, so z and X, y, although the values are the same, but not the same object, so the result of X is Z is false.

?? To determine whether a value belongs to a container, use the "in" and "not" operators. The following code first defines a list variable x and then determines whether the variable y and some values belong to X.

>>> x = [1,2,3,4,5]     # 定义一个列表变量>>> y = 3>>> 1 in xTrue>>> y in xTrue>>> 20 in xFalse>>> 20 not in xTrue

??“ The in and not-in operators can also be used to determine whether a string contains another string, that is, a string can be treated as a container of characters or substrings.

>>> s = "hello world">>> ‘e‘ in sTrue>>> "e" in sTrue>>> "x" in sFalse>>> "x" not in sTrue>>> "world"  in sTrue

?? If you encounter situations where you need to combine multiple logical expressions, you need to use logic and (and), logic or (or), and logical non (not). The logical and arithmetic rule is that only X and Y are true in the case of "X", the result of the operation is true, otherwise false. The logical OR operation rule is that only X and y in "x or Y" are false, the result of the operation is false, otherwise it is true. The logical non-operation rule is "not X", X is true, the result of the operation is false,x to false, and the result of the operation is true.

>>> 20 < 30 and 40 < 50True>>> 20 > 40 or 20 < 10False>>> not 20 > 40True

?? This example demonstrates the basic use of comparison operators.

print(20 == 30)         #  判断20和30是否相等,运行结果:False   x = 20y = 40print(x < y)                #  判断x是否小于y,运行结果:Trueif x > y:                   #  条件不满足    print("x > y")else:                       #  条件满足    print("x <= y")s1 = "hello"s2 = "Hello"if s1 >= s2 and x > y:      # 条件不满足    print("满足条件")elif not s1 < s2:           # 条件满足    print("基本满足条件")else:                       # 条件不满足    print("不满足条件")

The program runs as shown in the results.

5. Assertion (assertions)

?? Assertions are used in a manner similar to the IF statement, except that exceptions are thrown directly when the condition is not met. Similar to the following if statement (pseudo code)

if not dondition:       # 如果不满足条件,会直接抛出异常,程序会中断    crash program

?? So why is this code needed? This is mainly due to the need to monitor whether the program meets the conditions somewhere, and if the condition is not met, the developer should be notified in a timely manner rather than hiding the bugs until the critical moment crashes.

?? In fact, assertions are often used in TDD (Test-driven development, test-driven development), and TDD executes assertions when the program discovers exceptions and throws exceptions.
In the Python language, assertions require an Assert statement that specifies the conditional expression of an assertion after the Assert keyword. If the value of the conditional expression is false, an exception is thrown. And the assertion that subsequent statements are not executed is equivalent to a breakpoint on the program.

>>> value = 20>>> assert value < 10 or value > 30     # 条件不满足,会抛出异常Traceback (most recent call last):  File "<stdin>", line 1, in <module>AssertionError>>> assert value < 30                   #  条件满足,会正常执行后面的语句

?? As we can see, the value variable is 20, and the condition after the assert is "value < ten or value > 30", it is obvious that the condition is not satisfied, so an exception is thrown at the assertion. The latter assertion, the condition is "value < 30", the condition is satisfied, so the statement after the assertion will execute normally.

?? Throws an exception when the assertion condition is not met, by default, shows only where the exception was thrown, and does not show what throws the exception, so for the exception information to be more explicit, you can specify an exception description for the Assert statement.

>>> value = 20>>> assert value < 10 or value > 30, ‘value值必须在10和20之间‘ # 为断言指定异常描述信息Traceback (most recent call last):  File "<stdin>", line 1, in <module>AssertionError: value值必须在10和20之间            # 显示了异常描述信息

This example demonstrates the use of assertions.

name = "Bill"                           #  定义变量nameassert name == "Bill"                   #  断言条件表达式的值是True,继续执行下面的语句age = 20                                #  定义变量age#  断言条件表达式的值是False,抛出异常,后面的代码不会被执行assert 0 < age < 10, "年龄必须小于10岁"    print("hello world")        # 这行代码不会被执行

The program runs as shown in the results.

"Python from rookie to Master" has been published, began to serial, buy send video lessons

Python from rookie to Master (9): Conditional and conditional statements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: