A python conditional statement is the execution result (true or false) of one or more statements that determines which block of code is executed
The Python program language specifies that any non-0 and non-null (NULL) values are true,0 or null to FALSE.
Basic situation:
If Judge condition 1:
EXECUTE statement
Elif Judgment Condition 2:
EXECUTE statement
Else
EXECUTE statement
Instance:
N =100
If n<100:
Print (' n<100 ')
Elif n>100:
Print (' n>100 ')
Else
Print (' n=100 ')
The results of the operation are: n=100
In addition, Python does not support switch statements, where multiple conditional judgments can be combined with and and or, and the example above to determine if a is equal to 100 can be reduced to:
If n<100 and n>100 ...
#!/usr/bin/python
#-*-Coding:utf-8-*-
# example 1:if basic usage
Flag = False
name = ' Luren '
If name = = ' Python ': # to determine if the variable is ' python '
Flag = true # The setting flag is true when the condition is set up
print ' Welcome boss ' # and output welcome information
Else
Output variable name when print name # condition is not valid
The output results are:
>>> Luren # Output results
The condition of the IF statement can be expressed by > (greater than), < (less than), = = = (equal), >= (greater than equal), <= (less than equal), and the relation.
When judging a condition to be multiple values, you can use the following form:
Python does not have switch-case syntax like C/c++,java. However, this function, such as using dictionary and Lambda anonymous function features to replace the implementation.
Like the following code in PHP:
Switch ($value) {
Case ' a ':
$result = $x * 5;
Break
Case ' B ':
$result = $x + 7;
Break
Case ' C ':
$result = $x-2;
Break
}
The equivalent implementation of Python is:
result = {
' A ': Lambda x:x * 5,
' B ': Lambda x:x + 7,
' C ': Lambda x:x-2
}[value] (x)
If it's a slightly more complex function, it can be done, like we compute subtraction, and the function is defined as follows:
def add (a,b):
Return a + b
def multi (a,b):
return * b
def sub (a,b):
Return A-b
def div (a,b):
Return a/b#b is Non-zero
If the switch is implemented, case (' operand ') is the corresponding function to determine the line. Look at the implementation of Python:
Def calc (type,x,y):
Calculation = {' + ': Lambda:add (X,y),
' * ': Lambda:multi (X,y),
'-': lambda:sub (X,y),
'/': Lambda:div (X,y)}
return Calculation[type] ()
#calc = {1:lambda:add (x,y)}[value] ()
RESULT1 = Calc (' + ', 3,6)
RESULT2 = Calc ('-', 3,6)
Print RESULT1, RESULT2
The structure used here is as follows:
Message = {' type1 ': lambda:func1 (some_data),
' type2 ': Lambda:func2 (other_data),
}
Return Message[type] ()