Engineering #20: *for thing in things* needs to iterate! and a thanks to methods
And Lago-alba by Gerardo Dottori (1942)
You come across the following code. What errors does it raise for the given examples and what exactly do the error messages mean?
def find_first_nonzero_among(numbers):
for n in numbers:
if n != 0:
return n
find_first_nonzero_among(0, 0, 1, 0, 2, 0)
find_first_nonzero_among(1)
Ahh, not sure… Okay, I looked at the answer: it’s passing raw integers rather than a list. Because we’re doing for n in numbers, we have to iterate over one thing of iterables. So this is fine:
find_first_nonzero_among([1])
It’s a list of one, but still a list; we can go “for 1 in [1]” on it. Link to Launch School exercise.
I thought this was a good example of how much stuff methods (like .title) can simplify; solution one:
def capitalize_words(string):
return string.title()
string = 'capitalize the first letter in each word & fast'
result = capitalize_words(string)
print(result) # Capitalize The First Letter In Each Word & Fast
Solution two, without .title:
def capitalize_words(string):
words = string.split(' ')
capitalized_words = []
for word in words:
capitalized_words.append(word.capitalize())
return ' '.join(capitalized_words)
string = 'capitalize the first letter in each word & fast'
result = capitalize_words(string)
print(result) # Capitalize The First Letter In Each Word & Fast
Link to Launch School exercise.