What Are the Most Common Python Basic Interview Questions?

Most common python basic interview questions

Categories:

  • Author Avatar
    Written by:

    Nathan Rosidi

This article covers key Python interview questions for beginners, focusing on basics and data handling in Python. Let's dive in!

Did you know that Python is now the most used programming language? As of October 2022, more people use Python than C or Java. This fact comes from the TIOBE Index, a famous ranking for programming languages.

Another fact that, Python's popularity keeps growing fast. Every year, it gets 22% more users. By 2022, over four million developers were using Python on GitHub.

In this article, we will talk about the most common Python questions in job interviews, especially for beginners. We will look at basic things and also how to work with data in Python, buckle up and let’s get started!

Basic Python Interview Question #1: Find out search details for apartments designed for a sole-person stay

This question asks us to identify the search details for apartments that are suitable for just one person to stay in by Airbnb.


DataFrame: airbnb_search_details
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/9615-find-out-search-details-for-apartments-designed-for-a-sole-person-stay

Let’s see our data.

Table: airbnb_search_details

We are looking at information about apartments made for one person. We use two tools, pandas and numpy, which are like helpers for managing and understanding data.

  • First, we focus on the data that shows apartments for one person. We check where 'accommodates' is equal to 1.
  • Then, we also want these apartments to be of a specific type - 'Apartment'. So, we look for where 'property_type' says 'Apartment'.
  • By combining these two conditions, we get details only for apartments perfect for one person.
  • We store this specific information in a new place called 'result'.

In simple words, we are just picking out the apartment searches that match two things: meant for one person and are apartments. Let’s see the code.

import pandas as pd
import numpy as np

result = airbnb_search_details[(airbnb_search_details['accommodates'] == 1) & (airbnb_search_details['property_type'] == 'Apartment')]

Here is the expected output.

Basic Python Interview Question #2: Users Activity Per Month Day

Basic Python Interview Question from Facebook

This question is about figuring out how active users are on different days of the month on Facebook. Specifically, it asks for a count of how many posts are made each day, asked by Meta/Facebook.


DataFrame: facebook_posts
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2006-users-activity-per-month-day

Let’s see our data.

Table: facebook_posts

We are analyzing how often users post on Facebook during different days of the month. We use pandas, a tool for data handling, to do this.

  • First, we change the post dates into a format that's easy to work with.
  • Then, we look at these dates and focus on the day part of each date.
  • For each day, we count how many posts were made.
  • We then make a new table called 'user_activity' to show these counts.
  • Finally, we make sure this table is easy to read by resetting its layout.

Simply, we are counting Facebook posts for each day of the month and presenting it in a clear table. Let’s see the code.

import pandas as pd

result = facebook_posts.groupby(pd.to_datetime(facebook_posts['post_date']).dt.day)['post_id'].count().to_frame('user_activity').reset_index()

Here is the expected output.

Basic Python Interview Question #3: Customers Who Purchased the Same Product

This question involves finding customers who bought the same furniture items, asked by Meta. It asks for details like the furniture's product ID, brand name, the unique customer IDs who bought each item, and how many different customers bought each item.

The final list should start with the furniture items bought by the most customers


DataFrames: online_orders, online_products
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2150-customers-who-purchased-the-same-product

Let’s see our data.

Table: online_orders
Table: online_orders

We are focusing on customers who are interested in buying furniture. We use pandas and numpy, which help us organize and analyze data.

  • We start by combining two sets of data: one with order details (online_orders) and the other with product details (online_products). We match them using 'product_id'.
  • Then, we only keep the data that is about furniture.
  • We simplify this data to show only product ID, brand name, and customer ID, removing any duplicates.
  • Next, we count how many different customers bought each product.
  • We create a new table showing these counts along with product ID, brand name, and customer ID.
  • Lastly, we arrange this table so the products with the most unique buyers are at the top.

In short, we are finding and listing furniture items based on how popular they are with different customers, showing the most popular first. Let’s see the code.

import pandas as pd
import numpy as np

merged = pd.merge(online_orders, online_products, on="product_id", how="inner")
merged = merged.loc[merged["product_class"] == "FURNITURE", :]
merged = merged[["product_id", "brand_name", "customer_id"]].drop_duplicates()
unique_cust = (
    merged.groupby(["product_id"])["customer_id"]
    .nunique()
    .to_frame("unique_cust_no")
    .reset_index()
)
result = pd.merge(merged, unique_cust, on="product_id", how="inner").sort_values(
    by="unique_cust_no", ascending=False
)

Here is the expected output.

Basic Python Interview Question #4: Sorting Movies By Duration Time

This basic Python interview question requires sorting a list of movies based on how long they last, with the longest movies shown first, asked by Google.


DataFrame: movie_catalogue
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2163-sorting-movies-by-duration-time

Let’s see our data.

Table: movie_catalogue

We need to organize movies based on their duration, from longest to shortest. We use pandas, a tool for handling data, to do this.

  • We start by focusing on the movie duration. We extract the duration in minutes from the 'duration' column.
  • We change these duration values into numbers so that we can sort them.
  • Next, we sort the whole movie catalogue based on these duration numbers, putting the longest movies at the top.
  • After sorting, we remove the column with the duration in minutes since we don't need it anymore.

In simple terms, we are putting the movies in order from the longest to the shortest based on their duration. Let’s see the code.

import pandas as pd

movie_catalogue["movie_minutes"] = (
    movie_catalogue["duration"].str.extract("(\d+)").astype(float)
)

result = movie_catalogue.sort_values(by="movie_minutes", ascending=False).drop(
    "movie_minutes", axis=1
)

Here is the expected output.

Basic Python Interview Question #5: Find the date with the highest opening stock price

Basic Python Interview Question from Apple

This question asks us to identify the date when a stock (presumably Apple's, given the dataframe name) had its highest opening price, by Apple.


DataFrame: aapl_historical_stock_price
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/9613-find-the-date-with-the-highest-opening-stock-price

Let’s see our data.

Table: aapl_historical_stock_price

We are looking to find the day when a specific stock had its highest starting price. We use pandas and numpy, tools for data analysis, and handle dates with datetime and time.

  • We start with the stock price data, named 'aapl_historical_stock_price'.
  • Then, we adjust the dates to a standard format ('YYYY-MM-DD').
  • Next, we search for the highest opening price in the data. The 'open' column shows us the starting price of the stock on each day.
  • Once we find the highest opening price, we look for the date(s) when this price occurred.
  • The result shows us the date or dates with this highest opening stock price.

In summary, we are identifying the date when the stock started trading at its highest price. Let’s see the code.

import pandas as pd
import numpy as np
import datetime, time 

df = aapl_historical_stock_price
df['date'] = df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))

result = df[df['open'] == df['open'].max()][['date']]

Here is the expected output.

Basic Python Interview Question #6: Low Fat and Recyclable

This question wants us to calculate what proportion of all products are both low fat and recyclable by Meta/Facebook.


DataFrame: facebook_products
Expected Output Type: pandas.Series

Link to the question: https://platform.stratascratch.com/coding/2067-low-fat-and-recyclable

Let’s see our data.

Table: facebook_products

We need to find out how many products are both low in fat and can be recycled. We use pandas for data analysis.

  • First, we look at the products data and pick out only those that are marked as low fat ('Y' in 'is_low_fat') and recyclable ('Y' in 'is_recyclable').
  • We then count how many products meet both these conditions.
  • Next, we compare this number to the total number of products in the dataset.
  • We calculate the percentage by dividing the number of low fat, recyclable products by the total number of products and multiplying by 100.

Simply put, we are figuring out the fraction of products that are both healthy (low fat) and environmentally friendly (recyclable) and expressing it as a percentage, let’s see the code.

df = facebook_products[(facebook_products.is_low_fat == 'Y') & (facebook_products.is_recyclable == 'Y')]
result = len(df) / len(facebook_products) * 100.0

Here is the expected output.

Basic Python Interview Question #7: Products with No Sales

This question asks us to find products that have not been sold at all by Amazon. We need to list the ID and market name of these unsold products.


DataFrames: fct_customer_sales, dim_product
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2109-products-with-no-sales

Let’s see our data.

Table: fct_customer_sales
Table: dim_product

We are looking for products that haven't been sold yet. We use a merge function, a way of combining two sets of data, for this task.

  • We start by joining two data sets: 'fct_customer_sales' (which has sales details) and 'dim_product' (which has product details). We link them using 'prod_sku_id', which is like a unique code for each product.
  • We then look for products that do not have any sales. We do this by checking for missing values in the 'order_id' column. If 'order_id' is missing, it means the product wasn't sold.
  • After finding these products, we create a list showing their ID ('prod_sku_id') and market name ('market_name').

In simple words, we are identifying products that have never been sold and listing their ID and the market they are associated with, let’s see the code.

sales_and_products = fct_customer_sales.merge(dim_product, on='prod_sku_id', how='right')
result = sales_and_products[sales_and_products['order_id'].isna()][['prod_sku_id', 'market_name']]

Here is the expected output.

Basic Python Interview Question #8: Most Recent Employee Login Details

Basic Python Interview Question from Amazon

This question is about finding the latest login information for each employee at Amazon's IT department.


DataFrame: worker_logins
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2141-most-recent-employee-login-details

Let’s see our data.

Table: worker_logins

We need to identify when each employee last logged in and gather all the details about these logins. We use pandas and numpy for data management and analysis.

  • We start with the 'worker_logins' data, which records employees' login times.
  • For each employee ('worker_id'), we find the most recent ('max') login time.
  • We then create a new table ('most_recent') that shows the latest login time for each employee.
  • Next, we merge this table with the original login data. This helps us match each employee's most recent login time with their other login details.
  • We ensure that we're combining the data based on both employee ID and their last login time.
  • Finally, we remove the 'last_login' column from the result as it's no longer needed.

In short, we are sorting out the most recent login for each employee and displaying all related information about that login, let’s see the code.

import pandas as pd
import numpy as np

most_recent = (
    worker_logins.groupby(["worker_id"])["login_timestamp"]
    .max()
    .to_frame("last_login")
)
result = pd.merge(
    most_recent,
    worker_logins,
    how="inner",
    left_on=["worker_id", "last_login"],
    right_on=["worker_id", "login_timestamp"],
).drop(columns=['last_login'])

Here is the expected output.

Basic Python Interview Question #9: Customer Consumable Sales Percentages

This Python question requires us to compare different brands based on the percentage of unique customers who bought consumable products from them, following a recent advertising campaign, asked by Meta/Facebook.


DataFrames: online_orders, online_products
Expected Output Type: pandas.DataFrame

Link to the question: https://platform.stratascratch.com/coding/2149-customer-consumable-sales-percentages

Let’s see our data.

Table: online_orders
Table: online_products

We are comparing brands to see how popular their consumable products are with customers. We use pandas for data handling.

  • We begin by combining two data sets: one with customer orders (online_orders) and another with product details (online_products). We link them using 'product_id'.
  • Then, we focus on consumable products by filtering the data to include only items in the 'CONSUMABLE' product family.
  • For each brand, we count how many different customers bought their consumable products.
  • We then calculate the percentage of these unique customers out of all customers in the dataset.
  • We round these percentages to the nearest whole number for simplicity.
  • Finally, we arrange the brands so that those with the highest percentage of unique customers are listed first.

In short, we are finding out which brands had the most unique customers for their consumable products, and presenting this information in an easy-to-understand percentage form, ordered from most to least popular, let’s see the code.

import pandas as pd

merged = pd.merge(online_orders, online_products, on="product_id", how="inner")
consumable_df = merged.loc[merged["product_family"] == "CONSUMABLE", :]
result = (
    consumable_df.groupby("brand_name")["customer_id"]
    .nunique()
    .to_frame("pc_cust")
    .reset_index())

unique_customers = merged.customer_id.nunique()
result["pc_cust"] = (100.0 * result["pc_cust"] / unique_customers).round()
result

Here is the expected output.

Basic Python Interview Question #10: Unique Employee Logins

This question asks by Meta/Facebook us to identify the worker IDs of individuals who logged in during a specific week in December 2021, from the 13th to the 19th inclusive.


DataFrame: worker_logins

Link to the question: https://platform.stratascratch.com/coding/2156-unique-employee-logins

Let’s see our data.

Table: worker_logins

We are searching for the IDs of workers who logged in between the 13th and 19th of December 2021. We use pandas, a tool for managing data, and datetime for handling dates.

  • We start with the 'worker_logins' data, which has records of when workers logged in.
  • First, we make sure the login timestamps are in a date format that's easy to use.
  • Then, we find the logins that happened between the 13th and 19th of December 2021. We use the 'between' function for this.
  • From these selected logins, we gather the unique worker IDs.
  • The result will be a list of worker IDs who logged in during this specific time period.

Simply put, we are pinpointing which workers logged in during a certain week in December 2021 and listing their IDs, let’s see the code.

import pandas as pd
import datetime as dt

worker_logins["login_timestamp"] = pd.to_datetime(worker_logins["login_timestamp"])
dates_df = worker_logins[
    worker_logins["login_timestamp"].between("2021-12-13", "2021-12-19")
]
result = dates_df["worker_id"].unique()

Here is the expected output.

Final Thoughts

So, we've explored some of the most common basic Python interview questions. From basic syntax to complex data manipulation, we've covered topics that mirror real-world scenarios, and asked by the big tech companies.

Practice is the key to becoming not just good, but great at data science. Theory is important, but the real learning happens when you apply what you've learned. If you want to see more, here are the python interview questions.

Share

Become a data expert. Subscribe to our newsletter.