Python Variables
A variable is a name used to store a value in a Python program. Python variables are created when a value is assigned to a name. No separate declaration of the variable type is required.
Creating a Variable
The assignment operator = is used to assign a value to a variable.
name = "Rahul"
age = 20
marks = 85.5
print(name)
print(age)
print(marks)
Rahul 20 85.5
Dynamic Typing in Python
Python is a dynamically typed language. A variable does not need a fixed data type. Its type is determined automatically from the value assigned to it.
x = 10
print(x)
x = "Python"
print(x)
10 Python
Multiple Variable Assignment
Python allows multiple variables to be assigned values in a single statement.
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
10 20 30
Assigning the Same Value to Multiple Variables
x = y = z = 100
print(x)
print(y)
print(z)
100 100 100
Variable Naming Rules
Variables follow the same rules as Python identifiers.
- A variable name can contain letters, digits and underscore.
- It cannot start with a digit.
- Spaces are not allowed in variable names.
- Python keywords cannot be used as variable names.
- Variable names are case-sensitive.
student_name = "Amit"
age2 = 21
_total = 500
Case-Sensitive Variables
Python treats uppercase and lowercase letters as different.
name = "Rahul"
Name = "Amit"
print(name)
print(Name)
Rahul Amit
Variables and Data Types
A variable can store different types of values such as integers, floating-point numbers, strings, Boolean values and collections.
age = 20
price = 99.50
name = "Python"
passed = True
print(type(age))
print(type(price))
print(type(name))
print(type(passed))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
Changing the Value of a Variable
The value stored in a variable can be changed by assigning a new value.
score = 50
print(score)
score = 80
print(score)
50 80
Using Variables in Expressions
Variables can be used in mathematical expressions and calculations.
a = 10
b = 20
sum = a + b
product = a * b
print("Sum =", sum)
print("Product =", product)
Sum = 30 Product = 200
Deleting a Variable
The del keyword can be used to remove a variable.
x = 10
print(x)
del x
After del x, the variable x no longer exists.
Constants in Python
Python does not have a special keyword for declaring constants. By convention, names written in uppercase are used to indicate values that should not normally be changed.
PI = 3.14159
MAX_MARKS = 100
print(PI)
print(MAX_MARKS)
Local and Global Variables
A variable created inside a function is generally a local variable. A variable defined outside a function is generally a global variable.
x = 10
def display():
y = 20
print(x)
print(y)
display()
10 20
Checking the Type of a Variable
The type() function is used to determine the data type
of a variable.
value = 25
print(type(value))
<class 'int'>