In [ ]:
breakfast = ["sausage", "eggs", "bacon", "spam"]
for item in breakfast:
print(item)
Write then a for which loop determines the squares of the odd
integers up to 10. Use the range() function.
In [ ]:
squares = []
for i in range(1, 10, 2):
squares.append(i**2)
print(squares)
In [ ]:
fruits = {'banana' : 5, 'strawberry' : 7, 'pineapple' : 3}
for fruit in fruits:
print(fruit)
Next, write a loop that sums up the prices.
In [ ]:
sum = 0
for price in fruits.values():
sum += price
print(sum)
In [ ]:
f = [0, 1]
while True:
new = f[-1] + f[-2]
if new > 100:
break
f.append(new)
print(f)
In [ ]:
number = 7
if number < 0:
print("Negative")
elif number == 0:
print("Zero")
elif number in [3, 5, 7, 11, 17]:
print("Prime")
In [ ]:
xys = [[2, 3], [0, -1], [4, -2], [1, 6]]
tmp = []
for x, y in xys:
tmp.append([y,x])
tmp.sort()
for i, (y,x) in enumerate(tmp):
xys[i] = [x,y]
print(xys)
Next, create a new list containing only the sorted y values.
In [ ]:
ys = []
for x, y in xys:
ys.append(y)
print(ys)
Finally, create a new list consisting of sums the (x,y) pairs where both x and y are positive.
In [ ]:
sums = []
for x, y in xys:
if x > 0 and y > 0:
sums.append(x + y)
print(sums)
List comprehension is often convenient in this kind of situations:
In [ ]:
xys = [[2, 3], [0, -1], [4, -2], [1, 6]]
tmp = [[y, x] for x, y in xys]
tmp.sort()
xys = [[x, y] for y, x in tmp]
# One liner is possible but not very readable anymore:
xys = [[x, y] for y, x in sorted([[ytmp, xtmp] for xtmp, ytmp in xys])]
# Summing positives with one liner is ok:
sums = [x+y for x,y in xys if x > 0 and y > 0]
This is a classic job interview question. Depending on the interviewer or interviewee it can filter out up to 95% of the interviewees for a position. The task is not difficult but it's easy to make simple mistakes.
If a number is divisible by 3, instead of the number print "Fizz", if a number is divisible by 5, print "Buzz" and if the number is divisible by both 3 and 5, print "FizzBuzz".
In [8]:
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
print(number)
Food for thought: How do people commonly fail this test and why?
In [ ]:
In [10]:
import random
while True:
value = random.random()
if value < 0.1:
break
print("done")
In [12]:
temperatures_celsius = [0, -15, 20.15, 13.3, -5.2]
temperatures_kelvin = [c+273.15 for c in temperatures_celsius]