Variables
Variables are containers for storing data values. Variables in Python are used to store data values. They act as containers for storing data that can be referenced and manipulated later in a program
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
1. Declaring a Variable
In Python, you do not need to explicitly declare the data type of a variable. Python automatically assigns the data type based on the value you provide.
Example:
x = 5 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
2. Variable Naming Rules
Must begin with a letter (a-z, A-Z) or an underscore (_).
Cannot start with a digit.
Can only contain alphanumeric characters and underscores (A-Z, a-z, 0-9, _).
Case-sensitive (age and Age are different variables).
Cannot be a Python keyword (e.g., if, for, while, class, etc.).
3. Valid variable names:
name = "John"
_age = 25
user1 = "Alice"
Invalid variable names:
1name = "Error" # Cannot start with a digit
user-name = "Error" # Hyphens are not allowed
class = "Error" # 'class' is a reserved keyword
4. Reassigning Variables
Variables in Python can change their type dynamically.
x = 10 # Initially an integer
x = "Hello" # Now a string
x = 3.14 # Now a float
5. Assigning Multiple Variables
You can assign values to multiple variables in one line.
# Assigning the same value:
a = b = c = 10
# Assigning different values:
x, y, z = 1, 2, "Three"
6. Data Types of Variables
Some common data types in Python are:
int: Integer numbers (e.g., 1, -10)
float: Decimal numbers (e.g., 3.14, -2.5)
str: Strings of text (e.g., "Hello", 'Python')
bool: Boolean values (True, False)
You can check the data type of a variable using the type() function:
age = 25
print(type(age)) # <class 'int'>
7. Best Practices for Variables
Use descriptive names that make your code easy to understand.
Follow a consistent naming convention (e.g., snake_case).
Avoid using single letters except in temporary or loop variables.
8. Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
0 Comments:
Post a Comment