Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement if-else Statement

Python Implement if-else Statement

Document Object Reference Manual Python3 Examples

In Python,if-else statement is used to execute different code blocks based on a condition. If the condition is True, the code in the if block is executed; if the condition is False, the code in the else block is executed.

Example

Define a variable

x

=

10

Use an if-else statement

if

x

5

:

   

print

(

"x is greater than 5"

)

else

:

   

print

(

"x is less than or equal to 5"

)

Code analysis:

  1. x = 10: define a variable x and assign it the value 10.
  2. if x > 5:: Check whether x is greater than 5. If the condition is true, execute the if block is executed.
  3. print("x 大于 5"): If x is greater than 5, output "x is greater than 5".
  4. else:: If if condition is false, execute the else block is executed.
  5. print("x 小于或等于 5"): If x is not greater than 5, output "x is less than or equal to 5".

Output result:

x 大于 5

Document Object Reference Manual Python3 Examples