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

Python3 Conditional Control

Python3 Conditional Control

Python conditional statements decide which code block to execute based on the result (True or False) of one or more statements.

The following diagram gives a simple view of how conditional statements execute:

Code execution process:

Conditional keywords

Keyword / function Description Example
if A conditional statement that executes a code block when the condition is True if x > 0:
elif Multi-condition branch (else if) elif x == 0:
else Executed when none of the conditions is satisfied else:
pass An empty statement used as a placeholder to keep the syntax complete if x > 0: pass
match Structural pattern matching (Python 3.10+, similar to switch) match x: case 1: ...

if statement

The general form of an if statement in Python is as follows:

if

condition_1

:

statement_block_1

elif

condition_2

:

statement_block_2

else

:

statement_block_3

In Python, elif replaces else if, so the keywords of the if statement are:if – elif – else。

Note:

GIF demonstration:

Example

Below is a simple if example:

Example

#!/usr/bin/python3

var1

=

100

if

var1

:

print

(

"

1 - the if expression condition is true

"

)

print

(

var1

)

var2

=

0

if

var2

:

print

(

"

2 - the if expression condition is true

"

)

print

(

var2

)

print

(

"

Good bye!

"

)

The output of the code above is:


1 - if 表达式条件为 true
100
Good bye!

From the result you can see that because variable var2 is 0, the statements inside the corresponding if were not executed.

The following example shows a dog's age calculation:

Example

#!/usr/bin/python3

age

=

int

(

input

(

"

Enter your dog's age:

"

)

)

print

(

"

"

)

if

age

<=

0

:

print

(

"

You must be kidding me!

"

)

elif

age

==

1

:

print

(

"

Equivalent to a 14-year-old human.

"

)

elif

age

==

2

:

print

(

"

Equivalent to a 22-year-old human.

"

)

elif

age

2

:

human

=

22

(

age

2

)

5

print

(

"

Corresponding human age:

"

,

human

)

Exit prompt

input

(

"

Press the enter key to exit

"

)

Save the script above in a dog.py file and run the script:


$ python3 dog.py 
请输入你家狗狗的年龄: 1

相当于 14 岁的人。
点击 enter 键退出

Common operators used in if statements:

Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to, checks whether two values are equal
!= Not equal

Example

#!/usr/bin/python3

The program demonstrates the == operator

Using numbers

print

(

5

==

6

)

Using variables

x

=

5

y

=

8

print

(

x

==

y

)

The example above produces the following output:


False
False

The high_low.py file demonstrates numeric comparison operations:

Example

#!/usr/bin/python3

This example demonstrates a number guessing game

number

=

7

guess

= -

1

print

(

"

Number guessing game!

"

)

while

guess

!=

number

:

guess

=

int

(

input

(

"

Enter your guess:

"

)

)

if

guess

==

number

:

print

(

"

Congratulations, you guessed right!

"

)

elif

guess

<

number

:

print

(

"

Your guess is too low...

"

)

elif

guess

number

:

print

(

"

Your guess is too high...

"

)

Running the script above produces the following example output:


$ python3 high_low.py 
数字猜谜游戏!
请输入你猜的数字:1
猜的数字小了...
请输入你猜的数字:9
猜的数字大了...
请输入你猜的数字:7
恭喜,你猜对了!

Nested if

In nested if statements, you can place an if...elif...else structure inside another if...elif...else structure.


if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句

Example

!/usr/bin/python3

num

=

int

(

input

(

"

Enter a number:

"

)

)

if

num

%

2

==

0

:

if

num

%

3

==

0

:

print

(

"

The number you entered is divisible by both 2 and 3

"

)

else

:

print

(

"

The number you entered is divisible by 2 but not by 3

"

)

else

:

if

num

%

3

==

0

:

print

(

"

The number you entered is divisible by 3 but not by 2

"

)

else

:

print

(

"

The number you entered is divisible by neither 2 nor 3

"

)

Save the program above in a test_if.py file; running it produces:


$ python3 test.py 
输入一个数字:6
你输入的数字可以整除 2 和 3

match...case

Python 3.10 added the match...case conditional judgment, so a long chain of if-else is no longer needed.

The object after match is compared with the contents after each case in turn; if it matches, the matched expression is executed, otherwise it is skipped; _ matches anything.

match subject case ? Matches action_1 No match case ? Matches action_2 No match case ? Matches action_3 No match case _ (wildcard) Always matches wildcard

The syntax format is as follows:

match subject:
    case :
        
    case :
        
    case :
        
    case _:
        

case _: is similar to default: in C and Java; when no other case matches, this one is used, guaranteeing a match.

Example

def

http_error

(

status

)

:

    match status:

        case

400

:

           

return

"Bad request"

        case

404

:

           

return

"Not found"

        case

418

:

           

return

"I'm a teapot"

        case _:

           

return

"Something's wrong with the internet"

 

print

(

http_error

(

400

)

)

print

(

http_error

(

404

)

)

print

(

http_error

(

418

)

)

print

(

http_error

(

500

)

)

The above is an example that outputs HTTP status codes; the output for several status codes is:

Bad request
Not found
I'm a teapot
Something's wrong with the internet

A case can also set multiple matching conditions separated by |, for example:

...
    case 401|403|404:
        return "Not allowed"
status 401 403 404 | | "Not allowed"

Example

def

check_permission

(

status

)

:

    match status:

        case

200

:

           

return

"OK - request succeeded"

        case

301

|

302

:

           

return

"Redirect - redirection"

        case

401

|

403

|

404

:

           

return

"Not allowed - no permission or not found"

        case

500

|

502

|

503

:

           

return

"Server Error - server error"

        case _:

           

return

"Unknown status - unknown status code"

 

for

code

in

[

200

,

301

,

403

,

500

,

418

]

:

   

print

(

f

"Status code {code}: {check_permission(code)}"

)

For more on match...case, see:Python match-case statement