For Loops

© QuantSprout

Create a for loop

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

Create a for loop with range

for x in range(10):
    print x
0
1
2
3
4
5
6
7
8
9

Create a for loop with multiple values

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

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

def add_to_list(input_list):
    results = []
    for each in input_list:    
        addone = each + 1
        results.append(addone)
    return results

print add_to_list([10,15,7])
print add_to_list([20,8,19])
[11, 16, 8]
[21, 9, 20]
print range(3)
print range(2,5)
print range(1,10,2)
[0, 1, 2]
[2, 3, 4]
[1, 3, 5, 7, 9]
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

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
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
convert_temp_list([0,30,100])
[32.0, 86.0, 212.0]
convert_temp_list2([0,30,100])
[32.0, 86.0, 212.0]

Bonus: Add error handling to your temperature conversion function.

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
convert_temp_list3([0,30,100,'cat'])
[32.0, 86.0, 212.0, 'Error. cat is a non-numeric value.']
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
convert_temp_list4([0,30,100,'cat'])
[32.0, 86.0, 212.0, 'Error. cat is a non-numeric value.']