Variables and Data Types
Variables and data types are fundamental concepts in Python programming. In this tutorial, we will explore how variables are used to store data and the various data types available in Python.
Variables
In Python, a variable is a name that represents a value stored in the computer’s memory. You can assign different types of data to variables, and Python will automatically determine the data type based on the assigned value.
Variable Assignment
Variable assignment is done using the equal sign (=) operator.
# Assigning an integer to a variable
age = 25
# Assigning a string to a variable
name = "John Doe"
# Assigning a float to a variable
pi = 3.14
# Assigning a boolean to a variable
is_student = True
Variable Naming Rules
When naming variables in Python, you need to follow certain rules:
- The name must start with a letter (a-z, A-Z) or an underscore (_).
- The rest of the name can contain letters, digits (0-9), or underscores.
- Variable names are case-sensitive, so age, Age, and AGE are considered different variables.
It is also advisable to use descriptive names for variables to make the code more readable and understandable.
Constant Naming Convention
A constant is a special type of variable whose value cannot be changed. However, although Python does not support constants, we still name constants in all capital letters to separate them from variables.
PI = 3.14
APPLE_COLOR = "Red"
Data Types
Python is a dynamically typed language, meaning that you don’t need to specify the data type of a variable explicitly. Python automatically determines the data type based on the assigned value. Here are some common data types in Python:
Numeric Types
-
Integer (
int): Represents whole numbers, such as 5, -10, 0. -
Float (
float): Represents real numbers with decimal points, such as 3.14, -2.5, 0.0.
Text Type
-
String (
str): Represents sequences of characters enclosed in single or double quotes, such as "Hello", 'Python', "42".
Boolean Type
-
Boolean (
bool): Represents either True or False. Used for logical operations and control flow.
Collection Types
-
List (
list): Represents an ordered collection of elements, enclosed in square brackets []. -
Tuple (
tuple): Similar to lists, but immutable (cannot be changed after creation), enclosed in parentheses (). -
Set (
set): Represents an unordered collection of unique elements, enclosed in curly braces {}. -
Dictionary (
dict): Represents a collection of key-value pairs, enclosed in curly braces {}.
Type Casting
You can convert variables from one data type to another using type casting.
# Converting a float to an integer
num_float = 3.14
num_int = int(num_float) # num_int will be 3
# Converting an integer to a string
number = 42
number_str = str(number) # number_str will be "42"