# Loops and conditions¶

## if ... else¶

``````if expression:
statement(s)

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

if expression1:
statement(s)
elif expression2:
statement(s)
else:
statement(s)
``````

### Single line if else.¶

`'Yes' if fruit == 'Apple' else 'No'`
`a = 10 if fruit == 'Apple' else 20`
`if a == 20: print(a)`

## For loop¶

``````for something in somethings:
do something
``````

### Single Line for:¶

`doubled = [thing for thing in list_of_things]`
`images = [image.id for image in ec2.instances.all()]`

### Iterating two lists using `for` loop using `zip`:¶

zip Iterate two lists in parallel

``````a = ['abc', 'xyz']
b = ['123' '456']
for x,y in zip(a, b):
print(x,y)
...
('abc', '123')
('xzy', '456')
``````

### Iterate over two lists and their indices using enumerate together with zip¶

``````alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for i, (a, b) in enumerate(zip(alist, blist)):
print i, a, b

0 a1 b1
1 a2 b2
2 a3 b3
``````

## While Loop¶

``````while true:
do something
``````

### While with 2 variables¶

``````while len(list1) and len(list2):
if list1 < list2:
``````

## Break, continue and pass¶

`break` : breaks the ‘for’ or ‘while’ loop.
`continue`: continues with the next iteration of the loop.
`pass`: It does nothin. It is used when a statement is required syntactically but requires no action.

``````>>> raise ValueError('Hi there')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Hi there
``````

## Try, Except, Else and Finally¶

• If an error (exception) is encountered, a try block code execution is stopped and transferred down to the except block.
• In addition to using an except block after the try block, you can also use the finally block.
• The code in the finally block will be executed regardless of whether an exception occurs.

``````>>> try:
...    print("helo world")
... except:
...    print("here goes the error”
... finally:
print(all done)
``````
If exception type is given after the except keyword, and the the exception code matches, then the except clause is executed.

``````>>> try:
...    print('if variable VAR1 id defined')
...    VAR1
... except NameError:
...    print('variable VAR1 is not defined')
...
if variable VAR1 id defined
variable VAR1 is not defined
``````

The `try` ... `except` statement has an optional `else` clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the `try` clause does not raise an exception. Eg.

``````for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else: