How to use if statement in Python

If statement

The if statement lets us do the conditional statement. If a condition is true the corresponding code block will execute while if the condition is evaluated to false the same code block would not get executed.


name = 'java2s.com'
if name.endswith('2s.com'): 
    print 'Hello, java2s.com' 

The code above generates the following result.

else Clauses

We can add an alternative, with the else clause.


name = 'java2s.com'
if name.endswith('2s.com'): 
   print 'Hello, java2s.com' 
else: # w  w w  . ja v a2 s  .c o  m
   print 'Hello, stranger' 

The code above generates the following result.

elif Clauses

To check for several conditions, you can use elif, which is short for "else if." It is a combination of an if clause and an else clause?an else clause with a condition.

We can use elif to build ladder if statement.


num = 2# from  w w w .j  a  v  a2  s.  c om
if num > 0: 
    print 'The number is positive' 
elif num < 0: 
    print 'The number is negative' 
else: 
    print 'The number is zero' 
    

The code above generates the following result.

Nesting Blocks

We can have if statements inside other if statement blocks, as follows:


number = 10# w ww .  ja v  a 2  s  .  c om
if number <= 10:
    if number >= 1:
        print 'Great!'
    else:
        print 'Wrong!'
else:
    print 'Wrong!'


name = 'java2s.com'
if name.endswith('2s.com'): 
    if name.startswith('java'): 
        print 'Hello, java2s.com' 
    elif name.startswith('pthon.'): 
        print 'Hello, python' 
    else: 
        print 'Hello, 2s.com' 
else: 
    print 'Hello, stranger' 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules