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:
✅ 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:
🎯 Variable Assignment
Single Assignment
Multiple Assignment
Same Value to Multiple Variables
🧪 Variable Data Types
Python automatically detects the data type based on value.
To check data type:
🧩 Changing Variable Values (Reassignment)
🖨️ Using Variables in Print
Or using f-string:
🧠 Variable Scope
🔹 Global Variables
Declared outside functions; can be accessed anywhere.
🔹 Local Variables
Declared inside functions; accessible only inside the function.
🌍 Changing Global Variables Inside a Function
Use global keyword:
📌 Constants in Python
Python does not have true constants, but we use uppercase variable names by convention:
🧱 Dynamic Typing
Python allows variables to change type during execution.
📂 Delete Variable
👨💻 Example Program
🏁 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:
-
Create variables to store name, age, and city, then print them.
-
Assign the same value to three variables.
-
Change the type of a variable at runtime.
-
Use f-string to print:
"My name is John and I am 30."
