for n in [2, 4, 6, 8]:
print(n * 5)
tips = [5, 2, 3, 8, 9, 0, 2, 1]
for i in tips:
print('ignorning i!')
def modify_verb(verbs):
for verb in verbs:
print(verb + 'ing')
modify_verb(['eat', 'run'])
modify_verb(['cry', 'drink', 'sleep'])
# Ignore this code, just run it
from datascience import *
table = Table.read_table('data/titanic.csv').select(['Name', 'Age', 'Sex', 'Fare', 'Survived'])
titanic_fares = list(table.column('Fare'))[:10]
table
First let's implement count_above
using a while loop. We'll call this function count_above_while
.
def count_above_while(fares, threshold):
count = 0
i = 0
while i < len(fares):
if fares[i] > threshold:
count += 1
i += 1
return count
# Evaluates to 4, since 4 nums are >3
count_above_while([1, 2, 5, 8, 7, 9], 3)
# Evaluates to 0, since 0 nums are >10
count_above_while([4, 8, 2, 1], 10)
Let's now implement count_above
using a for loop, to show how much easier it is. We'll call this function count_above_for
.
def count_above_for(fares, threshold):
count = 0
for fare in fares:
if fare > threshold:
count += 1
return count
# Evaluates to 4, since 4 nums are >3
count_above_for([1, 2, 5, 8, 7, 9], 3)
# Evaluates to 0, since 0 nums are >10
count_above_for([4, 8, 2, 1], 10)
for char in 'university':
print(char.upper())
for j in range(10):
print(j)
range(10)
list(range(10))
list(range(3, 8))
# 1 + 2 + 3 + 4 + 5
# + 6 + 7 + 8 + 9 + 10
total = 0
for n in range(1, 11):
total += n
total
# 3 + 5 + 7 + 9
total = 0
for n in range(3, 11, 2):
total += n
total
for j in range(10, 0, -3):
print(j)
print('happy new year!')
# Remember, the + symbol
# concatenates two lists
[1, 2, 3] + [4, 5, 6]
def list_add(a, b):
# Checking to make sure that
# a and b have the same length
if len(a) != len(b):
return None
output = []
for i in range(len(a)):
output.append(a[i] + b[i])
return output
list_add([1, 2, 3], [4, 5, 6])
school = 'The University of California'
for p in range(__, 18, __):
print(school[p])
def sum_squares_for(values):
total = 0
for v in values:
total += v**2
return total
# 3^2 + 4^2 + 5^2
sum_squares_for([3, 4, 5])
def sum_squares_while(values):
total = 0
j = 0
while j < len(values):
total += values[j]**2
j += 1
return total
# 3^2 + 4^2 + 5^2
sum_squares_while([3, 4, 5])