A6 - Python Functions
Reference for this assignment
Python Manual - Pages 11
The section on f-strings on page 7 may also be useful.
Additional Information
A function is a subprogram that receives one or more pieces of information as input via it's arguments, and returns one value as output. Once a function is defined, we can call it as often as needed. A function doesn't do anything until it's called.
Examples
def remove_vowels(input_string):
# Input: any string
# Output: the input string with vowels removed
output_string = ""
for char in input_string:
if not char.lower() in ['a', 'e', 'i', 'o', 'u']:
output_string += char
return output_string
def is_all_even(nums):
# Input: a list of numbers
# Output: True if all numbers in the list are even, otherwise False
for num in nums:
if num % 2 == 1:
return False
# If we've reached here without returning False, it means
# all numbers are even
return True
# Test our `remove_vowels` function with two examples
print(remove_vowels("banana"))
print(remove_vowels("Eastview Secondary School!"))
# Test our `is_all_even` function with two examples:
# one returning True, one returning False
print(is_all_even([2, 8, 10, 14]))
print(is_all_even([1, 2, 4, 12]))
# A function that returns a Boolean value can be used in an `if` statement like this:
if is_all_even([1, 2, 3]):
print("Yup, all even numbers.")
else:
print("Nope, at least one odd number in that list.")
This code produces the following output:
Learning Goals
- Create and call functions that accept one or more arguments and return a value
Suggested Task
Create two functions such that:
- Each one accepts at least one argument and returns a value
- Use different data types for arguments and returns values, such as strings, lists, numbers, booleans
Call each function twice.
Some function ideas - use one of these ideas if you'd like, then try to come up with at least one of your own ideas:
- Input is a list of numbers and a single number; output is how many times the single number appears in the list
- Input is a string; output is
Trueif there are at least ten words (the split string method might be useful here) - Input is a string; output is the length of the longest word
- Input is a list; output is a list with all numbers of the input list squared
- Input is two lists; output is a list containing only the values that are in both input lists (this one would be a little tricky!)