Python Learning Notes Collation (10) if test for Python

Source: Internet
Author: User

The If statement is the selection of the action to be performed.
One, if statement
1. General format
The form is an if test followed by one or more optional elif (else IF) tests, as well as a final optional else block. The test and Else sections can be combined with nested statement blocks, indented below the beginning of the line. Python executes the first block of code where the settlement result is true, or if all tests are false, the else block is executed.
The general form of the IF statement is as follows:
If <test1>:
<statements1>
Elif <test2>:
<statements2>
Else
<statements3>
2. Basic
Except for the first if test and its associated statements, all other parts are selectable.
>>> if 1:
.. print ' True '
...
True
You need to handle the case where the test is false and need else. else is the default choice when all test conditions are not met
>>> if not 1:
.. print ' true '
.. else:
... print ' false '
...
False

3. Multi-Channel Branch
>>> x= ' Killer rabbit '
>>> if x = = ' Roger ':
... print "How ' s Jessica?"
... elif x = = ' Bugs ':
... print "What's Up Doc?"
.. else:
... print "Run away!" * *
...
Run away! Run away!
There are no swith and case statements in Ptyhon. A series of If/elif tests are written in the Ptyhon Multi-channel branch. Either index the dictionary or search the list. Because dictionaries and lists can be created at run time, they are sometimes more flexible than hard-coded if logic.
>>> choice= ' Ham '
>>> print {' spam ': 1.25,
... ' Ham ': 1.99,
... ' Eggs ': 0.99,
... ' Bacon ': 1.10}[choice]
1.99
This dictionary is a multi-path branch that is indexed according to the selection of keys, one of the branches to this set of values. The two are equivalent to the C switch, and can also be expressed using Python statements. However, the use of if expression is not concise.
The dictionary default value can be handled by Has_keys tests, get method calls, or exception snaps. Used in a dictionary-style branch to write the default action. The default values are handled here through get support
The situation
>>> ptest={' name ': ' Diege ', ' age ':, ' sex ': ' M '}
>>> print ptest.get (' name ', ' Bad choice ')
Diege
>>> Print Ptest.get (' class ', ' Bad choice ')
Bad choice
Later, you'll learn that a dictionary can also contain functions that represent more complex branching actions and implement a general jumping table. This type of function is used as a dictionary value, usually written as lamdba, by adding parentheses to the trigger action
One more example.

# # #对比shell中的条件表达式 ######
if [test1]
Then
Do something1
elif [Test2]
Then
Do Something2
Else
Do Something3
Fi
Ii. the rules of Python syntax
Python has simple and basic syntax for statements, but some are specific to what we need to know.
* Statements are run one after the other unless you do not write this
* The margins of blocks and statements are automatically detected
* Compound statement = First line + ":" + Indent statement
* Blank lines, spaces, and comments are usually ignored.
* The document string (docstring) will be ignored but will be saved and displayed by the tool.
Pyton supports another type of comment, called a document string.
1. code block Separator
Automatically indents the edge of a block in line. All statements that are indented to the same distance to the right belong to the same block of code. The statements inside the block are aligned vertically, as if they were within a column.
2. Statement delimiter
Python's statements generally end at the end of their line, but when the statement is too long to be placed on a single line, there are special rules that can be used in multiple rows.
1) If you use a pair of syntax brackets, the statement can span several lines. Write code in a pair such as a closed (), {},[]. The following lines can start at any indentation level and should all be vertically aligned.
2) If the statement ends with a backslash, it can span several lines.
3) Triple Quote string constants can span several lines
4) Other rules: about the statement delimiter. Annotations and whitespace can also appear anywhere in the file. Comments are terminated at the end of the row
3. Some special cases
if (A==b and C==d and
D==e and Ee==f):
Print "New"
Python allows you to write more than one non-compound statement on the same line (there are no other statements nested inside the statement), separated by semicolons.
>>> X=3;y=2;print X*y
6
Third, the Truth test
In Python:
* Any non-0 numeric or non-empty object objects are true
* Number 0, empty object and special object none are considered false
* Comparisons and equivalence tests are applied recursively in the data structure.
* Comparison and equality tests will return TRUE or FALSE (special versions of 1 and 0)
* Boolean and and OR operators return TRUE or false operands
The Boolean operator is used to combine the results of other tests, with three Boolean expression operators in Python:
X and Y
If both X and Y are true, it's true.
X or Y
If x or Y is true, it is true
Not X
If x is false, it is true (the expression returns TRUE or false)
X and y can be any truth value or an expression that returns a true value (such as an equality test, a range comparison, and so on). In addition, the Boolean and and OR operators return TRUE or false objects in Python.
Instead of true or false. Returns the object to the left or right of the and or OR operator. (Note: Each object is not true or false)
For or, the operand is evaluated from left to right, and then the first action object that is true is returned. Ptyhon will stop at the place where it finds the first truth. "What if it's not true?" 】
For and, the calculation is true when all is true, and the last object that is true is returned. Stop on the first false object
1, if/else three-dimensional expression
New expressions introduced by Python2.5
A=y if X else Z
Expression Y is executed only if X is true, and expression Z is executed only if X is False
>>> a= ' t ' if ' diege ' Else ' f '
>>> A
' t '
>>> a= ' t ' if ' Else ' f '
>>> A
' F '

>>> x= ""
>>> Y=1
>>> z=2
>>> y if x else Z
2
>>> x=9
>>> y if x else Z
1

Prior to version 2.5, the same effect can be used with care and and OR
A= ((X and Y) or Z)
The following expression is also similar, because the BOOL function converts x to the corresponding integer 1 or 0, and then it is used to pick the true or False value from the list.
A=[z,y][bool (X)]
>>> [' f ', ' t '][bool ("")]
' F '
The syntax of C is also the Shell's
Y? X:z
2. Why care about Boolean values
X=a or B or C or None
Such a statement sets X to the first non-empty (True) object in C, or to none if all objects are not empty.
This is possible because the OR operator returns one of two objects. This becomes quite common in Python to write code tricks: Select non-empty objects from a fixed-size collection as long as they are in a string or expression.
Short-circuit calculations are also important because the expression on the right side of the Boolean operation can invoke functions to perform substantial or important work. Otherwise, if the short-circuit rule is in effect, the additional effect will not occur.
If F1 () or F2 (): ...
Here, if F1 returns True (non-null), Python will no longer execute F2 (), in order to ensure that two functions will execute, or call them before or before.
TMP1,TMP2=F1 (), F2 ()
If TMP1 or TMP2: ...

Used to simulate the If/else statement: ((A and B) or C)
Assuming that B is true, A is true return B "A, A, is true return b,b, return b directly, do not calculate C", if not refer to return C

Finally, since all objects are essentially true or false, in Python, the direct test object (if x:), rather than the null value comparison (if x! = ":), the former is more common and simpler, the test is equivalent in terms of strings.

Python Learning Notes Collation (10) if test for Python

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: 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.