Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - Nested if Statement



Python supportsnested if statements which means we can use a conditionalif andif...else statement inside an existingif statement.

There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nestedif construct.

Additionally, within a nestedif construct, you can include anif...elif...else construct inside anotherif...elif...else construct.

Syntax of Nested if Statement

The syntax of the nestedif construct with else condition will be like this −

if boolean_expression1:   statement(s)   if boolean_expression2:      statement(s)

Flowchart of Nested if Statement

Following is the flowchart of Python nested if statement −

nested if statement flowchart

Example of Nested if Statement

The below example shows the working of nested if statements −

num = 36print ("num = ", num)if num % 2 == 0:   if num % 3 == 0:      print ("Divisible by 3 and 2")print("....execution ends....")

When you run the above code, it will display the following result −

num =  36Divisible by 3 and 2....execution ends....

Nested if Statement with else Condition

As mentioned earlier, we can nestif-else statement within anif statement. If theif condition is true, the firstif-else statement will be executed otherwise, statements inside theelse block will be executed.

Syntax

The syntax of thenested if construct with else condition will be like this −

if expression1:   statement(s)   if expression2:      statement(s)   else      statement(s)else:   if expression3:      statement(s)   else:      statement(s)

Example

Now let's take a Python code to understand how it works −

num=8print ("num = ",num)if num%2==0:   if num%3==0:      print ("Divisible by 3 and 2")   else:      print ("divisible by 2 not divisible by 3")else:   if num%3==0:      print ("divisible by 3 not divisible by 2")   else:      print ("not Divisible by 2 not divisible by 3")

When the above code is executed, it produces the followingoutput

num = 8divisible by 2 not divisible by 3num = 15divisible by 3 not divisible by 2num = 12Divisible by 3 and 2num = 5not Divisible by 2 not divisible by 3
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp