What are Variables?
A variable in Python acts as a container for storing data. It is a name given to a memory location where data is stored. The Variables make it easier to manage and manipulate data in a program.Key Features of Python Variables:
- Dynamic Typing: Python variables do not need explicit declaration; their type is determined automatically based on the value assigned.
- Case-Sensitive: The Variable names are case-sensitive (e.g., Age and age are different).
- No Type Declaration: Unlike some other programming languages, Python does not require the declaration of the type of variable.
How to Declare a Variable in Python
In Python, declaring a variable is as simple as assigning the value using the = operator:# Example of variable assignment
name = "Alice" # String
age = 25 # Integer
is_student = True # Boolean
In the above example:
In the above example:
- name is assigned a string value "Alice".
- age is assigned an integer value 25.
- is_student is assigned a boolean value True.
Rules for Naming Variables
To ensure that your code is readable and avoids errors follow these naming rules:1) Start with a Letter or Underscore: A variable name must begin with the letter (a-z, A-Z) or an underscore (_).
- Valid: my_var, _temp
- Invalid: 1variable, -name
- Example: my_variable_name
- Invalid: for = 10
- Example: myVar and myvar are different.
Variable Types in Python
Python supports multiple data types and variables can hold any of these types. The Common types include:- Integer (int): Whole numbers.
x = 10
- Floating Point (float): Decimal numbers.
pi = 3.14
- String (str): Text values.
greeting = "Hello, World!"
- Boolean (bool): True or False values.
is_ready = True
- List: Ordered, mutable collections.
fruits = ["apple", "banana", "cherry"]
- Tuple: Ordered, immutable collections.
coordinates = (10, 20)
- Dictionary (dict): Key-value pairs.
0 Comments