Python Variables
A variable is a name used to store a value in a Python program. Python does not require a variable to be declared with a data type before assigning a value. The type is determined automatically from the value.
Creating a Variable
A variable is created using the assignment operator =.
name = "Rahul"
age = 20
marks = 85.5
print(name)
print(age)
print(marks)
Rahul 20 85.5
Dynamic Typing
Python is dynamically typed. A variable can refer to values of different types during program execution.
x = 10
print(x)
x = "Python"
print(x)
10 Python
Multiple Variable Assignment
Multiple variables can be assigned values in a single statement.
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
10 20 30
Same Value to Multiple Variables
x = y = z = 100
print(x, y, z)
100 100 100
Variable Naming Rules
- A variable name can contain letters, digits and underscore.
- A variable name cannot start with a digit.
- Spaces are not allowed in variable names.
- Special characters such as
@,#and$are not allowed. - 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
Variables can store different types of values such as integers, floating-point numbers, strings and Boolean values.
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 a Variable Value
The value of a variable can be changed by assigning a new value.
score = 50
print(score)
score = 80
print(score)
50 80
Variables in Expressions
Variables can be used in mathematical expressions and calculations.
a = 10
b = 20
sum_value = a + b
product = a * b
print("Sum =", sum_value)
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
Local and Global Variables
A variable created inside a function is generally called a local variable. A variable created outside a function is generally called a global variable.
x = 10
def display():
y = 20
print(x)
print(y)
display()
10 20
Constants
Python does not provide a special keyword for constants. By convention, constant names are written in uppercase letters.
PI = 3.14159
MAX_MARKS = 100
print(PI)
print(MAX_MARKS)
Checking Variable Type
The type() function returns the data type of a variable.
value = 25
print(type(value))
<class 'int'>