For a friend who has just come into contact with the Python programming language, there is little understanding of the conditional statements in Python when we just started to learn python, and in this article we'll explain
python conditional StatementsAnd
conditional Statements
of the
General FormatKnowledge of this.
Python conditional statements
A python conditional statement determines the code block that executes by executing the result of one or more statements (true or false).
The Python program language specifies any non-0 and non-null (NULL) values of true,0 or NULL to FALSE.
In Python programming, if statements are used in the execution of control programs, in the basic form:
If judgment condition: Execute statement ... else: EXECUTE statement ....
(The above is the general format of the Python conditional statement)
Where the "judging condition" is established (not 0), the following statements are executed, and the execution content can be multiple lines, in order to be indented to differentiate the same range.
Else as an optional statement, you can execute the relevant statement when you need to execute the content when the condition is not true, as shown in the following example:
#!/usr/bin/python#-*-coding:utf-8-*-# example 1:if basic usage flag = Falsename = ' Luren ' if name = = ' Python ': # Judgment variable no is ' python '
flag = True # condition set flag for true print ' welcome boss ' # and OUTPUT welcome message else: Print name # condition not set when output variable name
The results are as follows:
Luren # Output results
The judgment condition of the IF statement can be expressed by > (greater than), < (less than), = = (equals), >= (greater than or equal), <= (less than or equal).
When judging a condition as multiple values, you can use the following form:
If judgment condition 1: EXECUTE statement 1......elif judgment Condition 2: EXECUTE statement 2......elif judgment Condition 3: Execute statement 3......else: EXECUTE statement 4 ...
Examples are as follows:
#!/usr/bin/python#-*-coding:utf-8-*-# example 2:elif usage num = 5 If num = = 3: # Determine NUM's value print ' boss ' elif num = = 2: print ' user ' elif num = = 1: print ' worker ' Elif num < 0: # value is less than zero output print ' error ' else: print ' Roa Dman ' # conditions are not set when the output
The result of the output is:
Roadman # Output results
(because Python does not support switch statements, so many conditions to judge, can only be implemented with Elif, if the judgment requires multiple conditions to be judged at the same time, you can use or (or), indicating that two conditions have a success in determining the condition, when using and (and), Indicates that only two conditions have been established at the same time, the judgment condition succeeds. )