Variables, Data Types & Type Casting
Variables store values in computer memory. In Python, you do not need to declare types upfront—Python detects types automatically at runtime.
What is it?
Python is dynamically typed. A variable is created the moment you first assign a value to it using the `=` assignment operator.
Why is it used?
Stores and manipulates data like user input, financial numbers, status flags, and complex records.
Detailed Explanation
Core Built-in Types:
• `int`: Whole integers (`10`, `-500`, `1000000`)
• `float`: Decimal numbers (`3.14`, `99.95`)
• `str`: Text strings in single or double quotes (`"Python"`)
• `bool`: Boolean `True` or `False` (capitalized in Python!)
• `NoneType`: Represents the absence of a value (`None`)
Type Casting:
Explicitly converting one data type into another:
• `int("2500")` -> `2500`
• `str(42)` -> `"42"`
• `float(10)` -> `10.0`
• Check type with `type(var)`.
Syntax Structure
Syntax Blueprint
variable_name = value
converted = int("100")
print(type(variable_name))
Code Example
PYTHON Code
# Course Pricing & Enrollment Types
course_title = "KLiC Advanced Python"
tuition_fee = 2500 # int
gst_rate = 0.18 # float
is_certified = True # bool (Note capital T)
notes_url = None # NoneType
# Inspect data types
print("Title Type: ", type(course_title))
print("Tuition Type:", type(tuition_fee))
print("Rate Type: ", type(gst_rate))
print("Cert Type: ", type(is_certified))
# Type Casting
raw_input_fee = "2500" # str from form or file
parsed_fee = int(raw_input_fee)
total_with_gst = parsed_fee * (1 + gst_rate)
print(f"Total Fee: ₹{total_with_gst:.2f}")
Explanation of the Code
• Python dynamically infers types for each variable.
• `int(raw_input_fee)` converts the string `"2500"` to a numeric integer so mathematical multiplication can occur.
• `:.2f` inside the f-string formats the float to 2 decimal places.
Expected Output
Title Type: <class 'str'>
Tuition Type: <class 'int'>
Rate Type: <class 'float'>
Cert Type: <class 'bool'>
Total Fee: ₹2950.00
Real-World Application
Used across web backends (Flask/Django) when processing URL query parameters or form submissions which always arrive as strings.
Common Mistakes to Avoid
• Trying to concatenate a string with an integer directly (`"Age: " + 25` throws `TypeError: can only concatenate str to str`). Use f-strings instead!
• Writing `true` or `false` in lowercase (Python requires capitalized `True` and `False`).
Quick Practice Challenge
Take a string `"150"`, convert it into an integer, add 50, and convert it back to a string with a currency prefix.
Key Takeaways
• Python is dynamically typed; variables are created upon assignment.
• Booleans are capitalized: `True` and `False`.
• Always convert input strings with `int()` or `float()` before doing arithmetic.