Variables in Python
What is a Variable? A variable is a named location in memory that stores a value. In Python, we can assign values to variables using the assignment operator =. The value of a variable can be changed later in the program.
Creating Variables
Python
x = 10 # integer name = "Ashish" # string price = 99.99 # float is_valid = True # boolean
- x stores an integer 10.
- name stores a string "Ashish".
- price stores a float 99.99.
- is_valid stores a boolean True.
Note: In Python you don’t need to declare variables before using it, unlike other languages like Java, C etc.
Variable Naming Rules
- Can contain letters (uppercase or lowercase), numbers, and underscores (_).
- Must start with a letter or an underscore (not a number).
- Variable names are case-sensitive (
Name
andname
are different). - Cannot use reserved keywords (like
class
,def
,if
, etc.). - Never use special symbols such as
!
,@
,#
,$
,%
, etc. - Whitespace is not allowed inside a variable name.
Example:
Python
age = 25 # valid _age = 30 # valid my_name = "Sam" # valid 2price = 100 # ❌ invalid class = "test" # ❌ invalid (keyword)
Re-declare the Variable In Python, re-declaring a variable typically means assigning a new value to an existing variable. Since Python is dynamically typed, you don’t need to explicitly declare the type of variable, so re-declaring it is just reassigning a new value.
Example: Changing the value of a variable.
Python
# Initial declaration x = 10 print(x) # Output: 10 # Re-declare the variable by assigning a new value x = 20 print(x) # Output: 20 # Re-declare with a different type (Python allows this because it's dynamically typed) x = "Now I'm a string" print(x) # Output: Now I'm a string
Multiple Assignments In Python, we can assign values to multiple variables in a single line.
a) Assigning different values to multiple variables: Python allows adding different values in a single line with “,” operators. We can assign multiple values at once.
Example:
Python
a, b, c = 10, 20, 30 print(a, b, c) # 10 20 30
b) Assigning a same value to multiple variables: Also, Python allows assigning a single value to several variables simultaneously with “=” operators.
Example:
Python
x = y = z = 100 print(x, y, z) # 100 100 100
Deleting Variables We can delete a variable using del:
Python
x = 50 del x # print(x) # ❌ Error: x is not defined
Checking Variable Type We can use the type() function:
Example:
Python
x = 10 print(type(x)) #y = "Hello" print(type(y)) #