欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

10-Python-Data-Science-Toolbox(Part 1)

程序员文章站 2024-01-30 16:35:28
...

1. Writing your own functions

1.1 User-defined functions

1.2 Strings in Python

In the video, you learned of another standard Python datatype, strings. Recall that these represent textual data. To assign the string ‘DataCamp’ to a variable company, you execute:
company = 'DataCamp'

You’ve also learned to use the operations + and * with strings. Unlike with numeric types such as ints and floats, the + operator concatenates strings together, while the * concatenates multiple copies of a string together. In this exercise, you will use the + and * operations on strings to answer the question below. Execute the following code in the shell:

object1 = "data" + "analysis" + "visualization"
object2 = 1 * 3
object3 = "1" * 3

1.3 Recapping built-in functions

1.4 Write a simple function

1.5 Single-parameter functions

1.6 Functions that return single values

1.7 Functions with multiple parameters

1.8 A brief introduction to tuples

1.9 Functions that return multiple values

1.10 Bringing it all together

1.11 Bringing it all together (1)

1.12 Bringing it all together (2)

1.13 Congratulations

2. Default arguments, variable-length arguments and scope

2.1 Scope and user-defined functions

2.2 Pop quiz on understanding scope

2.3 The keyword global

2.4 Python’s built-in scope

2.5 Nested functions

2.6 Nested Function I

2.7 Nested Function II

2.8 The keyword nonlocal and nested functions

2.9 Default and flexible arguments

2.10 Functions with one default arguments

2.11 Functions with multiple default arguments

2.12 Functions with variable-length arguments (*args)

2.13 Functions with variable-length keyword arguments (*kwargs)

2.14 Bringing it all together

2.15 Bringing it all together (1)

2.16 Bringing it all together (2)

3. Lambda functions and error-handling

3.1 Lambda functions

3.2 Pop quiz on lambda functions

In this exercise, you will practice writing a simple lambda function and calling this function. Recall what you know about lambda functions and answer the following questions:

  • How would you write a lambda function add_bangs that adds three exclamation points '!!!'to the end of a string a?
  • How would you call add_bangs with the argument 'hello'?

You may use the IPython shell to test your code.

□ \square The lambda function definition is: add_bangs = (a + '!!!'), and the function call is: add_bangs('hello').
■ \blacksquare The lambda function definition is: add_bangs = (lambda a: a + '!!!'), and the function call is: add_bangs('hello').
□ \square The lambda function definition is: (lambda a: a + '!!!') = add_bangs, and the function call is: add_bangs('hello').

3.3 Writing a lambda function you already know

Some function definitions are simple enough that they can be converted to a lambda function. By doing this, you write less lines of code, which is pretty awesome and will come in handy, especially when you’re writing and maintaining big programs. In this exercise, you will use what you know about lambda functions to convert a function that does a simple task into a lambda function. Take a look at this function definition:

def echo_word(word1, echo):
    """Concatenate echo copies of word1."""
    words = word1 * echo
    return words

The function echo_word takes 2 parameters: a string value, word1 and an integer value, echo. It returns a string that is a concatenation of echo copies of word1. Your task is to convert this simple function into a lambda function.

Instruction

  • Define the lambda function echo_word using the variables word1 and echo. Replicate what the original function definition for echo_word() does above.
  • Call echo_word() with the string argument 'hey' and the value 5, in that order. Assign the call to result.
# Define echo_word as a lambda function: 
echo_wordecho_word = (lambda word1,echo: word1*echo)

# Call echo_word: result
result = echo_word('hey', 5)

# Print result
print(result)

3.4 Map() and lambda functions

So far, you’ve used lambda functions to write short, simple functions as well as to redefine functions with simple functionality. The best use case for lambda functions, however, are for when you want these simple functionalities to be anonymously embedded within larger expressions. What that means is that the functionality is not stored in the environment, unlike a function defined with def. To understand this idea better, you will use a lambda function in the context of the map() function.

Recall from the video that map() applies a function over an object, such as a list. Here, you can use lambda functions to define the function that map() will use to process the object. For example:

nums = [2, 4, 6, 8, 10]
result = map(lambda a: a ** 2, nums)

You can see here that a lambda function, which raises a value a to the power of 2, is passed to map() alongside a list of numbers, nums. The map object that results from the call to map() is stored in result. You will now practice the use of lambda functions with map(). For this exercise, you will map the functionality of the add_bangs() function you defined in previous exercises over a list of strings.

Instruction

  • In the map() call, pass a lambda function that concatenates the string '!!!' to a string item; also pass the list of strings, spells. Assign the resulting map object to shout_spells.
  • Convert shout_spells to a list and print out the list.
# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]

# Use map() to apply a lambda function over spells: shout_spells
shout_spells = map(lambda item: item + '!!!', spells)

# Convert shout_spells to a list: shout_spells_list
shout_spells_list = list(shout_spells)

# Print the result
print(shout_spells_list)

3.5 Filter() and lambda functions

In the previous exercise, you used lambda functions to anonymously embed an operation within map(). You will practice this again in this exercise by using a lambda function with filter(), which may be new to you! The function filter() offers a way to filter out elements from a list that don’t satisfy certain criteria.

Your goal in this exercise is to use filter() to create, from an input list of strings, a new list that contains only strings that have more than 6 characters.

Instruction

  • In the filter() call, pass a lambda function and the list of strings, fellowship. The lambda function should check if the number of characters in a string member is greater than 6; use the len() function to do this.
    Assign the resulting filter object to result.
  • Convert result to a list and print out the list.
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn',
              'boromir', 'legolas', 'gimli', 'gandalf']

# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda member: len(member) > 6, fellowship)

# Convert result to a list: result_list
result_list = list(result)

# Print result_list
print(result_list)

3.6 Reduce() and lambda functions

3.7 Introduction to error handling

3.8 Pop quiz about errors

3.9 Error handling with try-except

3.10 Error handling with try-except

3.11 Error handling by raising an error

3.12 Bringing it all together

3.13 Bringing it all together (1)

3.14 Bringing it all together (2)

3.15 Bringing it all together (3)

3.16 Bringing it all together: testing your error handling skills

3.17 Congratulations!