Python Variables
A variable is the name given to a memory location. A value-holding Python variable is also known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters and digits.
How to Create a Variable
To begin with, let’s state that the assignment of a variable with an equal sign(=) is carried out within the set of constructs in Python.
x = 10 # Here we are declaring variable x and assigning it the value 10.
name = "Alice" # Here we are declaring a variable called name and assigning it the value Alice.
Rules for Naming Variables
1. Start with a letter or an underscore:
- Allowed:
name
,_name
- Not allowed:
1name
,@name
2. It can contain letters, numbers and underscores:
- Examples:
user_name
,age1
3. No spaces or special characters:
- Use underscores
_
in place of spaces.
4. Case-sensitive:
Name
andname
are different variables
5. Don’t use Python reserved keywords:
- Keywords like
if
,else
,while
, etc, cannot be used as variable names.
Assigning Values to Variables
You can give any type of value to a variable:
Numbers
age = 25 # Integer
height = 5.9 # Float
Strings (Text)
greeting = "Hello, world!"
Boolean (True or False)
is_active = True
Lists (Collection of items)
colors = ["red", "green", "blue"]
Other Data Types
Python also supports more complex data types like dictionaries, tuples, etc.
Changing Variable Values
One can change a variable’s value in the script by simply reassigning it:
x=10 # x is initially 10
x=20 # x is now 20
Dynamic Typing
- Python is dynamically typed, which means you don’t need to declare the type of a variable. It can change its type during the program’s execution.
code x = 10 # x is an integer
x = "Python" # Now x is a string
Multiple Variable Assignments
- Assigning the same value to multiple variables:
a = b = c = 5
- Assigning different values to multiple variables in one line:
x, y, z = 1, 2, 3
Printing Variable Values
Use the print()
to display the value of a variable:
name = "Alice"
print(name) # Output: Alice
Why Variables Are Useful
- Reusability: Use the same variable throughout the program.
- Readability: Makes your code more understandable.
- Flexibility: Change the value without altering the rest of the code.
Best Practices for Variables
1. Use meaningful names:
- Bad:
x = 25
- Good:
age = 25
2. Stick to lowercase for simple variable names (snake_case
is common in Python):
- Example:
user_name
,total_score
3. Avoid overly long names but make them descriptive:
- Good:
average_temperature
- Too long:
the_average_temperature_of_today_in_city
Example: Variables in Action
# Storing a person's details
name = "Alice"
age = 30
is_member = True
# Displaying details
print("Name:", name)
print("Age:", age)
print("Membership Status:", is_member)
# Updating age
age = 31
print("Updated Age:", age)