4.Variables and Data Types in Python
Understanding variables and data types is fundamental to programming in Python. This tutorial explains what variables are, how to declare them, rules for naming, and provides an overview of Python’s built-in data types with examples.
What is a Variable?
A variable is a named storage that holds data. In Python, variables are created when you assign a value to a name. Unlike some languages, Python does not require explicit declaration of variable types.
Example:
x = 10
name = ‘Alice’
price = 19.99
Rules for Naming Variables
- Variable names must start with a letter or underscore (_).
- They cannot start with a digit.
- Names can contain letters, digits, and underscores.
- Variable names are case-sensitive (age and Age are different).
- Avoid using Python keywords as variable names.
Python Data Types Overview
Python has several built-in data types. Here are the most commonly used ones:
int (Integer)
Represents whole numbers.
Example:
count = 42
float (Floating Point)
Represents decimal numbers.
Example:
price = 19.99
str (String)
Represents text.
Example:
bool (Boolean)
Represents True or False values.
Example:
is_active = True
list
Ordered, mutable collection.
Example:
fruits = [‘apple’, ‘banana’, ‘cherry’]
tuple
Ordered, immutable collection.
Example:
coordinates = (10, 20)
dict (Dictionary)
Collection of key-value pairs.
Example:
student = {‘name’: ‘Alice’, ‘age’: 21}
set
Unordered collection of unique elements.
Example:
unique_numbers = {1, 2, 3}
Conclusion
Variables and data types form the foundation of Python programming. Understanding how to use them effectively will help you write clear and efficient code.