Variables are a crucial concept in any programming language. In Python, variables are used to store and manage data, allowing us to perform operations on that data as needed. Let’s dive into the concepts of variables and how they work in Python.
2.1.1 What is a Variable?
A variable in Python is a symbolic name that holds a reference to a value. Variables store data that can be referenced and manipulated throughout a program.
- Variables can store different types of data, such as numbers, strings, lists, etc.
- The value of a variable can change over time.
x = 10 # Variable 'x' holds the integer value 10 name = "Alice" # Variable 'name' holds the string "Alice"
In this example:
x
is a variable storing the integer value10
.name
is a variable storing the string"Alice"
.
2.1.2 Declaring and Assigning Values to Variables
In Python, you do not need to explicitly declare the data type of a variable. Variables are dynamically typed, which means the type is inferred when a value is assigned to the variable.
- Assignment operator: The
=
symbol is used to assign a value to a variable.
Example :
age = 25 # Assigning an integer value greeting = "Hello" # Assigning a string value price = 19.99 # Assigning a float valueYou can also change the value of a variable later in the program. Python allows reassignment of variables to different types of data.
x = 5 # Initially, x is an integer x = "Now I'm a string" # Now, x is reassigned to a string
0 Comments