# For Loops¶

Create a for loop

In [1]:
for x in [1,2,3]:
print x

1
2
3


Create a for loop with range

In [2]:
for x in range(10):
print x

0
1
2
3
4
5
6
7
8
9


Create a for loop with multiple values

In [3]:
for x,y in [[1,4],[2,5],[3,6]]:
print x * y

4
10
18


Capture the all the results of a for loop

In [4]:
results = []
for x in [10,3,17]:
squared = x ** 2
results.append(squared)

print results

[100, 9, 289]


### Exercise¶

#### 1. Create a function that receives a list of numbers as an input, adds 1 to each number and returns the results as a list¶

In [18]:
def add_to_list(input_list):
results = []
for each in input_list:
return results


[11, 16, 8]
[21, 9, 20]

In [6]:
print range(3)
print range(2,5)
print range(1,10,2)

[0, 1, 2]
[2, 3, 4]
[1, 3, 5, 7, 9]

In [7]:
print add_to_list(range(0,100,5))

[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]


#### 2. Update your temperature conversion function from the Python Fundamentals exercise to accept a list of Celsius temperatures and return a list of Fahrenheit temperatures¶

In [8]:
def convert_temp_list(temp_list):
results = []
for temp in temp_list:
new_temp = temp * 9.0 / 5.0 + 32.0
results.append(new_temp)
return results

In [9]:
def convert_temp(degrees_c):
degrees_f = degrees_c * 9.0 / 5.0 + 32.0
return degrees_f

def convert_temp_list2(temp_list):
results = []
for temp in temp_list:
results.append(convert_temp(temp))
return results

In [10]:
convert_temp_list([0,30,100])

Out[10]:
[32.0, 86.0, 212.0]
In [11]:
convert_temp_list2([0,30,100])

Out[11]:
[32.0, 86.0, 212.0]

In [12]:
def convert_temp_check(degrees_c):
if (type(degrees_c) == int) | (type(degrees_c) == float):
degrees_f = degrees_c * 9.0 / 5 + 32
return degrees_f
else:
return "Error. {} is a non-numeric value.".format(degrees_c)

def convert_temp_list3(temp_list):
results = []
for temp in temp_list:
results.append(convert_temp_check(temp))
return results

In [13]:
convert_temp_list3([0,30,100,'cat'])

Out[13]:
[32.0, 86.0, 212.0, 'Error. cat is a non-numeric value.']
In [14]:
def convert_temp_list4(temp_list):
results = []
for degrees_c in temp_list:
if (type(degrees_c) == int) | (type(degrees_c) == float):
degrees_f = degrees_c * 9.0 / 5 + 32
results.append(degrees_f)
else:
results.append("Error. {} is a non-numeric value.".format(degrees_c))
return results

In [15]:
convert_temp_list4([0,30,100,'cat'])

Out[15]:
[32.0, 86.0, 212.0, 'Error. cat is a non-numeric value.']
In [ ]: