Path: blob/master/april_18/lessons/lesson-02/code/python-foundations/solution-code/python-functions-solutions.ipynb
1907 views
Kernel: Python 2
Practice Python Functions
_Author: Ryan Dunlap (San Francisco)
Resources: Potentially Helpful Functions
Nowadays, most of the string
module's components are already built into Python. However, it still has several constant values that can be useful, including:
In [1]:
Out[1]:
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1) Write a function that takes the length of a side of a square as an argument and returns the area of the square.
In [2]:
We can use the assert
statement to validate if our function's output is correct.
In [3]:
In [4]:
Out[4]:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-4-e5f18b8a7bbc> in <module>()
1 # If our assert statement is false, assert will return an error.
2
----> 3 assert area_square(5) == 21
AssertionError:
2) Write a function that takes the height and width of a triangle and returns the area.
In [4]:
In [5]:
3) Write a function that takes a string as an argument and returns a tuple consisting of two elements:
A list of all of the characters in the string.
A count of the number of characters in the string.
In [6]:
In [16]:
Out[16]:
(['R', 'y', 'a', 'n', ' ', 'R', 'o', 'c', 'k', 's'], 10)
4) Write a function that takes two integers, passed as strings, and returns the sum, difference, and product as a tuple (with all values as integers).
In [17]:
In [20]:
Out[20]:
(7, 3, 10)
5) Write a function that takes a list as the argument and returns a tuple consisting of two elements:
A list with the items in reverse order.
A list of the items in the original list that have an odd index.
In [10]:
In [21]:
Out[21]:
([5, 4, 3, 2, 1], [2, 4])
Challenge: Write a function that returns the score for a word. A word's score is the sum of the scores of its letters. Each letter's score is equal to its position in the alphabet.
So, for example:
A = 1, B = 2, C = 3, D = 4, E = 5
abe = 8 = (1 + 2 + 5)
Hint: The string library has a property ascii_lowercase
that can save some typing here.
In [22]:
In [23]:
In [ ]: