In Python, variables are used to store data values. Unlike some other programming languages, Python does not require explicit declaration of variables or their data types. Instead, variables are created when you assign a value to them.
Key Concepts of Variables in Python
- Variable Assignment
- Use the
=
operator to assign a value to a variable. Example:
x = 10 name = "Alice"
- Use the
Variable Naming Rules
- Variable names must start with a letter (a-z, A-Z) or an underscore (
_
). - The rest of the name can contain letters, numbers, or underscores.
- Variable names are case-sensitive (
myVar
andmyvar
are different). - Avoid using Python keywords (e.g.,
if
,else
,for
,while
, etc.) as variable names. - Use descriptive names for clarity (e.g.,
user_age
instead ofua
).
Examples of valid variable names:
age = 25 _count = 10 user_name = "Bob" total_amount = 100.50
Examples of invalid variable names:
2nd_place = "John" # Cannot start with a number my-var = 10 # Hyphens are not allowed if = 5 # 'if' is a keyword
- Variable names must start with a letter (a-z, A-Z) or an underscore (
- Dynamic Typing
- Python is dynamically typed, meaning you don't need to declare the type of a variable. The type is inferred from the value assigned.
Example:
x = 10 # x is an integer x = "Hello" # x is now a string
- Multiple Assignments
- You can assign multiple variables in a single line.
Example:
a, b, c = 1, 2, 3 print(a, b, c) # Output: 1 2 3
- Constants
- Python does not have built-in support for constants, but by convention, constants are written in uppercase.
Example:
PI = 3.14159
Example Code
# Variable assignment
name = "Alice"
age = 30
height = 5.5
# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
# Reassigning a variable
age = 31
print("Updated Age:", age)
# Multiple assignments
x, y, z = 10, 20, 30
print("x:", x, "y:", y, "z:", z)
# Swapping variables
x, y = y, x
print("After swapping - x:", x, "y:", y)
Output
Name: Alice
Age: 30
Height: 5.5
Updated Age: 31
x: 10 y: 20 z: 30
After swapping - x: 20 y: 10
Key Points to Remember
- Variables are created when you assign a value to them.
- Python is dynamically typed, so variables can hold values of any type.
- Use meaningful variable names to make your code more readable.
Let me know if you need further clarification or examples!