# 5.1 Functions
Run to view results
# A. Write a function that accepts one parameter, name
# The function should print the message "Hello, _____." filling in the blank with the name
def intro(name):
return f'Hello, {name}.'
intro("Harry Potter")
Run to view results
# B. Write a function that accepts one parameter, a number
# The function should return true or false depending on whether the number is even
def is_even(number):
return number % 2 == 0
print(is_even(81))
print(is_even(88))
Run to view results
# C. Write a function that accepts one parameter, a list
# The function should return the sum total of all numbers in the list, using a loop
def total_of_list(numbers):
return sum(numbers)
total_of_list([1,2,3,4,5])
Run to view results
# D. Write a function that accepts one parameter, a dictionary
# The function should print the message "Introducing ______ ______, ________!"
# Fill in the blanks with the "first_name", "last_name", and "title" properties of the dictionary
def intro_dict(dict):
return print(f'Introducing {dict["first_name"]} {dict["last_name"]}, {dict["title"]}!')
intro_dict({"first_name":"Harry", "last_name":"Potter", "title":"Wizard"})
Run to view results
# 5.2 Problem-Solving Functions
Run to view results
# A. Find the longest string in a given list of strings
def longest_string(string):
longest_len = 0
longest_word = ''
for i in string:
if len(i) > longest_len:
longest_len = len(i)
longest_word = i
return longest_word
longest_string(['life', 'is', 'fantastic'])
Run to view results
# B. Determine whether a given list contains a given value
def contains_value(list1, value):
return value in list1
print(contains_value(['a', 'orange', 2], 2))
print(contains_value(['a', 'orange', 2], 3))
print(contains_value(['a', 'orange', 2], 'blue'))
print(contains_value(['a', 'orange', 2], 'a'))
Run to view results
# C. Count how many times a given string contains a given letter
def count_letter_hard(string,letter):
counter = 0
for i in string:
if letter == i:
counter +=1
return counter
def count_letter(string, letter):
return string.count(letter)
print(count_letter_hard('Harry Potter', 'r'))
print(count_letter('Harry Potter', 'r'))
Run to view results
# D. Find the most common letter in a given string, and use the previous function in your answer
name = 'Harry Potter'
# oops forgot to use the function...
# create a dict for each letter, then iterate if found again
dict = {}
for i in name:
if i in dict.keys():
dict[i] += 1
else:
dict[i] = 1
#print(dict)
#TRY AGAIN ...
#print(set(name))
counter = 0
most_letters = ''
for letter in set(name):
if count_letter(name,letter) > counter:
counter = count_letter(name,letter)
most_letters = letter
print(f'Most frequent letter in "{name}" is "{most_letters}"')
Run to view results
# E. Find the area of a triangle given its length and height as parameters
def area_triangle(l,h):
return 0.5*l*h
area_triangle(5,3)
Run to view results