//Program
x = 5
if x < 10:
print('Smaller')
if x > 20:
print('Bigger')
print('Finis')
//Outputs
Smaller
Finis
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 or Yes / No
- Comparison operators look at variables but do not change the variables
Python | Meaning |
< | Less than |
<= | Less than or Equal to |
== | Equal to |
>= | Greater than or Equal to |
> | Greater than |
!= | Not equal |
Indentation
- Increase indent after an if statement or for 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 blcok
- 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(4 spaces)!
- Atom automatically uses spaces for files with “.py” extension (nice!)
- Most text editors can turn tabs into spaces - make sure to enable this feature
- NotePad++ : Settings → Preferences → Language Menu/Tab Settings
- TextWragler : TextWrangler → Preferences → Editor Defaults
- Python cares a lot about how far a line is intended. If you mix tabs and spaces, you may get “indentation errors” even if everything looks fine
Two-way Decisions
- Sometimes we want to do one thing if a logical expression is true and something else if the expression is false
- It is like a fork in the road - we must choose one or the other path but not both
Multi-way Decision
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 = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print('First', istr)
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print('Second', istr)
Sample try/except
rawstr = input('Enter a number:')
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0 :
print('Nice work')
else:
print('Not a number')
Summary
- Comparison operator
- Indentation
- One-way Decisions
- Two-way decisions: if: and else:
- Nested Decisions
- Multi-way decisions using elif
- try/except to compensate for errors