Introduction
In Python, variables are used to store data values. A variable is essentially a name given to a memory location that stores the value. Data types define the type of data a variable can hold, such as numbers, strings, and more. Python is a dynamically typed language, meaning you do not need to declare the type of a variable when you create it. This makes Python programming easier and more flexible for beginners and professionals alike.
Objective
The objective of this topic is to help you understand how to declare and use variables in Python, as well as how to work with different data types. By the end of this lesson, you’ll be able to:
- Understand what variables are in Python.
- Identify different data types in Python.
- Assign values to variables in Python.
Code Example
# Python program to demonstrate variables and data types # Assigning values to variables integer_variable = 10 float_variable = 10.5 string_variable = "Hello, Python!" boolean_variable = True # Printing variables and their types print("Integer Variable:", integer_variable, "- Type:", type(integer_variable)) print("Float Variable:", float_variable, "- Type:", type(float_variable)) print("String Variable:", string_variable, "- Type:", type(string_variable)) print("Boolean Variable:", boolean_variable, "- Type:", type(boolean_variable))
Explanation of the Program Structure
In this Python program:
- We first declare variables of different data types: integer, float, string, and boolean.
- We then print the value of each variable along with its type using the built-in
type()
function. This function returns the data type of the variable.
The print()
function is used to display the variable values and their types on the screen. The type()
function automatically determines the type of each variable.
How to Run the Program
To run this Python program, follow these steps:
- Open a text editor (like VSCode, PyCharm, or a simple text editor).
- Copy and paste the code into a new file and save it with a
.py
extension, such asvariable_demo.py
. - Open the terminal or command prompt on your computer.
- Navigate to the folder where your Python file is saved.
- Type
python variable_demo.py
and hitEnter
to execute the program.
After running the program, you should see the output printed to the terminal with the values of the variables and their respective data types.