In Python, variables are used to store values, and data types define the kind of values stored in variables.
1. What is a Variable?
A variable is like a container that holds data. It allows us to store and reuse values in a program.
Declaring a Variable
In Python, you donβt need to specify the data type. Just assign a value to a variable using =.
name = "Alice" # A string variable
age = 25 # An integer variable
height = 5.8 # A floating-point variable
is_student = True # A boolean variableprint(name) # Output: Alice
print(age) # Output: 25
2. Rules for Naming Variables
- Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
- Cannot start with a number (e.g., 1name is invalid).
- Case-sensitive (name and Name are different).
- Should not use Python keywords like if, for, print, etc.
- Use descriptive names (e.g., student_name instead of s).
my_var = 10 # Valid
_myVar = "Hello" # Valid
2nd_var = 20 # Invalid (cannot start with a number)
class = "Math" # Invalid (class is a Python keyword)
3. Data Types in Python
Python has several built-in data types:
x = 10 # Integer
y = 3.14 # Float
name = "Bob" # String
is_valid = True # Boolean
fruits = ["apple", "banana", "cherry"] # List
person = {"name": "Alice", "age": 25} # Dictionary
4. Checking Data Types
Use the type() function to check the type of a variable.
a = 100
b = 5.5
c = "Hello"
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'str'>
5. Type Casting (Converting Between Data Types)
Python allows converting data from one type to another.
num = 10
num_str = str(num) # Convert integer to string
num_float = float(num) # Convert integer to float
print(num_str) # Output: '10'
print(num_float) # Output: 10.0
print(type(num_str)) # Output: <class 'str'>
print(type(num_float)) # Output: <class 'float'>
Common Conversions:
int(x) β Convert x to an integer
float(x) β Convert x to a float
str(x) β Convert x to a string
Summary
- A variable is a name used to store a value.
- Python supports multiple data types, including numbers, text, lists, and dictionaries.
- Use the type() function to check the type of a variable.
- You can convert data types using int(), float(), and str().