Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Week 1 – Python for Data Science  ·  Day 03

Day 3: Python Basics: Variables, Types, Operators

⏱ 90 min📶 Beginner🎯 100% self-study
Day 3 / 60

✅ Today you will learn

  • Variables and naming rules
  • Data types: int, float, str, bool, None
  • Type conversion – the #1 cause of data bugs
  • Arithmetic, comparison and logical operators
  • f-strings for clean reports

🏢 In the real world

A CSV exported from a billing system stores prices as text like "1,299". Until you convert it to a number, totals and averages are impossible. Knowing types saves hours of debugging in real projects.

Variables: names for values

A variable is a label that points to a value. Python decides the type automatically.

Python
product = "Wireless Earbuds"      # str  (text)
price = 1499                     # int  (whole number)
rating = 4.3                     # float (decimal)
in_stock = True                  # bool (True / False)
discount_code = None             # None (no value yet)
print(product, price, rating, in_stock, discount_code)
print(type(product), type(price), type(rating), type(in_stock), type(discount_code))
Wireless Earbuds 1499 4.3 True None <class 'str'> <class 'int'> <class 'float'> <class 'bool'> <class 'NoneType'>
RuleGoodBad
Use letters, digits, _total_salestotal-sales
Cannot start with a digitsales_20242024_sales
Use snake_case and meaningavg_order_valuex1
Case-sensitivePrice ≠ price—

Data types you meet in every dataset

🔢
intCounts: quantity, age, number of orders
➗
floatMeasurements: price with paise, rating, temperature
🔤
strText: city, product name, review
✅
boolYes/No flags: churned, approved, paid
∅
None / NaNMissing value – very common in real data
The five everyday types

Type conversion

Python
price_text = "1,299"                  # how many CSVs store numbers
price = int(price_text.replace(",", ""))
qty = int("3")
print(price * qty)                    # now maths works
print(float("4.5") + 0.5)
print(str(2024) + "-25")
print(bool(0), bool(15), bool(""), bool("Delhi"))
3897 5.0 2024-25 False True False True
Python
age = "twenty"
try:
    age = int(age)
except ValueError as e:
    print("Cannot convert:", e)
Cannot convert: invalid literal for int() with base 10: 'twenty'

Operators

Python
monthly_salary = 45000
print("Yearly       :", monthly_salary * 12)
print("Per day (30) :", monthly_salary / 30)
print("Full weeks   :", 45 // 7, "| left days:", 45 % 7)
print("Power        :", 2 ** 10)
price, gst_rate = 1499, 18
print("Price + GST  :", price + price * gst_rate / 100)
Yearly : 540000 Per day (30) : 1500.0 Full weeks : 6 | left days: 3 Power : 1024 Price + GST : 1768.82
Python
marks, attendance = 72, 68
print(marks >= 40)                          # comparison -> bool
print(marks >= 40 and attendance >= 75)     # both needed
print(marks >= 90 or attendance == 100)     # any one
print(not attendance >= 75)
city = "Pune"
print(city in ["Pune", "Mumbai", "Nagpur"]) # membership
True False False True True
OperatorMeaningExample → result
+ - * /Add, subtract, multiply, divide7 / 2 → 3.5
//Floor division7 // 2 → 3
%Remainder7 % 2 → 1
**Power2 ** 3 → 8
== !=Equal / not equal5 == 5 → True
> < >= <=Compare3 > 5 → False
and or notLogicTrue and False → False
inIs inside"a" in "data" → True

Strings for data work

Python
city = "  new delhi "
clean = city.strip().title()
print(clean)                          # remove spaces + proper case
print(clean.upper(), clean.lower())
print(clean.replace("New ", ""))
email = "riya.sharma@gmail.com"
print(email.split("@")[1])            # domain
print(len(email), email.endswith(".com"))
print("Order ID:", "BK" + str(100245))
New Delhi NEW DELHI new delhi Delhi gmail.com 21 True Order ID: BK100245

f-strings and rounding

Python
name, orders, revenue = "Riya", 14, 28749.456
print(f"{name} placed {orders} orders worth ₹{revenue:,.2f}")
print(f"Average order value: ₹{revenue / orders:.0f}")
growth = 0.1834
print(f"Growth: {growth:.1%}")
print(round(28749.456, 1), round(28749.456, -2))
Riya placed 14 orders worth ₹28,749.46 Average order value: ₹2054 Growth: 18.3% 28749.5 28700.0
⚠️ Float surprise

0.1 + 0.2 gives 0.30000000000000004 because computers store decimals in binary. Always round money for display and compare floats with a tolerance.

Python
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2) == 0.3)
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
0.30000000000000004 True True

Real example: a shopping bill

Python
items = 3
price_each = 649.0                 # Basmati rice 5 kg
discount = 0.10                    # 10 % festive offer
gst = 0.05                         # 5 % GST on rice
subtotal = items * price_each
after_discount = subtotal * (1 - discount)
total = after_discount * (1 + gst)
print(f"Subtotal       : ₹{subtotal:,.2f}")
print(f"After discount : ₹{after_discount:,.2f}")
print(f"Total with GST : ₹{total:,.2f}")
print(f"You saved      : ₹{subtotal - after_discount:,.2f}")
Subtotal : ₹1,947.00 After discount : ₹1,752.30 Total with GST : ₹1,839.91 You saved : ₹194.70

🏅 Job skills unlocked today

✔ Choose the right data type✔ Convert text numbers safely✔ Use operators for business maths✔ Format reports with f-strings

Practice tasks

🏋️ Practice – do it yourself

Task 1: A salary text is "₹52,500". Convert it to an integer and print the yearly salary.
Show solution
Python
salary_text = "₹52,500"
salary = int(salary_text.replace("₹", "").replace(",", ""))
print("Yearly:", salary * 12)
Yearly: 630000
Task 2: Petrol costs ₹96.72 per litre. A car runs 15 km per litre. Print the cost of a 420 km trip with 2 decimals.
Show solution
Python
price, mileage, km = 96.72, 15, 420
litres = km / mileage
print(f"Litres: {litres:.1f} | Cost: ₹{litres * price:,.2f}")
Litres: 28.0 | Cost: ₹2,708.16
Task 3: Check eligibility: a student passes if marks ≥ 33 in every subject (maths 45, science 31, english 60). Print True/False.
Show solution
Python
maths, science, english = 45, 31, 60
print(maths >= 33 and science >= 33 and english >= 33)
False

Quick quiz

🧠 Quick Quiz – test yourself

1. What is type(4.0)?
A number with a decimal point is a float.
2. int("1,299") gives…
The comma is not a digit – remove it first with replace.
3. 17 % 5 equals…
% is the remainder: 17 = 5×3 + 2.
4. f"{0.256:.1%}" prints…
:.1% multiplies by 100 and shows one decimal.
5. Which name is a valid variable?
Names cannot start with a digit, contain hyphens or be keywords like class.

Interview corner

💼 Interview Corner

What is the difference between / and // in Python?

/ is true division and always returns a float (7/2 = 3.5). // is floor division and returns the largest whole number not greater than the result (7//2 = 3).

Why can 0.1 + 0.2 != 0.3 be True?

Floats are stored in binary and many decimals cannot be represented exactly, so tiny rounding errors appear. Use round(), math.isclose() or the decimal module for money.

Summary

  • Variables hold values; Python finds the type itself.
  • int, float, str, bool and None cover most data.
  • Clean text then convert: int(x.replace(",", "")).
  • f"{value:,.2f}" and f"{rate:.1%}" make reports readable.
➡️ Next

Day 4: make decisions with if/else, repeat with loops and package logic into reusable functions.

Frequently Asked Questions

Do I need to declare types in Python?
No. Python is dynamically typed – the type comes from the value. Use type() to check it.
What is the difference between None and NaN?
None is Python’s “no value”. NaN (not a number) is the float used by NumPy and pandas for missing numeric data. pandas treats both as missing.
Why use f-strings?
They are the clearest and fastest way to put values and formatting (commas, decimals, %) inside text.
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 4: Conditions, Loops & Functions Your progress: 3 / 60 (5%) · Lesson 4 / 60 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free