Programming‎ > ‎Python‎ > ‎

03-Conditional


Comparison Operators


• Boolean expressions ask a question and produce a Yes or
No result which we use to control program flow
• Boolean expressions using comparison operators evaluate to - True / False - Yes / No
• Comparison operators look at variables but do not change the variables

Python Meaning
< Less than
<= Less than or Equal
== Equal to
>= Greater than or Equal
> Greater than
!= Not equal


x = 5

if x == 5 :
print 'Equals 5'
if x > 4 :
print 'Greater than 4'

if x >= 5 :
print 'Greater than or Equals 5'

if x < 6 : print 'Less than 6'
if x <= 5 :
print 'Less than or Equals 5'

if x != 6 :
print 'Not equal 6'


Indentation


• Increase indent indent after an if statement or for statement (after : )
• Maintain indent to indicate the scope of the block (which lines are affected by the if/for)
• Reduce indent back to the level of the if statement or for statement to indicate the end of the block
• Blank lines are ignored - they do not affect indentation
• Comments on a line by themselves are ignored with regard to indentation


Warning: Turn Off Tabs


• Most text editors can turn tabs into spaces - make sure to enable this feature
> NotePad++: Settings -> Preferences -> Language Menu/Tab Settings
> TextWrangler: TextWrangler -> Preferences -> Editor Defaults

• Python cares a *lot* about how far a line is indented. If you mix tabs and spaces, you may get “indentation errors” even if everything looks fine


Two way using else:


x = 4
if x > 2 :
    print 'Bigger'
else :
    print 'Smaller'

print 'All done'


Multi-way


if x < 2 :
    print 'small'
elif x < 10 :
    print 'Medium'
else :
    print 'LARGE'

print 'All done'


The try/except Structure


• You surround a dangerous section of code with try and except
• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section


astr = 'Bob'
try:
    print 'Hello'
    istr = int(astr)
    print 'There'
except:
    istr = -1

print 'Done', istr




Comments