Topic3:- Python Variables
Python Variables
A variable in Python is a named location used to
store data in memory.
You can think of a variable as a container that holds a value — such as
a number, text, or list - which can change during the execution of a program.
Definition
A variable in Python:
- Is
created when you assign a value to it (no need to declare
explicitly).
- Acts
as a reference to the object (value) stored in memory.
Syntax
variable_name = value
- variable_name
→ name of the variable
- = →
assignment operator
- value
→ the data you want to store
Examples
1. Assigning integer values
x = 10
y = 25
print(x)
print(y)
Output:
10
25
2. Assigning string values
name = "Kavi"
print("Hello,", name)
Output:
Hello, Kavi
3. Assigning float values
pi = 3.14159
print("Value of pi:", pi)
Output:
Value of pi: 3.14159
4. Assigning multiple variables
a, b, c = 5, 10, 15
print(a, b, c)
Output:
5 10 15
5. Assigning same value to multiple variables
x = y = z = 100
print(x, y, z)
Output:
100 100 100
Variable Naming Rules
- Variable
names can contain letters, numbers, and underscores (_).
- They
cannot start with a number.
- Variable
names are case-sensitive (Age, age, and AGE are different).
- Avoid
using Python keywords (like if, while, for, etc.) as variable
names.
Examples of valid variable names:
name, student_age, total_marks, _count
Examples of invalid variable names:
2name, total-marks, class
Example Program
# Program to demonstrate variables
name = "Alice"
age = 21
height = 5.4
print("Age:", age)
print("Height:", height)
Output:
Name: Alice
Age: 21
Height: 5.4
Very useful
ReplyDelete