1. If statements
number = 10
if number < 20:
print('right')
Copy the code
Description:
If you use an if statement, if there is only one statement, the block can be written directly to the right of the colon “:”, as in the following code
number = 10
if number < 20:print('right')
Copy the code
2. if… else
a = -9
if a > 0:
b = a
else:
b = -a
Copy the code
I could just write it as
a = -9
b = a if a > 0 else -a
Copy the code
3. if… elif… else
number = 1
if number == 1:
print('1 flower, you are the only one for me! ')
elif number == 3:
print('3朵,i love you')
else:
print('number')
Copy the code
Conditional expressions
- In program development, it is often conditional to assign values according to the results of expressions. For example, to return two words with a large number of characters, use the following if statement.
a = 10
b = 6
if a > b:
r = a
else:
r = b
Copy the code
The above code can be simplified using conditional expressions as follows:
a = 10
b = 6
r = a if a > b elseWhen b uses a conditional expression, it evaluates the intermediate condition (a > b) first and returns the result if trueifThe value on the left side of the statement, otherwise returnselseThe right-hand value.Copy the code