Variables and Data Types
# Variables and Data Types
Welcome to Chapter 4! Variables are the building blocks of every program. They store data that your program manipulates. In this chapter, you'll learn how Python handles variables and its fundamental data types.
---
1. Introduction
Every program works with data — names, ages, prices, temperatures, and more. Variables are containers that hold this data in memory so your program can use and manipulate it. Python makes working with variables incredibly simple compared to other languages.
Real-World Analogy
Think of variables as labeled boxes in a warehouse:---
2. Learning Objectives
By the end of this chapter, you will be able to:
- Create and use variables in Python.
-
Understand Python's core data types:
int,float,str,bool.
- Explain dynamic typing.
- Perform type conversion (casting).
-
Use the
type()andid()functions.
- Understand variable naming conventions.
---
3. Variables in Python
Creating Variables
In Python, you create a variable by simply assigning a value using=:
```python id="py4ex1" # Creating variables — no type declaration needed! name = "Alice" age = 25 height = 5.6 isstudent = True
print(name) # Alice print(age) # 25 print(height) # 5.6 print(is_student) # True
python id="py4_ex2" x = 10 # x is an integer print(type(x)) # <class 'int'>
x = "Hello" # Now x is a string! print(type(x)) # <class 'str'>
x = 3.14 # Now x is a float! print(type(x)) # <class 'float'>
python id="py4_ex3" # Assign multiple variables at once a, b, c = 1, 2, 3 print(a, b, c) # 1 2 3
# Assign same value to multiple variables x = y = z = 0 print(x, y, z) # 0 0 0
# Swap variables (Pythonic way!) a, b = 10, 20 a, b = b, a print(a, b) # 20 10
python id="py4ex4" # ✅ Good — snakecase for variables and functions studentname = "Alice" totalmarks = 95 ispassed = True
# ❌ Bad — avoid these styles studentName = "Alice" # camelCase (used in Java, not Python) StudentName = "Alice" # PascalCase (used for classes only) STUDENTNAME = "Alice" # ALL CAPS (used for constants only)
# Constants (by convention, use ALL CAPS) MAXSPEED = 120 PI = 3.14159 DATABASE_URL = "localhost:5432"
python id="py4_ex5" import keyword print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Python Data Type Hierarchy: ┌─────────────────────────────────────────┐ │ Python Data Types │ ├─────────────┬─────────────┬─────────────┤ │ Numeric │ Sequence │ Other │ │ • int │ • str │ • bool │ │ • float │ • list │ • None │ │ • complex │ • tuple │ • dict │ │ │ │ • set │ └─────────────┴─────────────┴─────────────┘
python id="py4ex6" age = 25 temperature = -10 population = 8000000000 binary = 0b1010 # Binary: 10 octal = 0o17 # Octal: 15 hexadecimal = 0xFF # Hexadecimal: 255
print(age) # 25 print(population) # 8000000000 print(binary) # 10 print(hexadecimal) # 255 print(type(age)) # <class 'int'>
# Python ints have unlimited size! bignumber = 99999999999999999999999999999999 print(big_number) # Works perfectly!
python id="py4_ex7" price = 19.99 pi = 3.14159 negative = -0.5 scientific = 2.5e4 # 25000.0
print(price) # 19.99 print(scientific) # 25000.0 print(type(price)) # <class 'float'>
# ⚠️ Floating-point precision issue print(0.1 + 0.2) # 0.30000000000000004 (not 0.3!) print(0.1 + 0.2 == 0.3) # False!
# Fix with round() print(round(0.1 + 0.2, 1)) # 0.3
python id="py4_ex8" # Single quotes name = 'Alice'
# Double quotes greeting = "Hello, World!"
# Triple quotes (multi-line) message = """This is a multi-line string."""
# String operations print(len(name)) # 5 print(name.upper()) # ALICE print(name.lower()) # alice print(greeting[0]) # H (first character) print(greeting[-1]) # ! (last character) print(type(name)) # <class 'str'>
python id="py4ex9" isactive = True isdeleted = False
print(isactive) # True print(type(is_active)) # <class 'bool'>
# Booleans from comparisons print(10 > 5) # True print(10 < 5) # False print(10 == 10) # True
# Boolean as numbers (True = 1, False = 0) print(True + True) # 2 print(True * 10) # 10 print(False + 5) # 5
python id="py4_ex10" result = None
print(result) # None print(type(result)) # <class 'NoneType'>
# Common usage: default function return def greet(): print("Hello!")
x = greet() print(x) # None (functions return None if no return statement)
python id="py4ex11" name = "Alice" age = 25 height = 5.6 isstudent = True
print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> print(type(height)) # <class 'float'> print(type(is_student)) # <class 'bool'>
# isinstance() — check if variable is of a specific type print(isinstance(age, int)) # True print(isinstance(name, str)) # True print(isinstance(age, float)) # False
python id="py4ex12" # String to Integer agestr = "25" ageint = int(agestr) print(ageint + 5) # 30
# Integer to Float x = float(10) print(x) # 10.0
# Float to Integer (truncates decimal) y = int(3.99) print(y) # 3 (not 4 — it truncates, doesn't round!)
# Number to String price = 19.99 pricestr = str(price) print("Price: $" + price_str) # Price: $19.99
# String to Float height = float("5.6") print(height + 1) # 6.6
# Integer to Boolean print(bool(0)) # False print(bool(1)) # True print(bool(-5)) # True (any non-zero number is True) print(bool("")) # False (empty string is False) print(bool("Hi")) # True (non-empty string is True)
python id="py4_ex13" # id() returns the memory address of a variable a = 10 b = 10
print(id(a)) # e.g., 140234567890 print(id(b)) # Same as a! (Python reuses memory for small ints)
# is vs == print(a == b) # True (same value) print(a is b) # True (same object in memory)
c = [1, 2, 3] d = [1, 2, 3] print(c == d) # True (same value) print(c is d) # False (different objects in memory)
Memory Visualization: Variable 'a' ───┐ ├──→ [10] at address 0x7f12 Variable 'b' ───┘
Variable 'c' ──→ [1, 2, 3] at address 0x8a34 Variable 'd' ──→ [1, 2, 3] at address 0x8b56 (different!)
python id="py4ex14" # Student profile using different data types studentname = "Rahul Sharma" # str studentage = 20 # int studentgpa = 3.75 # float isenrolled = True # bool scholarship = None # NoneType
print(f"Name : {studentname}") print(f"Age : {studentage}") print(f"GPA : {studentgpa}") print(f"Enrolled : {is_enrolled}") print(f"Scholar : {scholarship}")
python id="py4_ex15" # Celsius to Fahrenheit celsius = 37.5 fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F") # Output: 37.5°C = 99.5°F
python id="py4ex16" values = [42, 3.14, "Hello", True, None, [1, 2], (3, 4), {"a": 1}]
for val in values: print(f"Value: {str(val):15} | Type: {type(val).name_}")
Value: 42 | Type: int
Value: 3.14 | Type: float
Value: Hello | Type: str
Value: True | Type: bool
Value: None | Type: NoneType
Value: [1, 2] | Type: list
Value: (3, 4) | Type: tuple
Value: {'a': 1} | Type: dict
``
---
9. Common Mistakes
- 1. Concatenating string with number without conversion:
python
age = 25
print("Age: " + age) # ❌ TypeError!
print("Age: " + str(age)) # ✅ Correct
print(f"Age: {age}") # ✅ Even better
`
-
2.
Floating-point comparison:
`python
print(0.1 + 0.2 == 0.3) # ❌ False!
print(round(0.1 + 0.2, 1) == 0.3) # ✅ True
`
-
3.
Using reserved words as variable names:
`python
list = [1, 2, 3] # ❌ Shadows the built-in list()
mylist = [1, 2, 3] # ✅ Correct
`
-
4.
Assuming
int() rounds: int(3.99) gives 3, not 4. It truncates.
---
10. Best Practices
-
Use descriptive variable names:
studentcount instead of sc.
-
Use snakecase for variables and functions.
-
Use ALLCAPS for constants:
MAXSIZE = 100.
-
Use f-strings for string formatting (Python 3.6+).
-
Avoid shadowing built-in names like
list, dict, str, type.
---
11. Exercises
-
1.
Create variables for your name, age, height, and whether you like Python.
-
2.
Write a program that swaps two variables without using a third variable.
-
3.
Convert a temperature from Fahrenheit to Celsius using the formula:
C = (F - 32) × 5/9.
-
4.
Create a program that shows the type and memory id of 5 different variables.
-
5.
Write a program that concatenates your first and last name using three different methods.
---
12. MCQs with Answers
Q1: What is the type of
x = 10?
A) float B) str C) int D) bool
Answer: C
Q2: What does
type(3.14) return?
A) <class 'int'> B) <class 'float'> C) <class 'str'> D) <class 'decimal'>
Answer: B
Q3: What is the result of
int(4.9)?
A) 5 B) 4 C) 4.9 D) Error
Answer: B — int() truncates, it doesn't round.
Q4: Which naming convention does PEP 8 recommend for variables?
A) camelCase B) PascalCase C) snake
case D) UPPERCASE
Answer: C
Q5: What is bool("")?
A) True B) False C) None D) Error
Answer: B — An empty string is falsy.
Q6: How do you check a variable's type?
A) typeof(x) B) type(x) C) class(x) D) check(x)
Answer: B
Q7: What does None represent?
A) Zero B) Empty string C) Absence of value D) False
Answer: C
Q8: Which is a valid variable name?
A) 2name B) my-var C)
D) class
Answer: C
Q9: What is the output of
True + True + False?
A) True B) 3 C) 2 D) 1
Answer: C — True=1, False=0, so 1+1+0=2
Q10: What is dynamic typing?
A) Variables must be declared with types B) Variables can change type at runtime C) Types are checked at compile time D) Types are immutable
Answer: B
---
13. Interview Questions
-
1.
What is dynamic typing in Python?
*Answer:* Dynamic typing means variables don't have fixed types. A variable can hold an integer, then be reassigned to hold a string. The type is determined at runtime.
-
2.
What is the difference between
is and ==?
*Answer:* == checks value equality (do they have the same value?). is checks identity equality (do they point to the same object in memory?).
-
3.
Why does
0.1 + 0.2 != 0.3 in Python?
*Answer:* Due to IEEE 754 floating-point representation, some decimal numbers cannot be represented exactly in binary. Use round() or the decimal module for precise calculations.
-
4.
What are Python's mutable vs immutable types?
*Answer:* Immutable: int, float, str, bool, tuple. Mutable: list, dict, set. Immutable objects cannot be changed after creation.
-
5.
What is None in Python?
*Answer:* None is Python's null equivalent. It represents the absence of a value and is the default return value of functions without a return statement.
---
14. FAQs
Q: Can Python integers overflow?
A: No! Python integers have arbitrary precision — they can be as large as your memory allows. This is unlike Java or C where int has a fixed size.
Q: When should I use
float vs int?
A: Use int for whole numbers (counts, indices, ages). Use float for decimal values (prices, measurements, percentages).
Q: What is the difference between
' and " for strings?
A: No difference in Python. Use whichever you prefer, but be consistent. Use one inside the other to avoid escaping: "It's Python" or 'He said "Hi"'.
---
15. Summary
-
Variables store data in memory and are created with
= assignment.
-
Python has dynamic typing — variables can change type.
-
Core data types: int (whole numbers), float (decimals), str (text), bool (True/False), None.
-
Use
type() to check types and casting functions (int(), float(), str()) to convert.
-
Follow PEP 8 naming conventions: snakecase for variables, ALLCAPS for constants.
-
The
is operator checks identity; ==` checks equality.
---
16. Next Chapter Recommendation
Now that you understand variables and data types, it's time to learn how to operate on them! In Chapter 5: Operators in Python, you'll master arithmetic, comparison, logical, assignment, membership, and identity operators. Let's go! 🚀