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

Python if Statement

Python if Statement

Python3 Conditional Statements Python3 Conditional Control


In Python programming,if statement is the most basic and most important conditional control structure. It decides whether to execute a particular block of code based on whether a condition is true or false.

Python's if The statement is very intuitive and readable; it defines code blocks through indentation, which is a major feature distinguishing Python from other languages.

Word meaning: if means "if" and is the entry point of conditional judgment.


Basic syntax and parameters

if The statement is a standalone code block and must be used with a conditional expression.

Syntax format


if conditional expression:
    代码块

Syntax Description

Return value / effect


Example

Let us thoroughly master if the usage of the statement.

Example 1: basic usage - comparing numbers

Example

Basic if statement

age

=

18

if

age

=

18

:

   

print

(

"Adult"

)

print

(

"Program ends"

)

Expected output:

成年人
程序结束

Code analysis:

  1. age >= 18 is a conditional expression that returns True.
  2. Because the condition holds, execute print("成年人")。
  3. print("程序结束") is not inside the indented block of the if, so it is executed regardless of the condition.

Example 2: checking whether a string is empty

Example

Check the string

name

=

""

An empty string is False

if

name:

   

print

(

f

"Hello, {name}"

)

else

:

   

print

(

"Please enter a name"

)

Non-empty string

name

=

"Tom"

if

name:

   

print

(

f

"Hello, {name}"

)

Expected output:

请输入名字
你好, Tom

Code analysis:

Example 3: multiple conditions

Example

Compound condition

score

=

85

Use logical operators

if

score

=

60

and

score

<

90

:

   

print

(

"Passed"

)

Check multiple conditions (simplified form)

if

60

<=

score

<

90

:  

Chained comparisons, a Python speciality

   

print

(

"Score is between 60 and 90"

)

Use in for testing

colors

=

[

"red"

,

"green"

,

"blue"

]

if

"red"

in

colors:

   

print

(

"Contains red"

)

Expected output:

及格了
成绩在 60-90 之间
包含红色

Code analysis:

Example 4: single-line if expression (ternary operator)

Example

Python's ternary expression

age

=

20

Format: value1 if condition else value2

result

=

"Adult"

if

age

=

18

else

"Minor"

print

(

result

)

 

Output: Adult

A more complex example

x

=

10

y

=

20

max_val

=

x

if

x

y

else

y

print

(

f

"Larger value: {max_val}"

)

 

Output: Larger value: 20

Expected output:

成年
较大值: 20

Python's ternary expression is more concise than in traditional languages; its format is value1 if condition else value2。


Python3 Conditional Statements Python3 Conditional Control