Beginner
Variables, Data Types, and Type Casting
📂 Phase 1: Python Basics, Variables, Data Types (Days 1–5) · Python ProgrammingPython is dynamically typed — you never declare a variable's type explicitly. The interpreter figures out the type automatically based on the value you assign, and that type can even change later if you reassign the variable to something else.
Declaring Variables
name = "Vishwas"
age = 22
height = 5.9
is_student = True
print(name, age, height, is_student)
There is no let, var, or type keyword — the variable simply springs into existence the moment you assign a value to it.
Python's Core Built-In Data Types
| Type | Example | Description |
|---|---|---|
| int | age = 22 | Whole numbers, positive or negative, no size limit |
| float | height = 5.9 | Decimal (floating-point) numbers |
| str | name = "Vishwas" | Text, written in single or double quotes |
| bool | is_active = True | True or False (note the capital letters) |
| complex | z = 3 + 4j | Complex numbers with a real and imaginary part |
Checking a Variable's Type
x = 10
y = 3.14
z = "hello"
print(type(x)) #
print(type(y)) #
print(type(z)) #
Dynamic Typing in Action
value = 100 # value is currently an int
print(type(value)) #
value = "one hundred" # now it's a string — Python allows this freely
print(type(value)) #
This flexibility is convenient, but it also means typos and unintended reassignments can introduce bugs that a statically typed language like Java would have caught at compile time.
Naming Rules for Variables
- Must start with a letter or underscore (never a digit)
- Can contain letters, digits, and underscores — no spaces or special characters
- Case-sensitive:
ageandAgeare different variables - Convention:
snake_casefor variables (total_marks, nottotalMarksas in Java)
Type Casting — Converting Between Types
Since input() always returns a string, you frequently need to convert it before doing math:
age_text = input("Enter your age: ") # always a string
age_number = int(age_text) # explicit cast to int
print(age_number + 5) # works — proper integer math
# print(age_text + 5) # would raise a TypeError — can't add str + int
Common Casting Functions
| Function | Converts To | Example |
|---|---|---|
| int() | Integer | int("25") → 25 |
| float() | Floating-point | float("3.14") → 3.14 |
| str() | String | str(42) → "42" |
| bool() | Boolean | bool(0) → False, bool(1) → True |
Interview tip: Be ready to explain why bool(0) is False but bool("0") is True — an empty string, 0, 0.0, and None are all "falsy," but a non-empty string like "0" is truthy simply because it is a non-empty string, regardless of what text it contains.