Conditional (If-Else) Statements in Python

(2 votes, average 4.50 out of 5)

Below is a quick example of how to use an if statement in python:

 

1
2
3
4
5
if x==3:
	print "We are inside an if statement"
	x = x + 1
print "we are no longer in an if statement"

 

Note that unlike most languages, no parentheses are needed, although including parentheses does not violate python syntax.  Anything indented after the if statement is included in the execution if the if statement evaluates to true.  The scope is closed once indentation returns to the indent location of the original, matching if statement.  Below is an example of an if, else if, else clause in python:

1
2
3
4
5
6
7
8
if x==3:
	print "we are inside the if statement"
elif x==2:
	print "we are inside the else-if statement"
else:
	print "we are inside the else statement"
#end conditional block
print "we are outside of the if-else block"

 

Important notes about this functionality in python:

  • Instead of a traditional "else if" statement, python uses the shorter keyword elif.  
  • Any elif or else keyword must be in line with a corresponding if statement.  If either of these keywords are not matched in indentation to an existing if statement, python will throw an error and exit.
  • Variables declared in an if statement can be used elsewhere in the code.  In other words, there is no scope for variables declared in an if block.  Convenient, but use wisely!
Partner Links:
Last Updated on Monday, 28 June 2010 14:08  
Related Articles

» Using Awk to Print Select Output

Awk is a very powerful utility, but its syntax is less than intuitive to a beginner. Here are a few common but very powerful things you can do with awk:1234567891011121314151617# print line 2 of the fileawk 'NR == 2' myFile.txt # print column 2 of the fileawk '{print $2}' myFile.txt # add up column 2awk '{s += $4} END {print s}' # print all the lines with more than 80 columnsawk 'length($0) > 80' myFile.txt # print the number of lines in the fileawk 'END { print NR }'...

» Comments in Python

Line CommentsLine comments in Python are very simple.  The # character denotes that everything afterward on that line is a comment.  12#here is a whole-line comment for some codex = 3 #this comments code on the current line Block CommentsUnfortunately, there is no specific syntax for block comments in python.  To comment a block of code, you must simply place a # before every line in the block of code you wish to comment.  Many Python IDE's, however, provide a simple way...

» How to Print in Python

Printing in Python is as simple as typing print followed by the string you wish to print.  You do not need to import any libraries.12>>> print "Hello World"Hello World You can also print the value of an integer or list simply by print 123456>>> x = [1, 2, 3]>>> print x[1, 2, 3]>>> y = 2>>> print y2If, however, you want to print a string AND some integer (or list), you need to cast to string.123>>> x = 42>>> print "The meaning...