Python Functions Lab
Intro
Time to practice some Python by writing functions that solve the four challenges below.
To test your functions, be sure to call each function at least once and print the returned value.
Set Up
Create a new Python repl on repl.it
Challenges
-
Write a function named
sum_tothat accepts a single integer,n, and returns the sum of the integers from 1 ton.For example:
sum_to(6) # returns 21 sum_to(10) # returns 55
-
Write a function named
largestthat takes a list of numbers as an argument and returns the largest number in that list.For example:
largest([1, 2, 3, 4, 0]) # returns 4 largest([10, 4, 2, 231, 91, 54]) # returns 231
-
Write a function named
occurancesthat takes two string arguments as input and counts the number of occurances of the second string inside the first string.For example:
occurances('fleep floop', 'e') # returns 2 occurances('fleep floop', 'p') # returns 2 occurances('fleep floop', 'ee') # returns 1 occurances('fleep floop', 'fe') # returns 0
-
Write a function named
productthat takes an arbitrary number of numbers, multiplies them all together, and returns the product.
(HINT: Review your notes on*args).For example:
product(-1, 4) # returns -4 product(2, 5, 5) # returns 50 product(4, 0.5, 5) # returns 10.0
Solution
Here's some possible solutions to these (don't peek unless you absolutely have to!)