Python Data Science Toolbox (Part 1)
Run the hidden code cell below to import the data used in this course.
1 hidden cell
Take Notes
nested functions, local scope, global, builtin
enclosing function; one whereby python searches for a value in the outer function if not found in inner function nested. global n: when defining a value to be global
nesting functions within functions: One reason why you'd like to do this is to avoid writing out the same computations within functions repeatedly. There's nothing new about defining nested functions: you simply define it as you would a regular function with def and embed it inside another function!
closure: This means that the nested or inner function remembers the state of its enclosing scope when called. Thus, anything defined locally in the enclosing scope is available to the inner function even when the outer function has finished execution.
# nested function, enclosing function
def outer():
"""prints the value of n"""
n=1
def inner():
nonlocal n
n=2
print(n)
inner()
print(n)
#closure
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return(inner_echo)
# Call echo: twice
twice = echo(2)
# Call echo: thrice
thrice = echo(3)
# Call twice() and thrice() then print
print(twice('hello'), thrice('hello'))
"""The keyword nonlocal and nested functions"""
# Define echo_shout()
def echo_shout(word):
"""Change the value of a nonlocal variable"""
# Concatenate word with itself: echo_word
echo_word = word * 2
# Print echo_word
print(echo_word)
# Define inner function shout()
def shout():
"""Alter a variable in the enclosing scope"""
# Use echo_word in nonlocal scope
nonlocal echo_word
# Change echo_word to echo_word concatenated with '!!!'
echo_word = echo_word + "!!!"
# Call function shout()
shout()
# Print echo_word
print(echo_word)
# Call function echo_shout() with argument 'hello'
echo_shout("hello")
Explore Datasets
Use the DataFrame imported in the first cell to explore the data and practice your skills!
- Write a function that takes a timestamp (see column
timestamp_ms) and returns the text of any tweet published at that timestamp. Additionally, make it so that users can pass column names as flexible arguments (*args) so that the function can print out any other columns users want to see. - In a
filter()call, write a lambda function to return tweets created on a Tuesday. Tip: look at the first three characters of thecreated_atcolumn. - Make sure to add error handling on the functions you've created!