Variables in Python
Introduction
- The value in a variable may change during the life of the program-hence the name “variable”.
Definition
- A variable is a memory container with a certain name that holds a temporary value for later use.
- A variable is a container that reserves memory to hold values of a specific data type.
Characteristics of Variables in Python
- The variable’s value can be a number, text, list, or any other type of data.
- Variables do not need explicit declaration; we just assign a value, and the variable is created.
- Python variables don’t have a fixed/static/pre-defined data type.
- Python variables are dynamically typed, meaning we don’t need to mention the data type earlier; rather, Python figures it out automatically. Python variables automatically assign a datatype at runtime.
- Example: x = 5 (integer), then later x = “hello” (string).
- Variable names must include letters, numbers, and underscores, but cannot start with a number.
- It does not contain any symbols or spaces in the variable name.
- Valid: student_name, age1
- Invalid: 1student, name@
- Python variables are case-sensitive, so Name and name are different variables.
Types of Variables in Python
- Global Variables – Declared outside functions and can be used anywhere in the program.
- Local Variables – Declared inside functions and can only be used within those functions.
- Constants – Values that should not change, usually written in capital letters conventionally (e.g.,
PI = 3.14
).
Advantages of Using Variables
- Reusability – We can store a value once and use it multiple times without rewriting it.
- Clarity – Meaningful variable names make the program easy to understand.
- Flexibility – Since Python allows dynamic typing, a variable can change its value type.
Disadvantages or Limitations
- Dynamic typing can confuse – Accidentally reassigning a variable to a different type might lead to errors. For example:
x = 5
, laterx = "five"
— may confuse readers or cause bugs. - Overuse of global variables can make debugging and maintenance harder.
- Memory issues can occur if unnecessary variables are kept alive without being cleared.
Examples of Variables in Python
-
# Storing numbers :- score = 100# Storing text:- username = “Rahul”Storing decimal numbers:- temperature = 36.6# Storing a list:- fruits = [“apple”, “banana”, “mango”]# Changing value of a variable:- score = 120
-
Multiple Variable Assignment
- Python allows to initialization of more than one variable in a single statement.
- For example –
- (i) a=b=c=40 print (a,b,c) Output: 40 40 40
- (ii) a,b,c = 10,20,30 print (a,b,c) Output: 10 20 30
DataTypes in Python
Introduction
- In Python, every piece of information we use—whether it’s a number, text, or list of items—has a type.
- Different kinds of data contain numbers, some include words, and others comprise collections of items.
Definition
- A data type in Python defines the nature of data stored in a variable.
Characteristics of Data Types in Python
- It tells Python whether the value is a number, a word, true/false, or even a group of multiple values.
- A data type tells Python what kind of value it is and how that value can be used.
- Python is dynamically typed, meaning we don’t need to declare a data type explicitly; Python figures it out automatically.
- Python has both primitive types (basic building blocks like numbers and strings) and non-primitive types (like lists and dictionaries).
- Data types decide what operations we can perform on a value. For example, we can add two numbers, but not two unrelated types like a number and text.
- Python allows type conversion, so we can convert values from one type to another using functions like
int()
,str()
, orfloat()
.
Categories of Python Data Types
Numeric Types
- The integer (int) type represents whole numbers, both positive and negative, without any decimal part. For example, if we write age = 25, Python understands that age is an integer because it is a complete number.
- The float type represents numbers that have a decimal point. For instance, if we write price = 199.99, Python treats this as a float because it contains a fractional part after the decimal.
- The complex type is used when numbers have both a real part and an imaginary part. For example, if we write z = 2 + 3j, Python recognizes this as a complex number where 2 is the real part and 3j is the imaginary part.
Text Type
- The string (str) data type is used to store text information.
- A string in Python can contain letters, words, or even entire sentences, and it must be written inside either single quotes (‘…’) or double quotes (“…”).
- For example, when we write name = “Rahul”, Python treats the value “Rahul” as a string because it is text.
- Strings can be used to display messages, store names, or hold any other textual data.
Boolean Type
- The boolean (bool) type is used when we need to represent truth values.
- It can only have two possible values: True or False.
- It’s often used in conditions and decision-making.
- For example, if we write attendance = True, Python stores the fact that the user is present/attendance as a truth value.
- Booleans are often used in conditions, such as deciding whether a program should continue or stop, based on whether something is true or false.
Sequence Types
- Python provides special data types that allow us to store multiple items in a particular order. These are called sequence types. These are –
- List :
- A list is an ordered and changeable collection of items.
- We can add, remove, or change elements inside a list.
- For example, fruits = [“apple”, “banana”, “cherry”] is a list that contains three fruit names, and we can later add another fruit, like “mango”, to the same list when needed.
- Tuple :
- A tuple is also an ordered collection of items, but it is unchangeable, meaning once we create it, we cannot modify its contents.
- For instance, dimensions = (10, 20, 30) is a tuple that holds three numbers, and we cannot add or remove items from it later.
- Range :
- A range is a sequence that represents a series of numbers, often used in loops.
- For example, numbers = range(5) means numbers from 0 up to 4.
- List :
Mapping Type
- The dictionary (dict) is a data type in Python that stores information in the form of key-value pairs.
- This is similar to a real-life dictionary where a word (the key) has a definition (the value).
- For example, if we write student = {“name”: “Rahul”, “age”: 21, “grade”: “A”}, Python stores the student’s details where “name”, “age”, and “grade” are keys, and “Rahul”, 21, and “A” are their respective values.
- Dictionaries are very useful for organizing data that belongs together.
Set Types
- Python also provides a way to store collections of unique items using sets.
- A set is an unordered collection that automatically removes duplicate values. For example, if we write unique_numbers = {1, 2, 3, 3, 2}, Python will store only {1, 2, 3} because sets do not allow repetition.
- A frozenset is similar to a set, but once created, it cannot be modified. For example, frozen = frozenset([4, 5, 6]) creates an unchangeable collection of numbers.
Binary Types
Python also includes data types for handling binary data, which is often used in low-level programming, file handling, or communication with hardware.
- Bytes :
- The bytes type is an immutable sequence of bytes.
- For example, data = b”hello” creates a series of bytes that represent the word “hello”.
- Bytearray :
- The bytearray type is similar to bytes, but it is mutable, meaning we can change its contents after creating it.
- For instance, arr = bytearray([65, 66]) creates a byte array with values corresponding to ASCII letters.
- memoryview :
- The memoryview type allows us to access and manipulate the memory of binary data directly, which can be useful for performance-sensitive tasks.
None Type
- It represents the absence of a value or a null value.
- Used to define a variable with no value or to signify an empty return.
- For example:- x = None # Here, x is a None Type.
Advantages of Data Types in Python
- They make programs more organized by clearly defining the type of information.
- They allow efficient memory management since Python knows how much space a value needs.
- They provide flexibility because we can convert one type into another when needed.
- They allow Python to perform operations safely, like adding numbers or joining strings.
Disadvantages or Limitations
- Dynamic typing can sometimes cause bugs if a variable changes to an unexpected type.
- Type errors may happen when we try to mix incompatible data types (e.g., adding a string to a number).
- Some data types (like lists) can use more memory compared to simpler data types.
Type Casting/Type Conversion Variables in Python
- Type casting refers to converting an object/data type of one type into another. It is of two types –
- Implicit/Automatic/Direct Type Casting:
- When any language compiler/interpreter automatically converts an object of one type into another, it is called automatic or implicit casting.
- For example, an integer object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because of its fractional part contents. Hence, the Python interpreter doesn’t automatically convert a float to an int, because it will result in loss of data. On the other hand, int can be easily converted into a float by setting its fractional part to 0 (implicit or automatic conversion).
- Explicit/Indirect Type Casting:
- To do this Casting, we use Python’s built-in functions int(), float(), and str() to perform explicit conversions, such as string to integer.
- We can specify the data type of a variable as needed with the help of a suitable data type in the casting process.
- For example –
- x = str(10) # In this case, x will be ’10’, i.e., String value.
- y = int(10) # In this case, y will be 10, i.e., an Integer value.
- z = float(10) # In this case, z will be 10.0, i.e., a Float value.
- Implicit/Automatic/Direct Type Casting:
0 Comments