Python if-else Statement Implementation

Document 对象参考手册Python3 Examples

In Python,if-elsethe statement is used to execute different code blocks based on the condition. If the condition is true (True), then executeifthe code in the block; if the condition is false (False), then executeelsethe code in the block.

Example

# Define a variable
x = 10

# Use the if-else statement
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

Code explanation:

  1. x = 10: Define a variablexand assign it the value 10.
  2. if x > 5:: Checkxwhether it is greater than 5. If the condition is true, executeifthe code in the block.
  3. print("x 大于 5"): Ifxit is greater than 5, then output "x is greater than 5".
  4. else:: Ififthe condition is false, executeelsethe code in the block.
  5. print("x 小于或等于 5"): Ifxit is not greater than 5, then output "x is less than or equal to 5".

Output result:

x 大于 5

Document 对象参考手册Python3 Examples

Other extensions