Using Variables in Python
1. Declaring Variables
In Python, you simply assign a value to a variable using the equals ( = ) sign.
a = 5 # Integer
b = 3.14 # Float
c = 'Hello' # String
d = True # Boolean
2. Naming Conventions
Variable names should start with a letter (a-z, A-Z) or an underscore ( _ ).
Subsequent characters can include letters, digits (0-9), and underscores.
Variable names are case-sensitive (
age
andAge
are different variables).my_variable = 10 _myVariable = 20 variable3 = 30
3. Using Variables
You can use variables in various operations and expressions.
# Arithmetic operations
x = 10
y = 20
sum = x + y # Addition
difference = x - y # Subtraction
product = x * y # Multiplication
quotient = x / y # Division
# Using variables in strings
name = "Alice"
greeting = "Hello, " + name + "!"
print(greeting)
4. Updating Variables
Variables can be updated by reassigning them new values.
5. Data Types and Type Conversion
Python variables can hold different types of data, and you can convert between types.
6. Working with Lists and Dictionaries
Variables can also store collections like lists and dictionaries.
7. Variable Scope
Variables have different scopes depending on where they are declared. There are local and global variables.
8. Best Practices
Use meaningful variable names for better code readability.
Follow the Python style guide (PEP 8) for naming conventions (e.g.,
snake_case
for variable names).
Example Script
Here’s a simple example script that uses variables: