Programming Tutorials

python if

By: Ashley J in Python Tutorials on 2017-09-27  

Often, you need to execute some statements only when some condition is true. Or in some cases you would need to execure different blocks of code based on a condition. The compound statement if -comprising if, elif, and else clauses-lets you conditionally execute blocks of statements. The syntax for the if statement is:

if expression: 
    statement(s) 
elif expression: 
    statement(s) 
elif expression: 
    statement(s) 
... 
else: 
    statement(s) 
     

The elif and else clauses are optional. Note that, unlike some languages, Python does not have a "switch" statement. Use if, elif, and else for all conditional processing.

Example python if code:

if x < 0: print('x is negative') 
elif x % 2: print('x is positive and odd') 
else: print('x is even and non-negative') 

When there is just a single simple statement, as here, it can follow the : on the same logical line as the header but when there are multiple statements in a clause (i.e., the clause controls a block of statements), place the statements on separate logical lines indented rightward from the header line. The block terminates when the indentation returns to that of the clause header (or further left from there).

if x < 0: 
    print('x is negative') 
    print('this will also be printed if
x<0 is true') 
elif x % 2: 
    print('x is positive and odd') 
    print('this will also be printed if x%2
is true') 
else: 
    print('x is even and non-negative') 
    

When the if clause's condition evaluates as true, the statements after the if clause execute, then the entire if statement ends. Otherwise, Python evaluates each elif clause's condition, in order. The statements after the first elif clause whose condition evaluates as true, if any, execute, and the entire if statement ends. Otherwise, when an else clause exists it is executed, and then the statements after the entire if construct execute.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Python )

Latest Articles (in Python)