Variables & Data Types and Basic Math Operations

What is a Variable?

Think of a variable like a box with a label on it.

You put something inside the box, and you use the label to find it later.

name = "Gagan"

Here:

  • name is the label (variable name)
  • "Gagan" is the value stored inside it
  • = means "store this value in this variable"

Now whenever you use name in your code, Python knows it means "Gagan".


Your First Variable Program


    name = "Gagan"
    age = 22
    print(name)
    print(age)

Output:

Gagan
22

Simple! You stored two values and printed them.


Variable Naming Rules

Not everything is allowed as a variable name. Here are the rules:

Allowed:

my_name = "Gagan"       # underscore is allowed
age2 = 25               # numbers allowed (not at start)
firstName = "Gagan"     # camelCase is allowed

NOT Allowed:

2age = 25          # cannot start with a number
my-name = "Gagan"  # hyphen not allowed
my name = "Gagan"  # spaces not allowed

Best Practice: Use lowercase with underscores for variable names. This is called snake_case and it's the Python standard:


    first_name = "Gagan"
    phone_number = 9876543210
    is_student = True


Data Types

Every value in Python has a type. Python has several built-in data types. As a beginner, these 4 are the most important:


1. String (str) — Text

Any text inside quotes is a string:


    name = "Gagan"
    city = "Delhi"
    message = "I love Python"

    print(type(name))   # <class 'str'>

type() tells you what type a variable is. Very useful for debugging.


2. Integer (int) — Whole Numbers

Numbers without decimal points:


    age = 22
    year = 2025
    students = 100

    print(type(age))   # <class 'int'>


3. Float (float) — Decimal Numbers

Numbers with decimal points:


    price = 99.99
    height = 5.11
    temperature = 36.6

    print(type(price))   # <class 'float'>


4. Boolean (bool) — True or False

Only two possible values — True or False:


    is_student = True
    has_job = False
    is_raining = True

    print(type(is_student))   # <class 'bool'>

Important: True and False must start with capital letters. true or false will give an error.


Using Variables with print()

You can combine variables and text in print using f-strings (the modern way):


    name = "Gagan"
    age = 22
    city = "Delhi"

    print(f"My name is {name}")
    print(f"I am {age} years old")
    print(f"I live in {city}")
    print(f"My name is {name} and I am {age} years old")

Output:

My name is Gagan
I am 22 years old
I live in Delhi
My name is Gagan and I am 22 years old

The f before the quote makes it an f-string. Inside {} curly brackets you write your variable name and Python automatically puts its value there.

This is the most used and cleanest way to print variables in modern Python.


Updating Variables

You can change the value of a variable anytime:


    score = 0
    print(f"Score: {score}")

    score = 10
    print(f"Score: {score}")

    score = 50
    print(f"Score: {score}")

Output:

Score: 0
Score: 10
Score: 50

The variable just gets updated with the new value.


Multiple Variables in One Line

Python allows this shortcut:


    x, y, z = 10, 20, 30
    print(x)   # 10
    print(y)   # 20
    print(z)   # 30

Or assign the same value to multiple variables:


    a = b = c = 0
    print(a, b, c)   # 0 0 0


A Complete Example

Let's put it all together:


    # Personal Information
    name = "Gagan"
    age = 22
    city = "Delhi"
    height = 5.11
    is_student = True

    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"City: {city}")
    print(f"Height: {height}")
    print(f"Student: {is_student}")
    print(f"Data type of name: {type(name)}")
    print(f"Data type of age: {type(age)}")

Output:

Name: Gagan
Age: 22
City: Delhi
Height: 5.11
Student: True
Data type of name: <class 'str'>
Data type of age: <class 'int'>

Exercise 🏋️

Create a program that stores this information in variables and prints it using f-strings:

  • Your name
  • Your age
  • Your favorite subject
  • Your city
  • Whether you are a student (True/False)

Expected output format:

Hello! My name is [name]
I am [age] years old
My favorite subject is [subject]
I live in [city]
Am I a student? [True/False]

Try it yourself!


Basic Math Operations

Python as a Calculator

Python can do all kinds of math. Think of it as a very powerful calculator.

Let's start simple:


    print(2 + 3)    # 5
    print(10 - 4)   # 6
    print(3 * 4)    # 12
    print(10 / 2)   # 5.0


All Math Operators in Python

Operator

Name

Example

Result

+

Addition

5 + 3

8

-

Subtraction

5 - 3

2

*

Multiplication

5 * 3

15

/

Division

10 / 3

3.333...

//

Floor Division

10 // 3

3

%

Modulus

10 % 3

1

**

Power / Exponent

2 ** 3

8

Let's understand each one properly.


Addition, Subtraction, Multiplication — Simple


    a = 10
    b = 3

    print(a + b)   # 13
    print(a - b)   # 7
    print(a * b)   # 30

Nothing surprising here. Works exactly like normal math.


Division / — Always Returns Float


    print(10 / 2)   # 5.0   (not 5, notice the .0)
    print(7 / 2)    # 3.5
    print(10 / 3)   # 3.3333333333333335

Regular division always returns a float even if the answer is a whole number. That's why 10 / 2 gives 5.0 not 5.


Floor Division // — Removes the Decimal


    print(10 // 3)   # 3   (3.33... becomes 3, decimal removed)
    print(7 // 2)    # 3   (3.5 becomes 3)
    print(15 // 4)   # 3   (3.75 becomes 3)

Floor division divides and then rounds down to the nearest whole number. Decimal part is just thrown away.


Modulus % — Gives the Remainder

This one confuses beginners at first but it's very useful:


    print(10 % 3)   # 1   (10 divided by 3 = 3, remainder is 1)
    print(15 % 4)   # 3   (15 divided by 4 = 3, remainder is 3)
    print(10 % 2)   # 0   (10 divided by 2 = 5, remainder is 0)

Think of it like this — when you divide 10 by 3:

  • 3 goes into 10 exactly 3 times (that's 9)
  • What's left over is 1
  • So 10 % 3 = 1

Most common use case: Checking if a number is even or odd:


    number = 7
    print(number % 2)   # 1 — odd (remainder is 1)

    number = 8
    print(number % 2)   # 0 — even (remainder is 0)

If number % 2 is 0 → even. If it's 1 → odd. You'll use this a LOT in future.


Power ** — Exponents


    print(2 ** 3)    # 8    (2 * 2 * 2)
    print(5 ** 2)    # 25   (5 * 5)
    print(3 ** 4)    # 81   (3 * 3 * 3 * 3)
    print(9 ** 0.5)  # 3.0  (square root of 9)


Math with Variables

You'll almost never do math with raw numbers. You'll use variables:


    price = 500
    quantity = 3
    discount = 50

    total = price * quantity
    final_price = total - discount

    print(f"Price per item: {price}")
    print(f"Quantity: {quantity}")
    print(f"Total before discount: {total}")
    print(f"Discount: {discount}")
    print(f"Final price: {final_price}")

Output:

Price per item: 500
Quantity: 3
Total before discount: 1500
Discount: 50
Final price: 1450

Shorthand Operators

These are shortcuts to update a variable's value:


    score = 10

    score = score + 5   # normal way
    score += 5          # shorthand — same thing

    score = score - 3
    score -= 3          # shorthand

    score = score * 2
    score *= 2          # shorthand

    score = score / 2
    score /= 2          # shorthand

Full example:


    score = 0
    print(f"Start: {score}")

    score += 10
    print(f"After +10: {score}")

    score += 5
    print(f"After +5: {score}")

    score -= 3
    print(f"After -3: {score}")

    score *= 2
    print(f"After *2: {score}")

Output:

Start: 0
After +10: 10
After +5: 15
After -3: 12
After *2: 24

Order of Operations (BODMAS)

Python follows the same math rules you learned in school — BODMAS/PEMDAS:

  1. Brackets ()
  2. Exponents **
  3. Multiplication *, Division /, Floor Division //, Modulus %
  4. Addition +, Subtraction -

    print(2 + 3 * 4)      # 14  (multiplication first, then addition)
    print((2 + 3) * 4)    # 20  (brackets first)
    print(10 - 2 + 3)     # 11  (left to right)
    print(2 ** 3 + 1)     # 9   (exponent first, then addition)

When in doubt — use brackets to make your intention clear:

result = (price * quantity) - discount   # clear and readable

Type Conversion in Math

Sometimes you'll have a number stored as a string and need to do math with it. Direct math won't work:


    a = "10"   # this is a string, not a number
    b = 5

    print(a + b)   # ERROR! can't add string and number

You need to convert it first:


    a = "10"
    b = 5

    a = int(a)     # convert string to integer
    print(a + b)   # 15 — works now!

Conversion functions:

  • int() — converts to integer
  • float() — converts to float
  • str() — converts to string

    print(int("25"))       # 25
    print(float("3.14"))   # 3.14
    print(str(100))        # "100"
    print(int(9.99))       # 9  (decimal part is cut off, not rounded)


Real World Example — Simple Bill Calculator


    item1 = 150
    item2 = 250
    item3 = 100

    subtotal = item1 + item2 + item3
    tax = subtotal * 0.18        # 18% GST
    total = subtotal + tax

    print(f"Item 1: Rs.{item1}")
    print(f"Item 2: Rs.{item2}")
    print(f"Item 3: Rs.{item3}")
    print(f"Subtotal: Rs.{subtotal}")
    print(f"GST (18%): Rs.{tax}")
    print(f"Total Bill: Rs.{total}")

Output:

Item 1: Rs.150
Item 2: Rs.250
Item 3: Rs.100
Subtotal: Rs.500
GST (18%): Rs.90.0
Total Bill: Rs.590.0

Exercise 🏋️

Write a program that:

  1. Stores two numbers in variables a = 17 and b = 5
  2. Prints the result of all 7 operations on them (addition, subtraction, multiplication, division, floor division, modulus, power)
  3. Also prints whether a is even or odd using modulus operator

Expected output format:

a = 17, b = 5
Addition: 22
Subtraction: 12
Multiplication: 85
Division: 3.4
Floor Division: 3
Modulus (Remainder): 2
Power: 1419857
Is a even? False  (hint: use a % 2 == 0)

Don't worry about the last line for now — we'll properly learn == in the next step. Just try your best!


Installing Python and Your First Python Program

Step 1: Installing Python

Let's start from the very beginning — getting Python on your computer.


How to Download & Install Python

Step 1: Go to the official website — python.org

Step 2: Click on the Downloads button. It will automatically detect your operating system (Windows/Mac/Linux) and suggest the latest version.

Step 3: Download Python 3.13.x (whatever the latest 3.13 version is shown)

Step 4: Run the installer


IMPORTANT — Windows Users (Read This Carefully)

When the installer opens, you will see a checkbox at the bottom that says:

☐ Add Python to PATH

CHECK THIS BOX BEFORE CLICKING INSTALL.

This is the most common beginner mistake. If you skip this, Python won't work from your terminal/command prompt.

After checking that box, click "Install Now" and wait for it to finish.


Verify Installation

After installing, let's confirm Python is working correctly.

On Windows:

  • Press Windows + R, type cmd, press Enter
  • A black window (Command Prompt) will open
  • Type this and press Enter:
python --version

On Mac/Linux:

  • Open Terminal
  • Type:
python3 --version

You should see something like:

Python 3.13.1

If you see this — Python is successfully installed! 🎉

If you see an error like "python is not recognized" — it means you forgot to check the PATH checkbox. In that case, uninstall Python and install again, this time checking that box.


Installing VS Code (Code Editor)

Python is installed. Now you need a place to write your code. We'll use VS Code — it's free and the most popular editor.

Step 1: Go to code.visualstudio.com

Step 2: Download for your OS and install it (simple next-next-finish installation)

Step 3: Open VS Code

Step 4: On the left side, click the Extensions icon (looks like 4 squares)

Step 5: Search for "Python" — install the one made by Microsoft (it has millions of downloads)

This extension helps VS Code understand Python code — gives you suggestions, highlights errors, etc.


Setting Up Your First Project Folder

Good habit from day one — keep your code organized.

Step 1: Create a folder on your Desktop or anywhere you like. Name it something like python-learning

Step 2: Open VS Code → File → Open Folder → select your python-learning folder

Step 3: Inside VS Code, create a new file → name it hello.py

The .py extension tells your computer "this is a Python file"


Step 2: Your First Python Program

The Tradition — "Hello, World!"

In programming, when you learn any new language, the very first program everyone writes is called "Hello, World!". It's a tradition since the 1970s. So let's follow it!


Writing Your First Program

Open the hello.py file you created in VS Code and type this:


    print("Hello, World!")

That's it. This is a complete, valid Python program.


Running Your Program

Method 1 — Using VS Code Terminal:

In VS Code, go to Terminal → New Terminal (or press Ctrl + backtick)

A terminal will open at the bottom of VS Code. Type:

python hello.py

On Mac/Linux:

python3 hello.py

Press Enter. You will see:

Hello, World!

Method 2 — Using the Play Button:

In VS Code, you'll see a ▶ Play button on the top right corner. Just click it and it runs your file directly.


What is print()?

print() is a function that displays text on the screen.

Whatever you write inside the brackets () with quotes, it will show on screen.

Let's try a few more examples. Update your file:


    print("Hello, World!")
    print("My name is Gagan")
    print("I am learning Python")
    print("This is my first program!")

Run it. Output:

Hello, World!
My name is Gagan
I am learning Python
This is my first program!

Each print() starts on a new line automatically.


Quotes — Single or Double?

Both work in Python. These two lines do the exact same thing:


    print("Hello, World!")
    print('Hello, World!')

You can use single quotes ' ' or double quotes " " — your choice. Just be consistent. Most people use double quotes.


What Happens If You Make a Mistake?

Let's intentionally break the code so you understand errors:


    print("Hello, World!"

Run this. You'll see:

SyntaxError: '(' was never closed

This is called a Syntax Error — it means your code has a typo or something is missing. Here the closing bracket ) is missing.

Fix it back:


    print("Hello, World!")

Important mindset: Errors are normal. Every programmer gets errors daily. Don't panic when you see one — just read it carefully and it usually tells you what went wrong.


Comments — Notes in Your Code

Sometimes you want to write notes in your code that Python should ignore. These are called comments.

Use the # symbol:


    # This is my first Python program
    print("Hello, World!")  # This prints a message

    # Python will ignore everything after the # symbol
    # print("This line will NOT run")
    print("But this line will run")

Output:

Hello, World!
But this line will run

Comments are very useful for:

  • Explaining what your code does
  • Temporarily disabling a line without deleting it
  • Leaving notes for yourself or others

Your First Exercise 🏋️

Write a program that prints the following output exactly:

Welcome to Python!
My name is [your name]
I am a beginner
Let's learn together!

Use 4 separate print() statements. Try it yourself first, then move to the next step.

Python Learning Roadmap for Beginners

Welcome! Python is one of the best first programming languages. It's simple, readable, and used everywhere — web development, data science, AI, automation, and more.


What You Need to Know Before Starting

Nothing! Seriously. Python is beginner-friendly. You just need:

  • A computer (Windows, Mac, or Linux — all work)
  • Basic computer skills (how to open files, use a browser)
  • Curiosity and patience

That's it. No prior coding experience needed.


Current Python Version

Always use Python 3.13 (latest stable as of 2025). Never use Python 2 — it's dead.


Your Complete Python Learning Roadmap

Stage 1 — Setup & Basics (Week 1-2)

This is where we start. You'll learn:

  • How to install Python
  • How to write your first program
  • Variables and data types (numbers, text, etc.)
  • Taking input from user
  • Basic math operations
  • Comments in code

Stage 2 — Control Flow (Week 2-3)

  • If / else conditions
  • Loops — for loop, while loop
  • Break and continue

Stage 3 — Functions (Week 3-4)

  • What is a function and why we need it
  • Creating and calling functions
  • Parameters and return values
  • Scope (local vs global variables)

Stage 4 — Data Structures (Week 4-5)

  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • When to use which one

Stage 5 — String Handling (Week 5)

  • String methods
  • String formatting (f-strings)
  • Slicing strings

Stage 6 — File Handling (Week 6)

  • Reading files
  • Writing files
  • Working with paths

Stage 7 — Error Handling (Week 6)

  • Try / except
  • Common errors and how to fix them

Stage 8 — Modules & Libraries (Week 7)

  • What is a module
  • Importing built-in modules
  • Installing external libraries with pip
  • Important built-in modules: os, math, random, datetime

Stage 9 — Object Oriented Programming / OOP (Week 8-9)

  • Classes and Objects
  • Constructor (init)
  • Methods
  • Inheritance
  • Encapsulation

Stage 10 — Pythonic Code & Best Practices (Week 9-10)

  • List comprehensions
  • Lambda functions
  • Map, filter
  • Writing clean code

Variables & Data Types and Basic Math Operations

What is a Variable? Think of a variable like a box with a label on it . You put something inside the box, and you use the label to find it...