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."
