Named Arguments Ans.

4.6_more_on_arguments_ans

Q1) Write any function you want that does anything you want. Call it once without named arguments and once with them.

Here is a function that I wrote that tells you the vowels vs. consonants of a word that you feed it.

In [7]:
def vowel_percent(word):
# start at no vowels
vowel_count = 0
# define what vowels are
vowels = ["A", "E", "I", "O", "U"]
# iterate through the letters
for letter in word:
# are they in vowels?
if letter in vowels:
# count them
vowel_count += 1
# as a percent
return vowel_count/len(word)


Some of you reading this are no doubt wondering "what about 'Y'?". We could easily add the letter 'Y' to the list. But there is a more refined approach. Let's make counting 'Y' an optional argument. If the user wants to use it they can. If not? No big deal. We can even set a default behavior.

In [6]:
def vowel_percent(word, count_y = True):
# start at no vowels
vowel_count = 0
# define what vowels are
vowels = ["A", "E", "I", "O", "U"]
# counting y?
if count_y == True:
vowels.append("Y")
# iterate through the letters
for letter in word:
# are they in vowels?
if letter in vowels:
# count them
vowel_count += 1
# as a percent
return vowel_count/len(word)

# call the function without counting the "y"
print(vowel_percent("YAMS", count_y = False))
# call with the default behavior
print(vowel_percent("YAMS"))

0.25
0.5


Q2) Write a function called "repeat_yourself". The function should be able to take an argument called "name" and an argument called "repititions". The function should print out "names" as many times as the number in "repititions" (each repeat on its own line). If the user doesn't enter anything, it should print out the word "yourself" ten times.

In [6]:
# define repeat_yourself that acts on 'name' and 'repititions'
# and defaults to "yourself" and 10 as defaults

def repeat_yourself(name = "yourself", repititions = 10):
# use range to iterate up to repititions
for number in range(repititions):
# print name each time
print(name)

repeat_yourself("Seattle", 5)
repeat_yourself()

Seattle
Seattle
Seattle
Seattle
Seattle
yourself
yourself
yourself
yourself
yourself
yourself
yourself
yourself
yourself
yourself