“if” statement
"if"
tell the program execute the section of code when the condition evaluates to
true.
Syntax
if_stmt
::= "if" expression
":" suite
test.py
a=10 if (a < 10) : print("a is less than 10") if (a == 10) : print("a is equal to 10") if( a > 10) : print("a is greater than 10")
$ python3
test.py
a is equal
to 10
if-else statement
If the
condition true, then if block code executed. other wise else block code
executed.
Syntax
if_stmt
::= "if" expression
":" suite
["else" ":" suite]
test.py
a=10 if (a != 10) : print("a is not equal to 10") else : print("a is equal to 10")
if-elif-else statement
By using
if-elif-else construct, you can choose number of alternatives. An if statement
can be followed by an optional elif...else statement.
Syntax
if_stmt
::= "if" expression
":" suite
( "elif" expression
":" suite )*
["else" ":"
suite]
test.py
a=10 if (a > 10) : print("a is greater than 10") elif (a < 10) : print("a is less than 10") else : print("a is equal to 10")
$ python3
test.py
a is equal
to 10
Note:
a. In
python, any non-zero integer value is treated as true; zero is false.
test.py
if (100) : print("Hello") else : print("Bye")
$ python3
test.py
Hello
b. Any
sequence (string, list etc.,) with a non-zero length is true, empty sequences
are false.
test.py
list=[] data="abc" if (list) : print("list is not empty") else : print("list is empty") if (data) : print("data is not empty") else : print("data is empty")
$ python3
test.py
list is
empty
data is not
empty
No comments:
Post a Comment