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

Source: Internet
Author: User
Tags stdin
1. Boolean values and variables
?? Before talking about conditional statements, you should first understand Boolean types. The conditional statement (if) needs to be assigned a Boolean value or a Boolean type variable in order to determine whether to specify a statement in the code block according to the condition. Boolean values have only two values: True and False, which can be translated into "True" and "False".

?? Now that we know what Boolean values are used for, but what values does Python treat as booleans? In fact, in Python, every type of value can be interpreted as a Boolean value. For example, the following values are interpreted as False in Boolean values.

None 0 "" () [] {}
?? There are some data types involved in these values that we haven't talked about so far (for example, [] represents a list of length 0), but the reader should not worry, these data types will be explained in detail in later chapters.

?? If you use these values in a conditional statement, the conditions in the conditional statement will be interpreted as False, that is, the statements in the conditional code block will not be executed.

?? At the bottom of the Python language, the Boolean value True is regarded as 1, and the Boolean value False is regarded as 0. Although on the surface, True and 1, False, and 0 are completely different values, in fact, they Are the same. We can verify this in the Python console.

>>> True == 1
True
>>> False == 0
True
>>> True + False + 20
twenty one
?? Obviously, we can directly consider True as 1, False as 0, or directly use True and False as 1 and 0, so the calculation result of True + False + 20 is 21.

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

>>> bool ("")
False
>>> bool ("Hello")
True
>>> bool ([])
False
>>> bool ([1,2,3])
True
>>> bool (20)
True
>>> bool (‘‘)
False
?? We can see that the several values given earlier will be considered to be False by the system, and will be converted to true Boolean values through the conversion of the bool function. However, these values cannot be directly compared with Boolean values. For example, you cannot directly use "[] == false". The correct way is to use the bool function to convert them to Boolean values, and then compare them.
bool ([]) == false

?? The "==" operator is used in the previous code. This is a logical operator and a binary operator. You need to specify the left and right operands to determine whether the two values are equal. If the two operands are equal, The result of the operation is True, otherwise it is False. This operator will be used frequently in later chapters. Of course, there are many similar operators, which will be introduced together when explaining conditional statements.

2. Conditional statements (if, else, and elif)
?? For computer programs, the first skill to learn is "turning", that is, according to different conditions, execute different program branches, such a program is meaningful.

The role of the if statement is to give the program this "turning" skill. Using the if statement requires the code block described in Section 3.3. The Python language requires that the code block to be executed must be indented when the conditions of the if statement are met (usually 4 spaces). The syntax of the if statement is as follows:

if logic expression: # if code block starts
    statement1
    statement2
    ...
    statementn
otherstatement # if end of code block
?? Where logical expression represents a logical expression, that is, an expression that returns a Boolean value (True or False). Since various data types of Python statements can be used as Boolean types, logical expressions can be regarded as ordinary expressions. According to the rules of the code block, use a colon (:) at the end of the start line of each code block. If the end of the if code block, it will fall back to the indentation of the start line of the code block.

The following is the basic usage of the if statement.

n = 3
if n == 3:
    print ("n == 3")
print ("End of if code block")
?? In the above code, "n == 3" is a logical expression, and the value in this example is True. And "print (" n == 3 ")" is a statement in the if code block. Since "n == 3" is True, "print (" n == 3 ")" will be 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, often more than one branch. For example, if the value of the variable n is 4, the condition of the if statement is False. In this case, to execute a branch with a condition of False, you can use the else clause.

n = 4
if n == 3:
    print ("n == 3")
else:
    print ("n is equal to other values")
print ("End of if code block")
?? In the above code, n is equal to 4, so the condition of the if statement is False, so the statements in the else code block will be executed. Both if and else are code blocks, so if and else statements must end with a colon (:).

?? In multi-branch conditional statements, you need to use the elif clause to set more conditions. Elif is followed by a logical expression, and elif is also a code block, so it must end with a colon (:). In addition, in an if statement, there can be only one if and else parts, and there can be any number of elif parts.

n = 4
if n == 3:
    print ("n == 3")
elif n == 4:
    print ("n == 4")
elif n == 5:
    print ("n == 5")
else:
    print ("n is equal to other values")
print ("End of if code block")
?? This example uses the raw_input function to enter a name from the console, and then use a conditional statement to determine what letter the name begins with.


from click._compat import raw_input
name = raw_input ("Please enter your name:") # Enter the name from the console
if name.startswith ("B"): # if block
    print ("Name starts with B")
elif name.startswith ("F"): # elif code block
    print ("Name starts with F")
elif name.startswith ("T"): # elif code block
    print ("Name starts with T")
else: # else code block
    print ("Name starts with other letters")
?? The results of the program run as shown.

3. Nested code blocks
?? Conditional statements can be nested, that is, in a conditional code block, there can be another conditional code block. A code block A containing a nested code block B may be referred to as B's parent code block. Nested code blocks still need to be indented on top of the parent code block to place their own code block. The following example shows how to use nested code blocks for logical judgment.

?? This example requires entering a name in the Python console, and then judging the input name in a nested code block, and output the result according to the judgment result.

name = input ("What's your name?") # Enter a string (name) from the Python console
if name.startswith ("Bill"): # Names that begin with Bill
    if name.endswith ("Gates"): # Names ending with Gates (nested code block)
        print ("Welcome Mr. Bill Gates")
    elif name.endswith ("Clinton"): # names ending in Clinton
        print ("Welcome Mr. Clinton")
    else: # other names
        print ("Unknown name")
elif name.startswith ("李"): # Names starting with "李"
    if name.endswith ("宁"): # names ending in "宁"
        print ("Welcome Teacher Li Ning")
    else: # other names
        print ("Unknown name")
else: # other names
    print ("Unknown name")
The program operation results are shown below.

"Python from novice to master" has been reprinted, so stay tuned

4. Comparison operators
?? Although the knowledge of the if statement itself has been completely explained so far, our study is far from being introduced. The conditions of the if statements given earlier are very simple, but in practical applications, the conditions of the if statements may be very complicated, which requires the use of the comparison operators introduced in this section.
Now let's take a look at the comparison operators in the Python language listed in the table below.

?? The comparison operators described by the superscript involve the concepts of objects and containers. At present, we have not talked about these technologies. In this section, the reader only needs to understand that Python can manipulate objects and containers through comparison operators. The chapter on objects and containers describes in detail how to manipulate objects and containers with related comparison operators.

?? In comparison operators, the most commonly used is to determine whether two values are equal, for example, a is greater than b, a is equal to b. These operators include "==", "<", ">", "> =", "<=" and "x! = Y".
?? If you compare two values for equality, you need to use the "==" operator, that is, two equal signs.

>>> "hello" == "hello"
True
>>> "Hello" == "hello"
False
>>> 30 == 10
False
?? Note that if you compare two strings for equality, each letter in the two strings will be compared, so "Hello" and "hello" are not equal, which means that the comparison operator is case sensitive of.

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


>>> "hello" = "hello" # using the assignment operator will throw an exception
  File "<stdin>", line 1
SyntaxError: ca n‘t assign to literal
>>> s = "hello"
>>> s
‘Hello’
?? For string, numeric and other types of values, you can also use the greater than (>), less than (<) and other operators to compare their sizes.

>>> "hello"> "Hello"
True
>>> 20> 30
False
>>> s = 40
>>> s <= 30
False
>>> "hello"! = "Hello"
True
?? Python compares strings in alphabetical ASCII order when comparing strings, for example, comparing the sizes of "hello" and "Hello". First, the sizes of ‘h’ and ‘H’ are compared. Obviously, the ASCII of ‘h’ is greater than the ASCII of ‘H’, so there is no need to compare them. Therefore, the result of "hello"> "Hello" is True.

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

>>> "hello" <"hello world"
True
?? In addition to several operators to compare the size, there are operators to determine whether two objects are equal, and to determine whether a value belongs to a container operator, although objects and containers have not been mentioned yet, but here May wish to do an experiment to see how these operators are used, so that in the future learning objects and containers is easier to master these operators.

?? The operators used to determine whether two objects are equal are is and is not. These two operators look similar to the equal operator (==), but they are quite mysterious.

>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>
>> x is z
False
>>> x is not z
True
?? In the above code, using "==" and "is" to compare x and y results are exactly the same, but when comparing x and z, the difference will be reflected. The result of x == z is True, while the result of x is z is False. This result occurs because the "==" operator compares the values of the objects, the values of x and z are a list (the list can also be regarded as an object), and the number and value of elements in the list Exactly the same, so the result of x == z is True. But the "is" operator is used to judge the identity of objects, that is, not only the values of the objects must be exactly the same, but also the objects themselves must be the same object. Obviously, x and y are the same object, because when assigning , First assign a list to y, and then assign the value of y to x, so x and y point to the same object, and z assigns another list, so although z, x, and y have the same value, they are not Points to 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 in" 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] # define a list variable
>>> y = 3
>>> 1 in x
True
>>> y in x
True
>>> 20 in x
False
>>> 20 not in x
True
?? "in" and "not in" operators can also be used to determine whether a string contains another string, that is, you can use the string as a container for characters or substrings.

>>> s = "hello world"
>>> ‘e’ in s
True
>>> "e" in s
True
>>> "x" in s
False
>>> "x" not in s
True
>>> "world" in s
True
?? If you need to combine multiple logical expressions together, you need to use logical AND, logical OR, and logical NOT. The logical AND operation rule is that the operation result is True only if x and y in "x and y" are both True, otherwise it is False. The logical OR operation rule is that the operation result is False only if both x and y in "x or y" are False, otherwise both are True. The logical NOT operation rule is "not x", where x is True, the operation result is False, x is False, and the operation result is True.

>>> 20 <30 and 40 <50
True
>>> 20> 40 or 20 <10
False
>>> not 20> 40
True
?? This example demonstrates the basic use of comparison operators.

print (20 == 30) # Determine if 20 and 30 are equal. Result: False
x = 20
y = 40
print (x <y) # determine if x is less than y, running result: True
if x> y: # condition is not met
    print ("x> y")
else: # condition is met
    print ("x <= y")
s1 = "hello"
s2 = "Hello"
if s1> = s2 and x> y: # condition is not met
    print ("conditions met")
elif not s1 <s2: # condition is met
    print ("Basically meets the conditions")
else: # condition is not met
    print ("Not satisfied")
The program operation results are shown below.

5. Assertions
?? Assertions are used in a similar way to if statements, except that when conditions are not met, an exception is thrown directly. Similar to the following if statement (pseudo code)

if not dondition: # If the condition is not met, an exception will be thrown directly and the program will be interrupted
    crash program
?? So why do you need such code? The main reason is that you need to monitor whether the program meets the conditions in a certain place. If the conditions are not met, you should notify the developer in time, rather than hiding these bugs until the critical moment.

In fact, assertions are often used in TDD (Test-driven development, Test-driven development), TDD will execute assertions when the program finds an exception, and throw an exception.
In Python, assertions require an assert statement, and the conditional expression of the assertion is specified after the assert keyword. If the value of the conditional expression is False, then an exception is thrown. And the statement after the assertion will not be executed, which is equivalent to a breakpoint of the program.

>>> value = 20
>>> assert value <10 or value> 30 # If the condition is not met, an exception will be thrown
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert value <30 # If the condition is satisfied, the following statements will be executed normally
?? We can see that the value of the value variable is 20, and the condition after the assert is "value <10 or value> 30". Obviously, the condition is not met, so an exception is thrown at the assertion. For the subsequent assertions, the condition is "value <30". This condition is satisfied, so the statements after the assertion will be executed normally.

?? When an assertion condition is not met, an exception is thrown. By default, only the location where the exception is thrown is displayed. It does not show what the exception was thrown. Therefore, for more specific exception information, you can specify an exception description for the assert statement.

>>> value = 20
>>> assert value <10 or value> 30, ‘value must be between 10 and 20’ # specify the exception description for the assertion
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: value must be between 10 and 20 # shows the exception description
This example demonstrates the use of assertions.

name = "Bill" # define variable name
assert name == "Bill" # Assert that the value of the conditional expression is True, continue to execute the following statement

age = 20 # define variable age
# Assert that the value of the condition expression is False, throw an exception, and the subsequent code will not be executed
assert 0 <age <10, "Age must be under 10"

print ("hello world") # this line of code will not be executed
The program operation results are shown below.

"Python from rookie to master" has been published, serialization has begun, buy and send video courses

Python from novice to master (9): conditions and conditional statements

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.