# Loops¶

Ha Khanh Nguyen (hknguyen)

## 1. Smallest Even Problem¶

• You are given 3 numbers x, y, z. Find the smallest even number among them and store it in a variable called result. If none of them is even, then result = -1. Note that they are all positive numbers.
• Now, let's say instead of 3 numbers, you are given 10 numbers! Well, the logic is the same, right? But we will have to write 10 if statements, each for each number. That's tedious but doable.
• There must be a way for us to tell Python to repeat this statement for all the numbers provided!
• That is the idea of loops in programming!

## 2. for Loops¶

• for loops are for iterating over a list of objects (or a collection of objects or an iterater).
• The standard syntax for a for loop is:
• Example:
• Let's do something more interesting than printing out the number:
• See video for the step by step walkthrough of the code segment above.

### 2.1 Use for loop for the smallest even problem¶

• Let's say 10 numbers are given to us in a list named nums.
• Similarly, we can use the same logic above for the other variations of this problem: smallest odd, largest even, largest odd.

### 2.2 for loop with strings¶

• for loop works very well with string!
• Example:
• You're a given a string s containing a mathematical expression with 2 operands and an addition. For example, s = '3+2.5'. There is no space between the number (operand) and the operator. Write a Python program to evaluate the expression and store the result in a variable named result.
• We can split s by +!

### 2.3 range() function¶

• The range() function in Python returns an iterator that yields a sequence of evenly spaced integers.
• What does this mean?
• The syntax of the range() function is: range(start, end, step)
• Sometimes, we don't want to iterate over a list of objects in the "default" way, instead we want to iterate the index of the list and access the elements by the index:

## 3. while Loops¶

• A while loop specifies a condition and a block of code that is to be executed until the condition evaluates to False or the loop is explicitly ended with break.
• The use of the break keyword is extremely useful in cases like this:
• To fix this error: