Python Variables
Variables in Python are used to store data values.
Python creates a variable at the moment you assign a value to it, which makes variable handling simple and flexible.
Creating Variables
In Python, variables are created without declaring a data type.
You just assign a value using the
= operator.Python automatically determines the type of the variable.
Code Example 1: Creating Variables
python
x = 10
name = "Python"
price = 99.99
Code Example 2: Reassigning Variables
python
x = 5
x = 20
print(x)
Code Example 3: Multiple Variables
python
a, b, c = 1, 2, 3
print(a, b, c)
Key Point
Python variables are dynamically typed.
Casting
Casting means specifying a data type for a variable.
Python allows you to convert values from one type to another.
Common casting functions:
int()float()str()
Code Example 1: Integer Casting
python
x = int(10.5)
print(x)
Code Example 2: Float Casting
python
y = float(5)
print(y)
Code Example 3: String Casting
python
z = str(100)
print(z)
Important
Casting helps control how data is stored and processed.
Get the Type
Python provides the
type() function to check the data type of a variable.This is useful for debugging and learning.
Code Example 1: Check Integer Type
python
x = 10
print(type(x))
Code Example 2: Check String Type
python
name = "Python"
print(type(name))
Code Example 3: Check Float Type
python
price = 19.99
print(type(price))
Single or Double Quotes?
In Python, strings can be created using single quotes (' ') or double quotes (" ").
Both are treated the same by Python.
Use double quotes when the string contains single quotes.
Code Example 1: Single Quotes
python
text = 'Hello Python'
print(text)
Code Example 2: Double Quotes
python
text = "Hello Python"
print(text)
Code Example 3: Mixed Quotes
python
text = "Python is a 'high-level' language"
print(text)
Best Practice
Be consistent with quote style throughout your code.
Case-Sensitive
Python is a case-sensitive language.
This means variable names with different letter cases are treated as different variables.
Code Example 1: Case Sensitivity
python
age = 25
Age = 30
print(age)
print(Age)
Code Example 2: Invalid Assumption
python
value = 10
# print(Value) # This will cause an error
Code Example 3: Recommended Naming Style
python
user_name = "Admin"
print(user_name)
Caution
Always use consistent naming to avoid confusion and errors.
Summary
- Variables store data values
- Created automatically on assignment
- Casting converts data types
type()checks variable type- Strings support single and double quotes
- Python is case-sensitive
Exercise
- Create variables of different types
- Convert one type into another using casting
- Use
type()to verify the result