🐍
Syllabus / Python Programming / Phase 1: Python Basics, Variables, Data Types (Days 1–5)
Beginner

Variables, Data Types, and Type Casting

📂 Phase 1: Python Basics, Variables, Data Types (Days 1–5) · Python Programming

Python 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

TypeExampleDescription
intage = 22Whole numbers, positive or negative, no size limit
floatheight = 5.9Decimal (floating-point) numbers
strname = "Vishwas"Text, written in single or double quotes
boolis_active = TrueTrue or False (note the capital letters)
complexz = 3 + 4jComplex 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: age and Age are different variables
  • Convention: snake_case for variables (total_marks, not totalMarks as 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

FunctionConverts ToExample
int()Integerint("25") → 25
float()Floating-pointfloat("3.14") → 3.14
str()Stringstr(42) → "42"
bool()Booleanbool(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.