Chapter 02 of 12

Variables
& Data
Types

Learn how Python stores data in memory using variables, discovers the five core data types, masters operators, type casting, and user input — the engine of every Python program.

~50 min read
Beginner Level
6 Exercises
variables.py — Python Mastery
1# Chapter 2 — Variables & Data Types
2
3name = "Harsh" # str
4age = 25 # int
5price = 99.99 # float
6is_active = True # bool
7
8print(type(name))
9age = int(input("Enter age: "))
5 Data Types
Type Casting
Variables
Understand memory storage
Data Types
int, float, str, bool, None
Naming Rules
Valid identifier conventions
Operators
Arithmetic, Comparison, Logical
type() Function
Inspect variable types
Type Casting
Convert between data types
User Input
Read keyboard input
Auto Detection
Python's dynamic typing

Why Do We Need Variables?

In programming, data needs to be stored, processed, and reused multiple times. Instead of writing values repeatedly, we use variables to store information in memory.

Core Idea
Variables are the most fundamental building block of programming. Almost every Python program uses them to store, access, and modify data.
In this chapter you will learn:
Variables • Data Types • Operators • Type Conversion • User Input
RAM Memory name = "Harsh" age = 25 price = 99.99 addr: 0x1A "Harsh" addr: 0x2B 25 addr: 0x3C 99.99 Variable Names Memory Locations Variables point to data stored in RAM

What are Variables?

A variable is a name given to a memory location that stores data. Think of it as a labelled container holding a value you can use or change later.

Variable as a Container
a 30 integer name "Harsh" string price 99.99 float a = 30 name = "Harsh" price = 99.99
Think of it like a box
The variable name is the label on the box. The value is what's inside the box.
Creating Variables
variables.py
1a = 30 # stores an integer
2name = "Harsh" # stores a string
3price = 99.99 # stores a decimal
4
5print(a)
6print(name)
7print(price)
Output
30
Harsh
99.99
Rules for Naming Variables
Valid Examples
name
age1
student_name
_total
Invalid Examples
1name ← starts with number
student name ← has space
@price ← special char
Identifier Rules Summary
Can contain: A–Z, a–z, 0–9, _  |  Must start with: letter or _  |  Cannot start with a number or contain spaces.

Python Data Types

Data types define what kind of value a variable holds. Python automatically detects the type based on the assigned value — no need to declare types manually.

Python's Superpower — Dynamic Typing
Unlike C or Java where you must declare int age = 25;, Python simply needs age = 25. Python figures out the type automatically. This makes Python fast to write and easy to read.
int 25 Whole Number float 99.99 Decimal Number str "Harsh" Text Data bool True True / False None None No Value
int
Integer
Whole numbers

Stores any whole number — positive, negative, or zero. No decimal point.

int
1age = 25
10 100 -50 0
float
Float
Decimal numbers

Stores numbers with a decimal point. Used for measurements, prices, and calculations.

float
1price = 99.99
3.14 88.45 100.0
str
String
Text data

Stores text enclosed in single or double quotes. Letters, words, sentences — any text.

str
1name = "Harsh"
"Python" "Hi!"
bool
Boolean
True or False

Only two possible values. Used in conditions, decisions, and logic. Always capitalized.

bool
1is_logged_in = True
True False
None
NoneType
Absence of value

Represents the intentional absence of any value. Like a placeholder or "empty" variable.

None
1data = None
None
Auto Type Detection
Python
1a = 71
2b = 88.44
3name = "Harsh"
4print(type(a))
5print(type(b))
6print(type(name))
Output
<class 'int'>
<class 'float'>
<class 'str'>

Operators in Python

Operators are symbols used to perform operations on values and variables. Python has four main categories.

1. Arithmetic Operators
For mathematical calculations
OperatorNameExample → Result
+Addition10 + 5 → 15
-Subtraction10 - 3 → 7
*Multiplication4 * 5 → 20
/Division10 / 2 → 5.0
%Modulus (remainder)10 % 3 → 1
**Exponent (power)2 ** 3 → 8
//Floor Division10 // 3 → 3
Example
1a = 10
2b = 5
3print(a + b)
4print(a * b)
5print(a % b)
Output
15
50
0
2. Assignment Operators
Assign values to variables
OperatorEquivalent ToExample
=Assignx = 10
+=x = x + nx += 5 → 15
-=x = x - nx -= 3 → 7
*=x = x * nx *= 2 → 20
/=x = x / nx /= 2 → 5.0
3. Comparison Operators
Compare values → returns bool
OpMeaningExample → Result
==Equal to5 == 5 → True
!=Not equal5 != 3 → True
>Greater than10 > 5 → True
<Less than3 < 8 → True
>=Greater or equal5 >= 5 → True
<=Less or equal4 <= 6 → True
4. Logical Operators
Combine conditions
and
Both must be True
True and True → True
or
At least one True
True or False → True
not
Reverses the value
not True → False

The type() Function

What does type() do?
The type() function returns the data type of any variable or value. It's a built-in Python function — no import needed. Essential for debugging and understanding your data.
type() example
1a = 31
2print(type(a))
3
4b = "31"
5print(type(b))
6
7c = 3.14
8print(type(c))
9
10d = True
11print(type(d))
Output
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>
Notice the Difference!
31 vs "31" — They're Different!
The number 31 is an integer you can do math with. The string "31" is text you cannot add or subtract. They look the same but behave completely differently.
31
type(31)
<class 'int'>
Can do math
"31"
type("31")
<class 'str'>
Cannot do math
Pro Tip
Always use type() when debugging to confirm what kind of data you're working with — especially after taking user input!

Type Casting

Type Casting means converting one data type into another. Python provides built-in functions for this.

int 31 str(31) str "31" str "32" int 32 int → str conversion int("32") str → int conversion
1
Integer → String
str() function
1result = str(31)
2print(result)
3print(type(result))
Output
"31"
<class 'str'>
2
String → Integer
int() function
1result = int("32")
2print(result)
3print(type(result))
Output
32
<class 'int'>
3
Integer → Float
float() function
1result = float(32)
2print(result)
3print(type(result))
Output
32.0
<class 'float'>
Type Casting Quick Reference
FunctionConverts ToExampleResult
int()Integerint("42"), int(3.9)42, 3 (truncates)
float()Floatfloat(10), float("3.14")10.0, 3.14
str()Stringstr(100), str(True)"100", "True"
bool()Booleanbool(0), bool(1)False, True

The input() Function

What is input()?
The input() function pauses the program and waits for the user to type something on the keyboard. It then returns what the user typed as a string.
Basic Usage
input.py
1name = input("Enter your name: ")
2print(name)
Terminal
Enter your name: Harsh
Harsh
⚠ Critical Rule — Always a String!
The value returned by input() is always a string, even if the user types a number. You must convert it with type casting if you need a number.
Input Returns a String
type check
1age = input("Enter age: ")
2print(type(age))
Output (even if user types 25)
<class 'str'>
Convert Input to Integer
cast input
1age = int(input("Enter age: "))
2print(age)
3print(type(age))
4print(age + 5)
Output (user typed 25)
25
<class 'int'>
30
Pattern to remember
int(input("prompt: ")) — wrap input() inside int() to get a number you can do math with.

Common Mistakes

Mistake 1: Forgetting to cast input()
Wrong — TypeError when adding
1num = input("Enter: ") # returns str!
2print(num + 10) # TypeError!
Correct — Cast to int first
1num = int(input("Enter: "))
2print(num + 10) # works!
Mistake 2: Variable name starts with number
Wrong — SyntaxError
11name = "Harsh" # SyntaxError!
23_count = 10 # SyntaxError!
Correct — Start with letter or _
1name1 = "Harsh" # valid
2_count = 10 # valid
Mistake 3: Converting non-numeric string to int
Wrong — ValueError
1x = int("Harsh") # ValueError!
Correct — Only numeric strings work
1x = int("42") # valid: "42" is numeric
Mistake 4: Using = instead of == for comparison
Wrong — Assigns instead of comparing
1if a = 5: # SyntaxError!
Correct — Use == to compare
1if a == 5: # correct: ==

Interview Questions

A variable is a named memory location that stores a value. In Python, variables are created when you assign a value to them using the = operator. Python is dynamically typed, so you don't need to declare the type — it's inferred automatically. Example: x = 10 creates an integer variable.

Python has five basic data types: int (whole numbers like 25), float (decimal numbers like 3.14), str (text like "Hello"), bool (True or False), and NoneType (represents no value). Python detects types automatically based on the assigned value.

Type casting is converting one data type into another. Python provides built-in functions: int() converts to integer, float() to float, str() to string, and bool() to boolean. It's especially useful when working with user input, since input() always returns a string.

The input() function always returns a string, regardless of what the user types. If the user enters the number 25, Python stores it as the string "25", not the integer 25. To use it as a number, you must convert it: age = int(input("Enter age: ")).

= is the assignment operator — it stores a value in a variable: x = 5. == is the comparison operator — it checks if two values are equal and returns True or False: x == 5 → True. Confusing them is one of the most common Python mistakes.

Variable names (identifiers) can contain letters (A-Z, a-z), digits (0-9), and underscores (_). They must start with a letter or underscore — never a digit. Spaces are not allowed. Python is case-sensitive: name and Name are different variables. Reserved keywords like if, for, while cannot be used as variable names.

Practice Questions

Write every line yourself — the best way to learn is by doing, not just reading.

Q1Easy
Add Two Numbers

Write a Python program to add two numbers and print the result.

Hint: Use the + operator between two variables.
Q2Easy
Find the Remainder

Write a program to find the remainder when one number is divided by another.

Hint: Use the % (modulus) operator.
Q3Easy
Check Data Type

Take input from the user and check the data type of the entered value using the type() function.

Hint: Use print(type(value)) to display the type.
Q4Medium
Greater Than Check

Given a = 34 and b = 80, use a comparison operator to determine if a is greater than b. Print the result.

Hint: Use > operator. The output will be False.
Q5Medium
Average Calculator

Write a Python program to calculate the average of two numbers entered by the user.

Hint: Use int(input()) for both numbers, then (a + b) / 2.
Q6Medium
Square a Number

Write a Python program to calculate the square of a number entered by the user.

Hint: Use ** (exponent) operator: num ** 2.

Chapter Summary

Variables are named memory locations that store data and can be reused throughout a program.
Python has 5 basic data types: int, float, str, bool, and None.
Python automatically detects the data type based on the assigned value — no manual declaration needed.
Variable names can contain letters, digits, and underscores. They cannot start with a number or contain spaces.
4 operator types: Arithmetic (+ - * / % ** //), Assignment (= += -=), Comparison (== != > <), Logical (and or not).
The type() function returns the data type of any variable — essential for debugging.
Type Casting converts between types: int(), float(), str(), bool().
The input() function reads keyboard input and always returns a string — convert it when you need a number.
Pattern: int(input("prompt: ")) — reads user input and converts it to integer in one line.
Completion Checklist
Understand Variables
Understand Data Types
Use Arithmetic Operators
Use Comparison Operators
Check Data Types using type()
Perform Type Casting
Take User Input
Solve All Practice Questions
Your Progress
0/8
Excellent Work!

You have successfully completed Chapter 2 — Variables & Data Types. You can now build programs that store, process, and interact with data!

Chapter 2 Complete!

Two chapters down, ten to go. You're building serious Python foundations — keep the momentum!

16.7%
2 of 12 chapters completed
Back to Course Home
Ch 1
Modules
Ch 2
Variables
3
Ch 3
Strings
4
Ch 4
Lists
5
Ch 5
Loops
...
More
Coming