Python Variables and Data Types: Your Computer's Memory Boxes with Different Types
Lesson Overview
Learn how variables work in Python by connecting to familiar mathematical concepts. Discover different data types like Integer, String, and Booleans, and master variable assignment and reassignment with practical examples.
Lesson Content
Remember Math Class? Let's Start There!
Think back to your algebra lessons. When you wrote:
x = 10
What did this mean?
- x is called a variable
- 10 is the value
- We're telling x to "hold" or "remember" the number 10, so whenever we want to use value 10 we can use variable X
The same concept exists in programming! Python uses variables exactly like mathematics - as containers to store and remember values.
What Exactly is a Variable?
Think of a variable as a labeled box in your room:
Think of two pen boxes on your desk labelled Blue Pen Box and Black Pen Box. You can put any pen inside either box - sometimes a blue pen goes in the "Blue Pen Box," sometimes a black pen, sometimes even a pencil. The box labels never change, but what's inside can change anytime
Variables work the same way - the name stays the same, but you can store different values inside whenever you want. Just like pen boxes are containers for pens, variables are containers for data. The label helps you remember which container you're using, even though the contents might be completely different from what the label says
Technically speaking: A variable is a memory location that stores a value, and that value can vary (change) over time - that's why we call it a "variable"!
Assignment: Putting Values in Boxes
Remember our math equation x = 10? In Python, this is called assignment:
How Assignment Works:
- x = 10 → Create a box labeled 'x' and put 10 inside
- x = 12 → Take out 10, put 12 in the same box
- The box name stays 'x', but contents change!
Pay Attention: Look closely at the code presented below, particularly what comes after the # mark, and grasp the context.
# Creating variables (like creating labeled boxes and put pens inside it)
x = 5 # Put number 5 in box labeled 'x' , the variable name is 'x' and it holds the value 5
y = 10 # Put number 10 in box labeled 'y' , the variable name is 'y' and it holds the value 10
result = 0 # Create empty box labeled 'result', the variable name is 'result' and it holds the value 0
# Re-assigning value for variables (like changing the pens inside already labeled boxes)
x = 100 # Previously x contained the value 5, now it has been updated with the value 100 --> called as Re-assignmentSyntax:
variable_name = valueDifferent Types of Data - Just Like Real Life!
In Mathematics, We Have:
- Integers: 1, 2, 100, -5
- Decimals: 3.14, 2.5, -1.7
- Complex numbers: 2+3i, 4-3i
In English Language, We Have:
- Words: "Python", "Hello"
- Characters: 'A', 'x', '@'
- Sentences: "I am learning Python"
- Paragraphs: Multiple sentences together
Just as mathematics organizes numbers into different categories (whole numbers, decimals, complex numbers) and English groups text elements by their structure (single characters, complete words, full sentences), programming languages have various data types to handle different kinds of information appropriately
Data types are categories that tell us what kind of data we're storing and what operations we can perform on them. Think of them as different types of boxes for different types of items!
Python's Basic Data Types
1. Numbers (Just Like Math!)
Integers (int): Whole numbers
age = 21 # This is an int (integer) data type
score = 100
temperature = -5Floats (float): Decimal numbers ==> A float is a number with a decimal point, like 3.14
height = 5.8 # This is a float data type - decimal numbers with fractional parts, Observe the dot/period in float numbers
price = 99.99
pi = 3.141592. Text/Strings (Like English Words!)
Strings (str): String means a group of characters (letters, numbers, symbols)—like words, sentences, names enclosed in either single quotation marks or double quotation marks can be String
name = "Rahul" # This is a string data type - notice how text is wrapped in double quotes ""
message = 'Welcome to Python!' # This is a string data type - notice how text is wrapped in single quotes ''
sepcial_char = '@' # This is string data type only with one character
empty_str = '' # This is just an empty string, it dont hold anythingThink of strings like sentences - they can be single characters or entire paragraphs!
3. Boolean (True/False Answers!)
Boolean (bool): Boolean refers to a value that is either True or False—like a light switch being on or off
is_student = True
is_raining = FalseJust like yes/no questions - the answer is always either True or False!
Sometimes, we need to change a value’s data type; for example, turning a number into a string, or text into a number to perform operations
Data Type Conversions:
Picture yourself traveling from India to Europe - you need to exchange your rupees for euros at the airport. The money's value remains the same, but its form changes to work in a new place( from INR to Euro).Python's type conversion works exactly like this currency exchange! When you convert the integer 100 to the string "100", the information stays the same but the data-type/format changes to work in different parts of your program.
Why conversion matters in Programming: Imagine an online shopping app where users enter their age as '25' (text), but the system needs to calculate discounts using math. Without converting that text to a number, the discount feature would crash! This conversion ensures different parts of your program can communicate properly, just like converting rupees to euros lets you shop internationally
you must convert the data type yourself using special pre-defined functions like int(), float(), str() or bool() .This explicit conversion makes sure your program works correctly without any issues or errors
Quick Reference: Conversion Functions
| Function | Converts To | Example | Result |
|---|---|---|---|
int() | Integer | int("42") | 42 |
float() | Float | float("3.14") | 3.14 |
str() | String | str(100) | "100" |
bool() | Boolean | bool(1) | True |
The type() Function - Your Data Detective
Now that you know how to convert between different data types, wouldn't it be helpful to have a detective tool that can tell you exactly what type of data you're working with? Meet Python's type() function - your personal data detective! Just like a detective examines evidence to determine what it is, type() investigates your variables/data and reveals their true data type identity
print(type(42)) # Output: <class 'int'>
print(type(3.14)) # Output: <class 'float'>
print(type("Hello")) # Output: <class 'str'>
print(type(True)) # Output: <class 'bool'>Let's Practice Together!
# Run this below code
first_name = "Krishna" # holds string data type in variable 'first_name' with value as 'Krishna'
print("Name: ", first_name) # Observe the print statement : it contains both the fixed text("Name : ") along with Variable(first_name) seperated by comma
age = 10 # holds integer data type in variable 'x' with value 10
print("Age after assignement:", age)
age = 39 # holds integer data type in variable 'x' but and re-assigned with value 39
print("Age after re-assignement:", age)Run this code and observe how the print function displays the contents of a variable - instead of displaying the variable name itself, it shows the data stored within that variable
Quick Recap:
- Variables are like labeled boxes that store values
- Assignment puts values into variables using = sign
- Re-assignment changes what's stored in the same variable
- Data types categorize different kinds of data (numbers, text, true/false)
- Data Type Conversions allow you to change data from one data type to another data type
- type() function is used to identify the data-type of the variable/data
Quick Challenge
Try this yourself:
# Create a simple profile
#Input Statements
your_name = input("What's your Name? ") # Takes the input from User, while taking input it shows the message : What's your name?
your_city = input("Which city are you from? ")
your_age = int(input("What's your age? "))
#Variable Assingment
likes_python = True
#Print Statements
print("\n--- Your Profile ---")
print("Name:", your_name)
print("City:", your_city)
print("Age:", your_age)
print("Next year you'll be:", your_age + 1)
print("Likes Python:", likes_python)Coming Up Next
Now that you know how to store different types of data, in our next lesson we'll learn about how Python handles numbers and mathematical operations