All 57 lessons

Lesson 1 of 57 · Getting Started

What Is Python and Why Do Data Analysts Use It?

By Skillancy Editorial Team

Run the code in the free Python Compiler or on your own computer. Lessons that read files use the FreshBasket practice data: download the dataset (ZIP).

If you have ever opened a spreadsheet with 10 lakh rows and watched Excel freeze, or copied the same weekly report together for the fifth Monday in a row, you already understand the problem Python solves. Python is a programming language that lets you tell a computer exactly what to do with data, once, and then repeat it on a million rows or a thousand files in seconds.

This is the first lesson of a free, hands-on Python tutorial built for people who want to work in data analytics. You do not need any programming background. By the end of the tutorial you will clean messy data, analyse it with pandas, draw charts, call APIs, scrape web pages and automate Excel reports. Every code example in these lessons was actually executed, and every output you see is real.

What is Python?

Python is a general-purpose programming language created by Guido van Rossum and first released in 1991. "General-purpose" means it is not limited to one job. The same language runs web backends at Instagram, powers machine learning at Google, automates data pipelines at Walmart and Flipkart, and helps a student rename 500 files in a folder.

Three design choices make Python the favourite first language for analysts:

1. It reads almost like English. Compare if delivery_minutes > 30: with the equivalent in many other languages. You can usually guess what a Python line does even before learning the syntax.

2. It is interpreted. You do not compile anything. Python reads your code line by line and executes it immediately, so you can try an idea and see the answer in a second.

3. It has an enormous library ecosystem. Libraries are packages of ready-made code written by other people. pandas handles tables, matplotlib draws charts, requests talks to websites, openpyxl writes Excel files. You will use all of these in this tutorial.

Why analysts use Python (and still keep Excel and SQL)

Python does not replace your other tools. It fills the gaps between them.

TaskExcelSQLPython
Quick look at 500 rowsExcellentFineFine
Millions of rowsStrugglesExcellentExcellent
Join and aggregate tablesPainful (VLOOKUP)ExcellentExcellent (pandas)
Clean messy text and datesManualLimitedExcellent
Repeat the same report every weekManual or macrosNeeds schedulingExcellent, fully scriptable
Statistics, forecasting, machine learningLimitedVery limitedExcellent
Call an API or scrape a websiteNoNoExcellent

A typical analyst's day uses all three: SQL to pull data from the warehouse, Python to clean and analyse it, Excel or a dashboard to share the result. If you already know SQL, you will find that Python's pandas library uses the same ideas (filter, group, join) with different spelling. Later in this tutorial there is a full lesson that translates SQL to pandas line by line.

How Python runs your code

When you run a Python program, the Python interpreter reads your instructions from top to bottom, one statement at a time. Each statement is executed before the next one starts. If something goes wrong, Python stops and prints an error message that tells you the line number and the type of problem. Reading those messages is a skill, and we practise it in every lesson.

There are three common ways to run Python:

  • A script is a text file ending in .py. You run it with python report.py. Scripts are best for automation that runs on a schedule.
  • The interactive shell (REPL) is what you get when you type python in a terminal. It runs one line at a time, which is handy for quick experiments.
  • A notebook (Jupyter or Google Colab) mixes code, output and notes in cells. It is the most popular way to do analysis because you see tables and charts right under the code that made them.

The next lesson shows you how to install Python and set up a notebook. For now, you only need to read along: every example here is shown together with its real output.

Meet FreshBasket: the dataset for this tutorial

Learning from toy examples like x = 5 gets boring quickly, and it does not prepare you for real work. So every lesson in this tutorial uses the same fictional company, FreshBasket, a quick-commerce grocery service that delivers within 30 minutes from dark stores in eight Indian cities.

The data lives in a handful of CSV files that you can download with the tutorial. The first thing an analyst always does with a new dataset is look at it, so let us do that now. Do not worry about understanding the code yet. We will explain it in later lessons, and each line here is simple enough to read.

Worked examples

Example 1: Python as a calculator

Question: FreshBasket's Bengaluru store delivered 412 orders yesterday with an average basket of ₹486.50. What was the revenue, and how much is that per minute of a 16-hour operating day?

orders_today = 412
average_basket = 486.50
revenue = orders_today * average_basket
revenue

Output

200438.0

How it works: Python evaluates the arithmetic expression orders_today * average_basket and stores the answer under the name revenue. A name that holds a value is called a variable. On the last line we wrote just revenue, and Python echoed its value back. In a notebook or the interactive shell, the last expression of a cell is always displayed this way.

Reading the result: The store earned ₹200,438.00 in one day. Let us divide by the minutes in 16 hours:

minutes_open = 16 * 60
revenue_per_minute = revenue / minutes_open
round(revenue_per_minute, 2)

Output

208.79

That is about ₹208.79 per minute, and it took us two lines. Notice we reused the variable revenue from the previous cell. Python remembers variables for as long as the session is open.

Example 2: Your first program

Question: How do I make Python display a message?

print("Welcome to FreshBasket analytics!")
print("Let us explore some real data.")

Output

Welcome to FreshBasket analytics!
Let us explore some real data.

How it works: print() is a built-in function: a named piece of code that does a job. You give it something inside the parentheses (here, text wrapped in quotes) and it displays it. Text in quotes is called a string. Each print call writes one line.

Reading the result: Two print calls, two lines of output, in the same order as the code. Python never reorders your statements.

Example 3: Combining text and numbers

Question: Print a sentence that reports the revenue we calculated.

city = "Bengaluru"
print(f"{city} store earned Rs. {revenue:,.0f} yesterday.")

Output

Bengaluru store earned Rs. 200,438 yesterday.

How it works: The f before the opening quote creates an f-string. Anything inside curly braces is replaced by the value of that variable, and the part after the colon controls the format: ,.0f means "use commas as thousand separators and show zero decimal places". F-strings are the cleanest way to build messages and you will use them constantly.

Reading the result: We got a readable sentence with the revenue rounded to the nearest rupee. If you change city and run it again, the message changes automatically, which is the first hint of how automation works.

Example 4: Looking at real data with pandas

Question: What does FreshBasket's order data look like?

import pandas as pd

orders = pd.read_csv("orders.csv")
orders.head()

Output

  order_id customer_id store_id  order_date  delivery_slot payment_method order_status  delivery_minutes  discount_pct
0   O02299       C0078      S03  2025-01-01  Evening (4-8)           Card    Delivered              34.0            15
1   O04533       C0230      S07  2025-01-01  Midday (10-2)            UPI    Delivered              24.0            15
2   O00778       C0328      S09  2025-01-02   Night (8-11)           Card    Delivered              37.0            15
3   O03607       C0310      S02  2025-01-02  Evening (4-8)            UPI    Delivered              29.0             0
4   O04377       C0280      S09  2025-01-02  Evening (4-8)            COD    Delivered              20.0             0

How it works: import pandas as pd loads the pandas library and gives it the short nickname pd, a convention used everywhere. pd.read_csv("orders.csv") reads the file into a DataFrame, which is pandas's name for a table with rows and columns. .head() shows the first five rows.

Reading the result: Each row is one order, with columns for the customer, the store, the date, how the customer paid and how long the delivery took. The table has 6,000 rows. The same data in Excel would be uncomfortable; here it loaded in a fraction of a second.

Example 5: Answering business questions in one line each

Question: How many orders were delivered, and what was the average delivery time?

delivered = orders[orders["order_status"] == "Delivered"]
print("Delivered orders:", len(delivered))
print("Average delivery minutes:", round(delivered["delivery_minutes"].mean(), 1))

Output

Delivered orders: 5391
Average delivery minutes: 23.7

How it works: The first line keeps only the rows where order_status equals "Delivered". It is the pandas version of WHERE order_status = 'Delivered'. We stored the filtered table in delivered. Then len() counts rows and .mean() averages a column.

Reading the result: 5,391 of 6,000 orders were delivered, with an average delivery time of 23.7 minutes. That beats FreshBasket's 30-minute promise on average, but averages hide problems. In later lessons you will check how many individual orders missed the promise.

Example 6: The same question in SQL and Python

Question: If I already know SQL, how different is this?

SELECT COUNT(*) AS delivered_orders,
       ROUND(AVG(delivery_minutes), 1) AS avg_minutes
FROM orders
WHERE order_status = 'Delivered';
result = (
    orders[orders["order_status"] == "Delivered"]["delivery_minutes"]
    .agg(["count", "mean"])
    .round(1)
)
result

Output

count    5391.0
mean       23.7
Name: delivery_minutes, dtype: float64

How it works: The SQL query filters with WHERE, then aggregates with COUNT and AVG. The pandas version filters with square brackets, picks the column, and applies the same two aggregations through .agg(). The shape of the thinking (filter, then summarise) is identical.

Reading the result: Both give the same numbers: 5,391 delivered orders and an average of 23.7 minutes. Knowing SQL means you already know the logic of pandas.

Example 7: A taste of repetition

Question: Print a one-line summary for each of our first four cities without writing four separate print statements.

stores = pd.read_csv("stores.csv")
orders_by_city = orders.merge(stores, on="store_id")["city"].value_counts()

cities = ["Bengaluru", "Mumbai", "Delhi", "Hyderabad"]
for c in cities:
    print(f"{c}: {orders_by_city[c]} orders")

Output

Bengaluru: 1301 orders
Mumbai: 945 orders
Delhi: 1291 orders
Hyderabad: 689 orders

How it works: cities is a list of four strings. The for loop takes them one at a time, puts the current one into c, and runs the indented lines underneath. Indentation (the four spaces) is how Python knows which lines belong to the loop. Do not worry about the first two lines yet: they join the orders table to the stores table so each order knows its city, and count orders per city. You will learn both in the pandas module.

Reading the result: Four cities, four lines, one block of code. If we had 400 cities, the code would not change. Repetition without copy-paste is the core of automation.

Example 8: Python reads like English

Question: Flag an order as fast or slow.

delivery_minutes = 34

if delivery_minutes <= 30:
    verdict = "Within promise"
else:
    verdict = "Late"

print(f"{delivery_minutes} minutes -> {verdict}")

Output

34 minutes -> Late

How it works: if tests a condition. When it is true, Python runs the indented block under it; otherwise it runs the block under else. The comparison <= means "less than or equal to".

Reading the result: 34 is greater than 30, so the condition is false and the else branch ran. Try changing delivery_minutes to 22 in your own notebook and watch the verdict change.

Common mistakes

1. Forgetting quotes around text. Text must be inside quotes, otherwise Python thinks it is the name of a variable that does not exist.

print(Welcome)

Output

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print(Welcome)
          ^^^^^^^
NameError: name 'Welcome' is not defined

The error NameError: name 'Welcome' is not defined means Python looked for a variable called Welcome. Fix it with print("Welcome").

2. Wrong capitalisation. Python is case-sensitive: Revenue and revenue are different names.

print(Revenue)

Output

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print(Revenue)
          ^^^^^^^
NameError: name 'Revenue' is not defined. Did you mean: 'revenue'?

3. Bad indentation. Lines inside a loop or an if must be indented consistently.

for c in ["Pune", "Chennai"]:
print(c)

Output

  File "example.py", line 2
      print(c)
      ^^^^^
  IndentationError: expected an indented block after 'for' statement on line 1

The message IndentationError: expected an indented block tells you the line after the colon needs to be indented, usually by four spaces.

Practice questions

Practice 1 (Easy): Monthly revenue

Using variables, calculate a month's revenue if FreshBasket Pune delivers 150 orders a day at an average basket of ₹520, over 30 days. Print the answer in a sentence.

Show solution
daily_orders = 150
basket = 520
days = 30
monthly_revenue = daily_orders * basket * days
print(f"Pune monthly revenue: Rs. {monthly_revenue:,}")

Output

Pune monthly revenue: Rs. 2,340,000

Multiplying three variables gives the total, and the , in the f-string format adds thousand separators so the number is easy to read.

Practice 2 (Medium): Cancelled orders

Using the orders DataFrame, find how many orders have the status "Cancelled".

Show solution
cancelled = orders[orders["order_status"] == "Cancelled"]
print(len(cancelled))

Output

370

Filtering with == keeps only the cancelled rows, and len() counts them. That is 370 orders, or 6.2% of all orders.

Practice 3 (Hard): Fast-delivery percentage

What percentage of delivered orders reached the customer in 20 minutes or less? Round to one decimal place.

Show solution
fast = delivered[delivered["delivery_minutes"] <= 20]
pct = len(fast) / len(delivered) * 100
print(f"{pct:.1f}% of delivered orders took 20 minutes or less")

Output

32.6% of delivered orders took 20 minutes or less

We filtered the already-filtered delivered table, divided the count of fast orders by the count of all delivered orders, and multiplied by 100. Always divide by the right denominator: here it is delivered orders, not all orders.

Key takeaways

  • Python is a readable, free, general-purpose language, and the most common programming tool for data analysts.
  • It complements Excel and SQL; it does not replace them.
  • Python runs your code top to bottom, one statement at a time, and tells you exactly where a problem occurred.
  • A variable stores a value, a function such as print() does a job, and a DataFrame is a table in pandas.
  • You can answer real business questions about 6,000 orders in a few lines of code.
  • All examples use the FreshBasket dataset, so each lesson builds on data you already know.

Next: Setting Up Python, Jupyter and Your First Script

Frequently asked questions

Do I need to know maths or programming before starting?

No. Basic school arithmetic is enough. This tutorial introduces every programming idea from scratch, with analytics examples, and later lessons build on earlier ones step by step.

Should I learn Python or SQL first?

Learn both, but if you can only start with one, SQL is faster to get productive with for pure data retrieval. Python becomes essential once you need cleaning, automation, charts or machine learning. They complement each other, and this tutorial shows how.

Which Python version should I use?

Use any recent version, Python 3.10 or newer. The examples here were run on Python 3.13 with pandas 3. Where behaviour differs on older versions, the lesson tells you.

Is Python free?

Yes. Python, pandas, matplotlib and every other tool in this tutorial are free and open source. You can also run everything in your browser using Google Colab without installing anything.

Can Python replace Excel?

Not entirely. Excel is still the best tool for quick ad hoc work and for sharing results with non-technical colleagues. Python takes over when data is big, messy, repetitive, or needs advanced analysis. Many analysts use Python to produce the Excel file that others then open.

How long will it take to learn?

Most learners who study one lesson a day and practise the questions become comfortable with core Python in three to four weeks, and productive with pandas by week eight. Consistency matters more than long sessions.

Newsletter

Keep learning Python

One email a week with Python and analytics guides, new practice questions and cohort dates. No spam, unsubscribe anytime.

Ready to practise? Try the Python interview questions