Python Variables

🔤 Python Variables

A variable in Python is a name that stores data in memory. The data stored in a variable can be used, updated, or processed later in the program.

Python variables are created automatically when you assign a value:

name = "Vipul"
age = 25

✅ Why Variables?

Variables help you:

  • Store values

  • Reuse values

  • Change values dynamically

  • Make programs interactive


🧠 Rules for Naming Variables

✔ Can contain letters, numbers, and underscores
✔ Must start with a letter or underscore
✔ Cannot start with a number
✔ Cannot contain spaces
✔ Case-sensitive

Valid Names Invalid Names
student_name 123name ❌
age1 name-age ❌
_total my salary ❌

Example:

name = "John"
Name = "David" # Different from name
print(name, Name)

🎯 Variable Assignment

 Single Assignment

x = 10

 Multiple Assignment

a, b, c = 10, 20, 30
print(a, b, c)

 Same Value to Multiple Variables

x = y = z = 100

🧪 Variable Data Types

Python automatically detects the data type based on value.

x = 10 # int
y = 10.5 # float
name = "Raj" # string
isActive = True # boolean

To check data type:

print(type(x))

🧩 Changing Variable Values (Reassignment)

x = 10
print(x)
x = 50 # value changed
print(x)

🖨️ Using Variables in Print

name = "Vipul"
print("My name is", name)

Or using f-string:

print(f"My name is {name}")

🧠 Variable Scope

🔹 Global Variables

Declared outside functions; can be accessed anywhere.

x = 10

def demo():
print(x)

demo()

🔹 Local Variables

Declared inside functions; accessible only inside the function.

def test():
a = 5
print(a)
test()
# print(a) ❌ gives error

🌍 Changing Global Variables Inside a Function

Use global keyword:

x = 10

def update():
global x
x = 20

update()
print(x) # Output: 20


📌 Constants in Python

Python does not have true constants, but we use uppercase variable names by convention:

PI = 3.14
MAX_SPEED = 120

🧱 Dynamic Typing

Python allows variables to change type during execution.

x = 10
print(type(x))
x = “Hello”
print(type(x))

📂 Delete Variable

x = 100
del x
# print(x) -> Error

👨‍💻 Example Program

# storing user details
name = "Vipul"
age = 25
is_student = False
print(f”Name: {name}“)
print(f”Age: {age}“)
print(f”Student: {is_student}“)

🏁 Summary Table

Feature Example
Create variable x = 10
Multiple variables a, b = 1, 2
Same value assignment x = y = 5
Check type type(x)
Change value x = "Hello"
Delete variable del x
Global variable global x

🚀 Practice Questions

Try these:

  1. Create variables to store name, age, and city, then print them.

  2. Assign the same value to three variables.

  3. Change the type of a variable at runtime.

  4. Use f-string to print: "My name is John and I am 30."

You may also like...