Python - Variable

      

🧠 Python Variables (in Python)

A variable is a name used to store data in memory.


Creating a variable

In Python, you don’t need to declare a type.

x = 10

name = "Shivam"

price = 99.5

👉 Python automatically understands the data type.

🔹 Rules for variable names

✔ Must start with a letter or _
✔ Can contain letters, numbers, _
❌ Cannot start with a number
❌ Cannot use keywords like if, for, class

✔ Valid

age = 25

_user = "abc"

total_amount = 100


❌ Invalid

1name = "abc"   # ❌

class = 10      # ❌ keyword


🔹 Assigning multiple variables

a, b, c = 1, 2, 3


🔹 Changing value (dynamic typing)

x = 10

x = "Hello"   # type changed automatically

🔹 Check type

x = 10

print(type(x))   # <class 'int'>

🔹 Variable types (basic)

a = 10        # int

b = 3.14      # float

c = "Hello"   # string

d = True      # boolean

⚠️ Common mistakes

x = 10

print(X)   # ❌ Python is case-sensitive

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:


Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "Raj"

Pascal Case

Each word starts with a capital letter:

MyVariableName = "Raj"

Snake Case

Each word is separated by an underscore character:

my_variable_name = "Raj"


🧠 Variables store references, not actual data

In Python, a variable doesn’t directly hold the value — it points to an object in memory.


🧠 Variables store references, not actual data

In Python, a variable doesn’t directly hold the value — it points to an object in memory.

a = 10

b = 10

print(id(a))

print(id(b))

👉 Often, both a and b will have the same memory address
(because Python reuses small integers)

🔹 Assigning one variable to another

x = [1, 2, 3]

y = x

👉 Now:

  • x and y point to same object in memory
print(id(x))
print(id(y))

✔ Same address

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence