Python Variables & Data Types
Learn how to store information in variables and understand Python’s basic data types.
Introduction
In Python, a variable is like a container that holds data. You give the container a name, and then you can use that name to access the data later. The kind of data a variable stores is called its data type.
Creating a Variable
You don’t need to declare variable types in Python — just assign a value using =.
# Assigning values to variables
name = "Alice"
age = 25
height = 5.6
print(name)
print(age)
print(height)
Output:
Alice
25
5.6
Common Data Types
Python has many data types, but here are the most common ones:
- String (
str): text data - Integer (
int): whole numbers - Float (
float): decimal numbers - Boolean (
bool): True or False
# Examples of data types
greeting = "Hello" # str
year = 2025 # int
price = 19.99 # float
is_student = True # bool
print(type(greeting))
print(type(year))
print(type(price))
print(type(is_student))
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
Common Mistakes
-
Using invalid variable names:
2name = "Bob" # ❌ Error: variable names cannot start with numbersSyntaxError: invalid syntax -
Forgetting quotes for strings:
city = London # ❌ WrongNameError: name 'London' is not defined✅ Correct:
city = "London" -
Case sensitivity: Variables are case-sensitive.
Name = "Alice" print(name) # ❌ ErrorNameError: name 'name' is not defined✅ Correct:
print(Name) # Works fine
Deeper Insights
- You can assign the same value to multiple variables at once:
x = y = z = 100
print(x, y, z)
a, b, c = 1, 2, 3
print(a, b, c)
age = 25
age = "twenty five"
print(age)
💡 Try It Yourself
- Create a variable
countrywith your country’s name and print it. - Create two variables,
lengthandwidth, assign them values, and print their product. - Try assigning one variable’s value to another and print both.
- What happens if you do
number = "10"and then tryprint(number + 5)? (Hint: data types matter!)
What’s Next?
Now that you understand variables and data types, you’re ready to explore Operators in Python — the tools that let you do math and logic with variables.
You can run the codes here and practice:
No comments:
Post a Comment