Variables in Python
A variable is a name that refers to a value stored in memory. In Python, you create a variable simply by assigning a value to a name using the equals sign (=).
Python is dynamically typed, meaning you do not need to declare the type of a variable — Python determines the type automatically based on the value you assign.
Example
# Creating variables — no type declaration needed
name = "Alice"
age = 25
height = 5.7
is_student = True
print(name) # Alice
print(age) # 25
print(height) # 5.7
print(is_student) # True - Variable names must start with a letter or underscore, not a number
- Variable names are case-sensitive: 'age' and 'Age' are different variables
- Use snake_case for variable names in Python (e.g., my_variable, user_name)
- Avoid using Python reserved words like 'if', 'for', 'class', 'return' as variable names
Try Creating Variables
JavaScript
# Create your own variables
name = "Alice"
age = 25
height = 5.7
is_student = True
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Student:", is_student) Notes
- Python variables are references to objects in memory. When you reassign a variable, you're changing which object it points to, not modifying the object itself.
Core Data Types and Type Casting
Python has several built-in data types. The four most common primitive types are int (integers), float (decimal numbers), str (strings), and bool (True/False).
You can check the type of any value using the type() function, and convert between types using type casting functions like int(), float(), str(), and bool().
Example
# Core data types
x = 10 # int — whole numbers
y = 3.14 # float — decimal numbers
name = "Python" # str — text
active = True # bool — True or False
# Check types with type()
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(active)) # <class 'bool'>
# Type casting
num_str = "42"
num_int = int(num_str) # Convert string to int
num_float = float(num_str) # Convert string to float
back_to_str = str(num_int) # Convert int to string
print(num_int) # 42
print(num_float) # 42.0
print(back_to_str) # "42" - int: Whole numbers like 1, -5, 1000 (no size limit in Python)
- float: Decimal numbers like 3.14, -0.5, 2.0
- str: Text enclosed in single or double quotes like 'hello' or "hello"
- bool: Only two values — True or False (capitalized)
- NoneType: The special value None represents the absence of a value
Try Type Casting
JavaScript
# Experiment with types and casting
num_str = "42"
num_int = int(num_str)
num_float = float(num_str)
print("Original:", num_str, type(num_str))
print("As int:", num_int, type(num_int))
print("As float:", num_float, type(num_float))
# Bool casting
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("hi")) # True Notes
- Be careful with type casting — converting a non-numeric string like 'hello' to int will raise a ValueError.
