Variables are fundamental to any programming language, allowing you to store and manipulate data. In Python, variables are dynamically typed, which means you don’t have to specify the type when declaring them.
A variable is a name that refers to a value stored in the memory of your program. It acts as a label for the data you want to work with.
x = 10 # x is a variable holding the integer value 10
y = "Hello, World!" # y is a variable holding a string value
Variable names in Python must follow certain rules and conventions to be valid and readable.
Must start with a letter or an underscore (_):
name
, _name
1name
, @name
Can contain letters, digits, and underscores:
name1
, user_name
user-name
, user name
Cannot be a Python keyword:
if
, for
, while
Case-sensitive:
Name
and name
are treated as two different variables.age = 25 # Good
a = 25 # Bad
first_name = "Alice" # Recommended
firstName = "Alice" # Avoid in Python
In Python, you don’t need to declare the type of a variable explicitly. The type is inferred from the assigned value.
# Integer
x = 10
# String
y = "Hello"
# Float
z = 3.14
# Boolean
is_active = True
Python allows variables to be reassigned to a value of a different type during the program execution. This is because Python is dynamically typed.
x = 10
x = "Now I am a string!"
print(x) # Output: Now I am a string!
Although Python does not have built-in support for constants, developers use naming conventions to indicate variables that should not change.
PI = 3.14159 # A constant (by convention, use uppercase names)
GRAVITY = 9.8
Note: Python does not enforce immutability for constants.
Objective: Write a Python script to practice declaring and using variables with proper naming conventions.
Create a Python File:
Create a file named variables_practice.py
.
Declare Variables: Declare variables to store your name, age, and a floating-point number representing your height.
Example:
name = "Alice"
age = 30
height = 5.5
Print Variables: Print the values of these variables using meaningful messages.
Example:
print("Name:", name)
print("Age:", age)
print("Height:", height)
Reassign Values: Reassign one of the variables with a new value of a different type and print the updated value.
Example:
age = "Thirty"
print("Updated Age:", age)
Define Constants: Define two constants using uppercase variable names and print their values.
Example:
SPEED_OF_LIGHT = 299792458 # meters per second
PLANCK_CONSTANT = 6.62607015e-34 # m^2 kg / s
print("Speed of Light:", SPEED_OF_LIGHT)
print("Planck Constant:", PLANCK_CONSTANT)
Understanding variables and their naming conventions is the first step toward writing clean, maintainable Python code. Next, we’ll explore data types to understand the kind of values variables can store.