avatarFarzad Mahmoodinobar

Summary

This web content provides a comprehensive tutorial on Python's advanced functions, including scope, nested functions, exception handling, and lambda functions, with twelve practice questions to aid data scientists in their learning.

Abstract

The post is designed to enhance the Python skills of data scientists, particularly those relevant to a role at Amazon. It builds upon basic Python topics by delving into advanced concepts such as scope, nested functions, exception handling, and lambda functions. Each topic is accompanied by a series of practice questions to facilitate hands-on learning, with a Jupyter notebook provided for interactive coding exercises. The tutorial emphasizes understanding through practice, encouraging readers to attempt the questions before checking the provided answers. The post aims to solidify the reader's grasp of these advanced functions, which are crucial for a data scientist's toolkit.

Opinions

  • The author believes in the importance of practical application to solidify learning, as evidenced by the inclusion of practice questions and a Jupyter notebook for verification of answers.
  • The post suggests that a deep understanding of Python's advanced functions is essential for data scientists, especially in the context of working at Amazon.
  • The author acknowledges that some concepts, like nested functions, may require time and effort to understand, indicating a supportive approach to learning complex topics.
  • The use of real-world scenarios, such as calculating BMI with lambda functions, implies that the author values the application of Python skills to solve practical data science problems.
  • By providing a guided tutorial with questions and answers, the author shows a commitment to making learning Python's advanced functions accessible and structured for data scientists.

12 Foundational Practice Questions on Python’s Advanced Functions for a Data Scientist + Practice Notebook

This post is part of a series of posts where I cover various Data Scientist Role Requirements in Amazon. This post continues where we left off the previous one on the basic topics in building a Python Foundation for a Data Scientist.

Topics

The following topics will be covered in more detail in this post:

  1. Scope
  2. Nested Functions
  3. Exception Handling
  4. Lambda Functions

Tutorial + Questions and Answers

I will start with a brief overview of each concept and then most of the learning will be during the twelve practice questions included for each topic. The Jupyter notebook including questions and answers is provided in the next section. To maximize learning, try to answer the questions yourself before looking at the notebook. Then look at the notebook to verify your answer.

1. Scope

1.1. Scope — Overview

Scope can be broken down into two categories

  • Global: Variables declared outside a function.
  • Local: Variables declared inside a function.

1.2. Scope — Questions

Question 1:

Define a function named a_1, which takes two arguments, multiplies them and stores them in a global variable g_1 (although it is inside the function). Then test the function on arguments 4 and 6.

Question 2:

Take a look at function q_2:

x = 5
def q_2():
    global x
    x = 9
    return x

What do you expect the below two will return? Now try it and see if that is what you expected.

  • print(x)
  • print(q_2())

Question 3:

Let’s try a function that is slightly different than the one in question 2.

y = 5
def q_3():
    y = 9
    return x

What will the following two return? What changed from question 2? Try it and see if that is what you expected.

  • print(y)
  • print(q_3())

2. Nested Functions

2.1. Nested Functions — Overview

  • Nested Function is a function inside another function.
  • There can be layers of nested functions, in which case the most inner function runs first and then it works its way back to the most outer function, which will run last.

2.2. Nested Functions —Questions

Question 4:

This one is going to take some getting used to so do not be disappointed if you do not follow the logic at first.

Define a function named outer_functionthat takes argument x and includes another function nested inside named inner_function, which takes argument y. The inner_functio returns the result of x * y. Test the function when x is 4 and y is 6 and therefore we expect a result of 24.

3. Default Arguments

3.1. Default Arguments — Overview

  • Default arguments are function arguments that are defined at the time the function is declared.
  • When a function’s arguments are not provided by the user calling the function, the default arguments will be used.

3.2. Default Arguments —Questions

Question 5:

Define a function that takes x and y arguments and returns x to the power of y. When y is not provided, it should be 2 by default. Test it on a few scenarios to see how default arguments work.

4. Exception Handling

4.1. Exception Handling — Overview

Exceptions in Python is when an error happens, such as dividing a value by zero, which would generate a ZeroDivisionError: division by zero. We will focus on how to use try and except to convey specific information when an exception happens. There are a few key words to learn for this topic, which will be more solidified after going through the exercise questions.

  • try block is to test a block of code for errors.
  • except block is to handle the error.
  • else block is to execute code in the absence of an error.
  • finally block is executed regardless of what happened in the try block, unlike else which only happens when there are no errors.

4.2. Exception Handling — Questions

Question 6:

Define a function named q_6 that takes two arguments and returns the multiplication of the two arguments. The function is not designed to accept any negative arguments so if any of the two arguments is negative, the function should return a ValueError() class exception that states invalid arguments in a string format. Test out the function on a few scenarios to make sure the function behaves as intended.

Question 7:

When a value is divided by zero, Python throws an error stating ZeroDivisionError: division by zero — give it a try if you have not come across it before. Define function q_7 that takes two arguments and divides one by the other. When the denominator is zero, instead of Python’s usual error message, print division by zero is not possible. Test out the function on a few scenarios to make sure the function behaves as intended.

Question 8:

Define function q_8 that takes one argument. When that argument is zero, returns a ValueError() class exception that zero is not an acceptable argument, otherwise returns the argument. Regardless of the argument, the function should also create a message stating that finished going through "try and except".

5. Lambda Functions

5.1. Lambda Functions — Overview

Unlike the functions we have seen so far, Lambda functions are anonymous, meaning they do not have a name. Lambda functions can take any number of arguments but they can only have one expression (expression is what we have the function do). Therefore they are more limited compared to the regular functions. Unlike the regular functions we had seen so far that start with a def, Lambda functions start with lambda, and therefore there are no surprises that they are called Lambda functions.

The usual format of a Lambda function is as follows:

lambda arguments: expression

For example, Lambda function below takes two arguments and multiplies them.

l = lambda x, y : x * y

In order to pass arguments to the above Lambda function, we can use a format such as: l(2, 3), which will return 6.

Lambda functions will make a lot more sense when we go over the questions and answers.

5.2. Lambda Functions — Questions

Question 9:

Create a lambda function named q_9 that takes one argument and returns that argument to the power of 2.

Question 10:

Create a regular function called q_10 that doubles any given argument, using a nested Lambda function. Test it to make sure it behaves as intended.

Question 11:

Use a Lambda function to change the below list into a lower case and save it as a list named q_11.

i_11 = [“Data Science”, “Python”, “lambda”]

Question 12:

The data frame below includes weights and heights of participants in kilograms and meters, respectively. Calculate their Body Mass Index (BMI) using a Lambda function and store the results in a column named bmi in the same data frame. BMI is weight in kilograms divided by height in meters squared.

import pandas as pd
q_12 = pd.DataFrame({'participant_number' : [1, 2, 3, 4],
                    'weight' : [65, 80, 43, 89],
                    'height' : [1.87, 1.76, 1.53, 1.89]})

3. Notebook

Below is the notebook with both questions and answers for reference.

Thanks for Reading!

If you found this post helpful, please follow me on Medium and subscribe to receive my latest posts!

Data Science
Python
Machine Learning
Amazon
Interview
Recommended from ReadMedium