Lesson 2.2: Variables and Data Types
Introduction:
Variables are used to store data in a program, and Python allows you to work with different types of data efficiently. Understanding variables and data types is fundamental to writing Python programs.
1. Variables in Python:
-
A variable is a name assigned to a value.
-
No need to declare the data type explicitly (Python is dynamically typed).
-
Variable names must follow these rules:
-
Must start with a letter or underscore
_ -
Can contain letters, digits, and underscores
-
Cannot be a Python keyword
-
Case-sensitive (
name≠Name)
-
Example:
2. Data Types in Python:
Python provides several built-in data types:
-
Numeric Types:
-
int(Integer): Whole numbers -
float(Floating-point): Decimal numbers -
complex: Complex numbers
-
-
Text Type:
-
str(String): Sequence of characters
-
-
Boolean Type:
-
bool: RepresentsTrueorFalse
-
-
Sequence Types:
-
list,tuple,range(covered in advanced lessons)
-
-
Set Types:
-
set,frozenset
-
-
Mapping Type:
-
dict(Dictionary)
-
3. Checking Data Types:
-
Use the
type()function to find the type of a variable.
4. Type Conversion:
-
Convert one data type to another using functions like
int(),float(),str().
Practical Tip:
-
Use meaningful variable names to make code readable.
-
Keep track of data types to avoid errors in calculations and logic.
Learning Outcome of This Lesson:
-
Understand what variables are and how to use them
-
Learn different Python data types and their applications
-
Check and convert data types effectively
-
Write simple programs using variables and basic data types
